refactor: extract shared client utilities

- Add src/lib/client/clipboard.ts with CopyFeedback class
- Add src/lib/client/validation.ts with createErrorDisplay and isInteger
- Add src/lib/client/animations.ts with popElement
- Refactor NumberGenerator, LotteryGenerator, PasswordGenerator,
  ListGenerator, CardGenerator, CoinGenerator, UuidGenerator,
  WheelSpinner to use shared utilities
- Leave DiceGenerator and ColorGenerator untouched (complex patterns)
This commit is contained in:
emil
2026-05-10 20:56:33 +03:00
parent f1ba82735b
commit 56ab3f6952
11 changed files with 1921 additions and 1218 deletions
+154 -70
View File
@@ -1,13 +1,17 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="card-generator" class="mt-8"> <div id="card-generator" class="mt-8">
<div class="flex flex-col sm:flex-row gap-4 items-end"> <div class="flex flex-col sm:flex-row gap-4 items-end">
<div class="flex-1"> <div class="flex-1">
<label for="crd-count" class="block text-sm font-medium text-zinc-400 mb-1">{T.cardsToDraw}</label> <label
for="crd-count"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.cardsToDraw}</label
>
<input <input
id="crd-count" id="crd-count"
type="number" type="number"
@@ -18,13 +22,18 @@ const T = useT(isRu ? 'ru' : 'en');
aria-label={T.cardsToDraw} aria-label={T.cardsToDraw}
/> />
</div> </div>
<label class="flex items-center gap-2.5 cursor-pointer select-none group pb-2"> <label
class="flex items-center gap-2.5 cursor-pointer select-none group pb-2"
>
<input <input
id="crd-replace" id="crd-replace"
type="checkbox" type="checkbox"
class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer" class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer"
/> />
<span class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors">{T.allowDuplicates}</span> <span
class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors"
>{T.allowDuplicates}</span
>
</label> </label>
</div> </div>
@@ -33,7 +42,8 @@ const T = useT(isRu ? 'ru' : 'en');
role="alert" role="alert"
aria-live="polite" aria-live="polite"
class="mt-3 text-sm text-red-500 hidden" class="mt-3 text-sm text-red-500 hidden"
></p> >
</p>
<div class="my-10 min-h-32 flex flex-col items-center justify-center gap-4"> <div class="my-10 min-h-32 flex flex-col items-center justify-center gap-4">
<div <div
@@ -41,7 +51,8 @@ const T = useT(isRu ? 'ru' : 'en');
class="flex flex-wrap justify-center gap-2" class="flex flex-wrap justify-center gap-2"
aria-live="polite" aria-live="polite"
aria-label="Drawn cards" aria-label="Drawn cards"
></div> >
</div>
<button <button
id="crd-copy-btn" id="crd-copy-btn"
@@ -51,14 +62,41 @@ const T = useT(isRu ? 'ru' : 'en');
> >
<span id="crd-copy-label">{T.copy}</span> <span id="crd-copy-label">{T.copy}</span>
<span id="crd-copy-icon" aria-hidden="true"> <span id="crd-copy-icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/> xmlns="http://www.w3.org/2000/svg"
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/> width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect>
<path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path>
</svg> </svg>
</span> </span>
<span id="crd-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> id="crd-check-icon"
<path d="M20 6 9 17l-5-5"/> class="hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5"></path>
</svg> </svg>
</span> </span>
</button> </button>
@@ -76,53 +114,97 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const COPY_LABEL = isRu ? 'Копировать' : 'Copy'; import { createErrorDisplay } from "@/lib/client/validation";
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const ERR_AT_LEAST = isRu ? 'Вытащите хотя бы 1 карту.' : 'Draw at least 1 card.';
const ERR_UNIQUE = isRu ? 'Нельзя вытащить более 52 уникальных карт.' : 'Cannot draw more than 52 unique cards.';
const ERR_MAX52 = isRu ? 'Максимум 52 карты одновременно.' : 'Maximum 52 cards at once.';
const countInput = document.getElementById('crd-count') as HTMLInputElement; const isRu = document.documentElement.lang === "ru";
const replaceCb = document.getElementById('crd-replace') as HTMLInputElement; const COPY_LABEL = isRu ? "Копировать" : "Copy";
const btn = document.getElementById('crd-btn') as HTMLButtonElement; const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
const copyBtn = document.getElementById('crd-copy-btn') as HTMLButtonElement; const ERR_AT_LEAST = isRu
const cardsEl = document.getElementById('crd-cards') as HTMLDivElement; ? "Вытащите хотя бы 1 карту."
const errorEl = document.getElementById('crd-error') as HTMLParagraphElement; : "Draw at least 1 card.";
const copyLabel = document.getElementById('crd-copy-label') as HTMLSpanElement; const ERR_UNIQUE = isRu
const copyIcon = document.getElementById('crd-copy-icon') as HTMLSpanElement; ? "Нельзя вытащить более 52 уникальных карт."
const checkIcon = document.getElementById('crd-check-icon') as HTMLSpanElement; : "Cannot draw more than 52 unique cards.";
const ERR_MAX52 = isRu
? "Максимум 52 карты одновременно."
: "Maximum 52 cards at once.";
const RANKS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']; const countInput = document.getElementById("crd-count") as HTMLInputElement;
const replaceCb = document.getElementById(
"crd-replace",
) as HTMLInputElement;
const btn = document.getElementById("crd-btn") as HTMLButtonElement;
const copyBtn = document.getElementById(
"crd-copy-btn",
) as HTMLButtonElement;
const cardsEl = document.getElementById("crd-cards") as HTMLDivElement;
const errorEl = document.getElementById(
"crd-error",
) as HTMLParagraphElement;
const copyLabel = document.getElementById(
"crd-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById(
"crd-copy-icon",
) as HTMLSpanElement;
const checkIcon = document.getElementById(
"crd-check-icon",
) as HTMLSpanElement;
const RANKS = [
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
];
const SUITS = [ const SUITS = [
{ symbol: '♠', label: 'Spades', red: false }, { symbol: "♠", label: "Spades", red: false },
{ symbol: '♥', label: 'Hearts', red: true }, { symbol: "♥", label: "Hearts", red: true },
{ symbol: '♦', label: 'Diamonds', red: true }, { symbol: "♦", label: "Diamonds", red: true },
{ symbol: '♣', label: 'Clubs', red: false }, { symbol: "♣", label: "Clubs", red: false },
]; ];
const DECK = SUITS.flatMap((suit) => const DECK = SUITS.flatMap((suit) => RANKS.map((rank) => ({ rank, suit })));
RANKS.map((rank) => ({ rank, suit }))
);
let lastCards: { rank: string; suit: typeof SUITS[number] }[] = []; let lastCards: { rank: string; suit: (typeof SUITS)[number] }[] = [];
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null;
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); } const errors = createErrorDisplay(errorEl);
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); } const clipboard = new CopyFeedback(copyIcon, checkIcon);
function draw() { function draw() {
const count = parseInt(countInput.value, 10); const count = parseInt(countInput.value, 10);
const withReplacement = replaceCb.checked; const withReplacement = replaceCb.checked;
if (!Number.isInteger(count) || count < 1) { showError(ERR_AT_LEAST); return; } if (!Number.isInteger(count) || count < 1) {
if (!withReplacement && count > 52) { showError(ERR_UNIQUE); return; } errors.show(ERR_AT_LEAST);
if (count > 52) { showError(ERR_MAX52); return; } return;
}
if (!withReplacement && count > 52) {
errors.show(ERR_UNIQUE);
return;
}
if (count > 52) {
errors.show(ERR_MAX52);
return;
}
clearError(); errors.clear();
if (withReplacement) { if (withReplacement) {
lastCards = Array.from({ length: count }, () => DECK[Math.floor(Math.random() * DECK.length)]); lastCards = Array.from(
{ length: count },
() => DECK[Math.floor(Math.random() * DECK.length)],
);
} else { } else {
const deck = [...DECK]; const deck = [...DECK];
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
@@ -133,31 +215,33 @@ const T = useT(isRu ? 'ru' : 'en');
} }
renderCards(); renderCards();
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
} }
function renderCards() { function renderCards() {
cardsEl.innerHTML = ''; cardsEl.innerHTML = "";
lastCards.forEach(({ rank, suit }) => { lastCards.forEach(({ rank, suit }) => {
const card = document.createElement('div'); const card = document.createElement("div");
card.setAttribute('aria-label', `${rank} of ${suit.label}`); card.setAttribute("aria-label", `${rank} of ${suit.label}`);
card.className = [ card.className = [
'flex flex-col items-center justify-between w-14 h-20 rounded-lg border px-1.5 py-1.5', "flex flex-col items-center justify-between w-14 h-20 rounded-lg border px-1.5 py-1.5",
'bg-zinc-900 border-zinc-700 select-none', "bg-zinc-900 border-zinc-700 select-none",
suit.red ? 'text-red-400' : 'text-zinc-100', suit.red ? "text-red-400" : "text-zinc-100",
].join(' '); ].join(" ");
const top = document.createElement('div'); const top = document.createElement("div");
top.className = 'w-full text-left text-sm font-bold leading-none tabular-nums'; top.className =
"w-full text-left text-sm font-bold leading-none tabular-nums";
top.textContent = rank; top.textContent = rank;
const mid = document.createElement('div'); const mid = document.createElement("div");
mid.className = 'text-2xl leading-none'; mid.className = "text-2xl leading-none";
mid.textContent = suit.symbol; mid.textContent = suit.symbol;
const bot = document.createElement('div'); const bot = document.createElement("div");
bot.className = 'w-full text-right text-sm font-bold leading-none tabular-nums rotate-180'; bot.className =
"w-full text-right text-sm font-bold leading-none tabular-nums rotate-180";
bot.textContent = rank; bot.textContent = rank;
card.append(top, mid, bot); card.append(top, mid, bot);
@@ -167,22 +251,22 @@ const T = useT(isRu ? 'ru' : 'en');
async function copyCards() { async function copyCards() {
if (!lastCards.length) return; if (!lastCards.length) return;
const text = lastCards.map(({ rank, suit }) => `${rank}${suit.symbol}`).join(', '); const text = lastCards
.map(({ rank, suit }) => `${rank}${suit.symbol}`)
.join(", ");
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
}, 1500); }, 1500);
} }
btn.addEventListener('click', draw); btn.addEventListener("click", draw);
copyBtn.addEventListener('click', copyCards); copyBtn.addEventListener("click", copyCards);
countInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') draw(); }); countInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") draw();
});
</script> </script>
+105 -53
View File
@@ -1,14 +1,19 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="coin-generator" class="mt-8"> <div id="coin-generator" class="mt-8">
<div> <div>
<div class="flex items-center justify-between mb-1"> <div class="flex items-center justify-between mb-1">
<label for="coin-count" class="text-sm font-medium text-zinc-400">{T.numberOfCoins}</label> <label for="coin-count" class="text-sm font-medium text-zinc-400"
<span id="coin-count-val" class="text-sm font-semibold tabular-nums text-zinc-100">1</span> >{T.numberOfCoins}</label
>
<span
id="coin-count-val"
class="text-sm font-semibold tabular-nums text-zinc-100">1</span
>
</div> </div>
<input <input
id="coin-count" id="coin-count"
@@ -19,7 +24,9 @@ const T = useT(isRu ? 'ru' : 'en');
class="w-full accent-[#534AB7] cursor-pointer" class="w-full accent-[#534AB7] cursor-pointer"
aria-label={T.numberOfCoins} aria-label={T.numberOfCoins}
/> />
<div class="flex justify-between text-xs text-zinc-600 mt-1 select-none"> <div
class="flex justify-between text-xs text-zinc-600 mt-1 select-none"
>
<span>1</span><span>20</span> <span>1</span><span>20</span>
</div> </div>
</div> </div>
@@ -30,9 +37,14 @@ const T = useT(isRu ? 'ru' : 'en');
class="flex flex-wrap justify-center gap-2" class="flex flex-wrap justify-center gap-2"
aria-live="polite" aria-live="polite"
aria-label="Coin results" aria-label="Coin results"
></div> >
</div>
<div id="coin-summary" class="hidden text-sm text-zinc-500 tabular-nums"></div> <div
id="coin-summary"
class="hidden text-sm text-zinc-500 tabular-nums"
>
</div>
<button <button
id="coin-copy-btn" id="coin-copy-btn"
@@ -42,14 +54,41 @@ const T = useT(isRu ? 'ru' : 'en');
> >
<span id="coin-copy-label">{T.copy}</span> <span id="coin-copy-label">{T.copy}</span>
<span id="coin-copy-icon" aria-hidden="true"> <span id="coin-copy-icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/> xmlns="http://www.w3.org/2000/svg"
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/> width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect>
<path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path>
</svg> </svg>
</span> </span>
<span id="coin-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> id="coin-check-icon"
<path d="M20 6 9 17l-5-5"/> class="hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5"></path>
</svg> </svg>
</span> </span>
</button> </button>
@@ -67,30 +106,45 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const COPY_LABEL = isRu ? 'Копировать' : 'Copy';
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const HEADS_LABEL = isRu ? 'О' : 'H';
const TAILS_LABEL = isRu ? 'Р' : 'T';
const HEADS_WORD = isRu ? 'орёл' : 'Heads';
const TAILS_WORD = isRu ? 'решка' : 'Tails';
const HEADS_SUMMARY = isRu ? 'орёл' : 'heads';
const TAILS_SUMMARY = isRu ? 'решка' : 'tails';
const countInput = document.getElementById('coin-count') as HTMLInputElement; const isRu = document.documentElement.lang === "ru";
const countVal = document.getElementById('coin-count-val') as HTMLSpanElement; const COPY_LABEL = isRu ? "Копировать" : "Copy";
const btn = document.getElementById('coin-btn') as HTMLButtonElement; const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
const copyBtn = document.getElementById('coin-copy-btn') as HTMLButtonElement; const HEADS_LABEL = isRu ? "О" : "H";
const coinsEl = document.getElementById('coin-coins') as HTMLDivElement; const TAILS_LABEL = isRu ? "Р" : "T";
const summaryEl = document.getElementById('coin-summary') as HTMLDivElement; const HEADS_WORD = isRu ? "орёл" : "Heads";
const copyLabel = document.getElementById('coin-copy-label') as HTMLSpanElement; const TAILS_WORD = isRu ? "решка" : "Tails";
const copyIcon = document.getElementById('coin-copy-icon') as HTMLSpanElement; const HEADS_SUMMARY = isRu ? "орёл" : "heads";
const checkIcon = document.getElementById('coin-check-icon') as HTMLSpanElement; const TAILS_SUMMARY = isRu ? "решка" : "tails";
const countInput = document.getElementById(
"coin-count",
) as HTMLInputElement;
const countVal = document.getElementById(
"coin-count-val",
) as HTMLSpanElement;
const btn = document.getElementById("coin-btn") as HTMLButtonElement;
const copyBtn = document.getElementById(
"coin-copy-btn",
) as HTMLButtonElement;
const coinsEl = document.getElementById("coin-coins") as HTMLDivElement;
const summaryEl = document.getElementById("coin-summary") as HTMLDivElement;
const copyLabel = document.getElementById(
"coin-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById(
"coin-copy-icon",
) as HTMLSpanElement;
const checkIcon = document.getElementById(
"coin-check-icon",
) as HTMLSpanElement;
let lastResults: boolean[] = []; let lastResults: boolean[] = [];
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null;
countInput.addEventListener('input', () => { const clipboard = new CopyFeedback(copyIcon, checkIcon);
countInput.addEventListener("input", () => {
countVal.textContent = countInput.value; countVal.textContent = countInput.value;
}); });
@@ -101,48 +155,46 @@ const T = useT(isRu ? 'ru' : 'en');
const heads = lastResults.filter(Boolean).length; const heads = lastResults.filter(Boolean).length;
const tails = count - heads; const tails = count - heads;
coinsEl.innerHTML = ''; coinsEl.innerHTML = "";
lastResults.forEach((isHeads) => { lastResults.forEach((isHeads) => {
const coin = document.createElement('div'); const coin = document.createElement("div");
coin.setAttribute('aria-label', isHeads ? HEADS_WORD : TAILS_WORD); coin.setAttribute("aria-label", isHeads ? HEADS_WORD : TAILS_WORD);
coin.className = [ coin.className = [
'flex flex-col items-center justify-center w-14 h-14 rounded-full border-2 font-bold text-xs select-none', "flex flex-col items-center justify-center w-14 h-14 rounded-full border-2 font-bold text-xs select-none",
isHeads isHeads
? 'border-[#534AB7] bg-[#534AB7]/10 text-[#534AB7]' ? "border-[#534AB7] bg-[#534AB7]/10 text-[#534AB7]"
: 'border-zinc-600 bg-zinc-800 text-zinc-400', : "border-zinc-600 bg-zinc-800 text-zinc-400",
].join(' '); ].join(" ");
coin.textContent = isHeads ? HEADS_LABEL : TAILS_LABEL; coin.textContent = isHeads ? HEADS_LABEL : TAILS_LABEL;
coinsEl.appendChild(coin); coinsEl.appendChild(coin);
}); });
if (count > 1) { if (count > 1) {
summaryEl.textContent = `${heads} ${HEADS_SUMMARY} · ${tails} ${TAILS_SUMMARY}`; summaryEl.textContent = `${heads} ${HEADS_SUMMARY} · ${tails} ${TAILS_SUMMARY}`;
summaryEl.classList.remove('hidden'); summaryEl.classList.remove("hidden");
} else { } else {
summaryEl.classList.add('hidden'); summaryEl.classList.add("hidden");
} }
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
} }
async function copyResults() { async function copyResults() {
if (!lastResults.length) return; if (!lastResults.length) return;
const text = lastResults.map((h) => (h ? HEADS_WORD : TAILS_WORD)).join(', '); const text = lastResults
.map((h) => (h ? HEADS_WORD : TAILS_WORD))
.join(", ");
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
}, 1500); }, 1500);
} }
btn.addEventListener('click', flip); btn.addEventListener("click", flip);
copyBtn.addEventListener('click', copyResults); copyBtn.addEventListener("click", copyResults);
</script> </script>
+131 -59
View File
@@ -1,27 +1,37 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="list-generator" class="mt-8"> <div id="list-generator" class="mt-8">
<div class="flex flex-col gap-4"> <div class="flex flex-col gap-4">
<div> <div>
<label for="lst-items" class="block text-sm font-medium text-zinc-400 mb-1"> <label
{T.items} <span class="text-zinc-600">({T.itemsOneLine})</span> for="lst-items"
class="block text-sm font-medium text-zinc-400 mb-1"
>
{T.items}
<span class="text-zinc-600">({T.itemsOneLine})</span>
</label> </label>
<textarea <textarea
id="lst-items" id="lst-items"
rows="6" rows="6"
placeholder="Alice&#10;Bob&#10;Carol&#10;David" placeholder="Alice
Bob
Carol
David"
class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-sm font-mono focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors resize-y" class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-sm font-mono focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors resize-y"
aria-label={T.items} aria-label={T.items}></textarea>
></textarea>
</div> </div>
<div class="flex flex-col sm:flex-row gap-4 items-end"> <div class="flex flex-col sm:flex-row gap-4 items-end">
<div class="flex-1"> <div class="flex-1">
<label for="lst-pick" class="block text-sm font-medium text-zinc-400 mb-1">{T.pick}</label> <label
for="lst-pick"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.pick}</label
>
<input <input
id="lst-pick" id="lst-pick"
type="number" type="number"
@@ -31,13 +41,18 @@ const T = useT(isRu ? 'ru' : 'en');
aria-label={T.pick} aria-label={T.pick}
/> />
</div> </div>
<label class="flex items-center gap-2.5 cursor-pointer select-none group pb-2"> <label
class="flex items-center gap-2.5 cursor-pointer select-none group pb-2"
>
<input <input
id="lst-replace" id="lst-replace"
type="checkbox" type="checkbox"
class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer" class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer"
/> />
<span class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors">{T.allowDuplicates}</span> <span
class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors"
>{T.allowDuplicates}</span
>
</label> </label>
</div> </div>
</div> </div>
@@ -47,7 +62,8 @@ const T = useT(isRu ? 'ru' : 'en');
role="alert" role="alert"
aria-live="polite" aria-live="polite"
class="mt-3 text-sm text-red-500 hidden" class="mt-3 text-sm text-red-500 hidden"
></p> >
</p>
<div class="my-8 min-h-16 flex flex-col items-center justify-center gap-3"> <div class="my-8 min-h-16 flex flex-col items-center justify-center gap-3">
<div <div
@@ -55,7 +71,8 @@ const T = useT(isRu ? 'ru' : 'en');
class="flex flex-wrap justify-center gap-2" class="flex flex-wrap justify-center gap-2"
aria-live="polite" aria-live="polite"
aria-label="Picked items" aria-label="Picked items"
></div> >
</div>
<button <button
id="lst-copy-btn" id="lst-copy-btn"
@@ -65,14 +82,41 @@ const T = useT(isRu ? 'ru' : 'en');
> >
<span id="lst-copy-label">{T.copy}</span> <span id="lst-copy-label">{T.copy}</span>
<span id="lst-copy-icon" aria-hidden="true"> <span id="lst-copy-icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/> xmlns="http://www.w3.org/2000/svg"
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/> width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect>
<path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path>
</svg> </svg>
</span> </span>
<span id="lst-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> id="lst-check-icon"
<path d="M20 6 9 17l-5-5"/> class="hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5"></path>
</svg> </svg>
</span> </span>
</button> </button>
@@ -90,49 +134,81 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const COPY_LABEL = isRu ? 'Копировать' : 'Copy'; import { createErrorDisplay } from "@/lib/client/validation";
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const ERR_ADD_ONE = isRu ? 'Добавьте хотя бы один элемент в список.' : 'Add at least one item to the list.';
const ERR_PICK_ONE = isRu ? 'Выберите хотя бы 1 элемент.' : 'Pick at least 1 item.';
const itemsInput = document.getElementById('lst-items') as HTMLTextAreaElement; const isRu = document.documentElement.lang === "ru";
const pickInput = document.getElementById('lst-pick') as HTMLInputElement; const COPY_LABEL = isRu ? "Копировать" : "Copy";
const replaceCb = document.getElementById('lst-replace') as HTMLInputElement; const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
const btn = document.getElementById('lst-btn') as HTMLButtonElement; const ERR_ADD_ONE = isRu
const copyBtn = document.getElementById('lst-copy-btn') as HTMLButtonElement; ? "Добавьте хотя бы один элемент в список."
const resultEl = document.getElementById('lst-result') as HTMLDivElement; : "Add at least one item to the list.";
const errorEl = document.getElementById('lst-error') as HTMLParagraphElement; const ERR_PICK_ONE = isRu
const copyLabel = document.getElementById('lst-copy-label') as HTMLSpanElement; ? "Выберите хотя бы 1 элемент."
const copyIcon = document.getElementById('lst-copy-icon') as HTMLSpanElement; : "Pick at least 1 item.";
const checkIcon = document.getElementById('lst-check-icon') as HTMLSpanElement;
const itemsInput = document.getElementById(
"lst-items",
) as HTMLTextAreaElement;
const pickInput = document.getElementById("lst-pick") as HTMLInputElement;
const replaceCb = document.getElementById(
"lst-replace",
) as HTMLInputElement;
const btn = document.getElementById("lst-btn") as HTMLButtonElement;
const copyBtn = document.getElementById(
"lst-copy-btn",
) as HTMLButtonElement;
const resultEl = document.getElementById("lst-result") as HTMLDivElement;
const errorEl = document.getElementById(
"lst-error",
) as HTMLParagraphElement;
const copyLabel = document.getElementById(
"lst-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById(
"lst-copy-icon",
) as HTMLSpanElement;
const checkIcon = document.getElementById(
"lst-check-icon",
) as HTMLSpanElement;
let lastPicked: string[] = []; let lastPicked: string[] = [];
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null;
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); } const errors = createErrorDisplay(errorEl);
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); } const clipboard = new CopyFeedback(copyIcon, checkIcon);
function pick() { function pick() {
const items = itemsInput.value.split('\n').map((s) => s.trim()).filter(Boolean); const items = itemsInput.value
.split("\n")
.map((s) => s.trim())
.filter(Boolean);
const count = parseInt(pickInput.value, 10); const count = parseInt(pickInput.value, 10);
const withReplacement = replaceCb.checked; const withReplacement = replaceCb.checked;
if (items.length === 0) { showError(ERR_ADD_ONE); return; } if (items.length === 0) {
if (!Number.isInteger(count) || count < 1) { showError(ERR_PICK_ONE); return; } errors.show(ERR_ADD_ONE);
return;
}
if (!Number.isInteger(count) || count < 1) {
errors.show(ERR_PICK_ONE);
return;
}
if (!withReplacement && count > items.length) { if (!withReplacement && count > items.length) {
showError( errors.show(
isRu isRu
? `Нельзя выбрать ${count} уникальных элементов из списка ${items.length}.` ? `Нельзя выбрать ${count} уникальных элементов из списка ${items.length}.`
: `Cannot pick ${count} unique items from a list of ${items.length}.` : `Cannot pick ${count} unique items from a list of ${items.length}.`,
); );
return; return;
} }
clearError(); errors.clear();
if (withReplacement) { if (withReplacement) {
lastPicked = Array.from({ length: count }, () => items[Math.floor(Math.random() * items.length)]); lastPicked = Array.from(
{ length: count },
() => items[Math.floor(Math.random() * items.length)],
);
} else { } else {
const pool = [...items]; const pool = [...items];
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
@@ -142,38 +218,34 @@ const T = useT(isRu ? 'ru' : 'en');
lastPicked = pool.slice(0, count); lastPicked = pool.slice(0, count);
} }
resultEl.innerHTML = ''; resultEl.innerHTML = "";
lastPicked.forEach((item) => { lastPicked.forEach((item) => {
const chip = document.createElement('span'); const chip = document.createElement("span");
chip.textContent = item; chip.textContent = item;
chip.className = chip.className =
'inline-flex items-center px-3 py-1.5 rounded-full border border-[#534AB7]/40 bg-[#534AB7]/10 text-zinc-100 text-sm font-medium'; "inline-flex items-center px-3 py-1.5 rounded-full border border-[#534AB7]/40 bg-[#534AB7]/10 text-zinc-100 text-sm font-medium";
resultEl.appendChild(chip); resultEl.appendChild(chip);
}); });
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
} }
async function copyPicked() { async function copyPicked() {
if (!lastPicked.length) return; if (!lastPicked.length) return;
await navigator.clipboard.writeText(lastPicked.join(', ')); await navigator.clipboard.writeText(lastPicked.join(", "));
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
}, 1500); }, 1500);
} }
btn.addEventListener('click', pick); btn.addEventListener("click", pick);
copyBtn.addEventListener('click', copyPicked); copyBtn.addEventListener("click", copyPicked);
itemsInput.addEventListener('keydown', (e) => { itemsInput.addEventListener("keydown", (e) => {
if (e.key === 'Enter' && e.ctrlKey) pick(); if (e.key === "Enter" && e.ctrlKey) pick();
}); });
</script> </script>
+164 -56
View File
@@ -1,116 +1,224 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="lottery-generator" class="mt-8"> <div id="lottery-generator" class="mt-8">
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div> <div>
<label for="lg-from" class="block text-sm font-medium text-zinc-400 mb-1">{T.from}</label> <label
<input id="lg-from" type="number" value="1" class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors" /> for="lg-from"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.from}</label
>
<input
id="lg-from"
type="number"
value="1"
class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors"
/>
</div> </div>
<div> <div>
<label for="lg-to" class="block text-sm font-medium text-zinc-400 mb-1">{T.to}</label> <label
<input id="lg-to" type="number" value="49" class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors" /> for="lg-to"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.to}</label
>
<input
id="lg-to"
type="number"
value="49"
class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors"
/>
</div> </div>
<div> <div>
<label for="lg-pick" class="block text-sm font-medium text-zinc-400 mb-1">{T.pick}</label> <label
<input id="lg-pick" type="number" value="6" min="1" class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors" /> for="lg-pick"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.pick}</label
>
<input
id="lg-pick"
type="number"
value="6"
min="1"
class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-base focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors"
/>
</div> </div>
</div> </div>
<p id="lg-error" role="alert" aria-live="polite" class="mt-3 text-sm text-red-500 hidden"></p> <p
id="lg-error"
role="alert"
aria-live="polite"
class="mt-3 text-sm text-red-500 hidden"
>
</p>
<div class="my-10 min-h-24 flex flex-col items-center justify-center gap-4"> <div class="my-10 min-h-24 flex flex-col items-center justify-center gap-4">
<div id="lg-result" class="flex flex-wrap justify-center gap-2" aria-live="polite"></div> <div
<button id="lg-copy-btn" type="button" class="invisible inline-flex items-center gap-1.5 text-xs font-medium text-zinc-500 hover:text-zinc-200 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] rounded"> id="lg-result"
class="flex flex-wrap justify-center gap-2"
aria-live="polite"
>
</div>
<button
id="lg-copy-btn"
type="button"
class="invisible inline-flex items-center gap-1.5 text-xs font-medium text-zinc-500 hover:text-zinc-200 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] rounded"
>
<span id="lg-copy-label">{T.copy}</span> <span id="lg-copy-label">{T.copy}</span>
<span id="lg-copy-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg></span> <span id="lg-copy-icon" aria-hidden="true"
<span id="lg-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg></span> ><svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
><rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect><path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path></svg
></span
>
<span
id="lg-check-icon"
class="hidden text-[#534AB7]"
aria-hidden="true"
><svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
><path d="M20 6 9 17l-5-5"></path></svg
></span
>
</button> </button>
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<button id="lg-btn" type="button" class="w-full sm:w-auto px-8 py-3 bg-[#534AB7] text-white font-semibold rounded-lg hover:bg-[#4740a0] active:bg-[#3d3990] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 transition-colors duration-100 cursor-pointer"> <button
id="lg-btn"
type="button"
class="w-full sm:w-auto px-8 py-3 bg-[#534AB7] text-white font-semibold rounded-lg hover:bg-[#4740a0] active:bg-[#3d3990] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 transition-colors duration-100 cursor-pointer"
>
{T.draw} {T.draw}
</button> </button>
</div> </div>
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const ERR_INTEGERS = isRu ? 'Все значения должны быть целыми числами.' : 'All values must be whole numbers.'; import { createErrorDisplay, isInteger } from "@/lib/client/validation";
const ERR_FROM_TO = isRu ? '«От» должно быть меньше «До».' : '"From" must be less than "To".';
const ERR_PICK_MIN = isRu ? '«Выбрать» должно быть не менее 1.' : '"Pick" must be at least 1.';
const COPY_LABEL = isRu ? 'Копировать' : 'Copy';
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const fromInput = document.getElementById('lg-from') as HTMLInputElement; const isRu = document.documentElement.lang === "ru";
const toInput = document.getElementById('lg-to') as HTMLInputElement; const ERR_INTEGERS = isRu
const pickInput = document.getElementById('lg-pick') as HTMLInputElement; ? "Все значения должны быть целыми числами."
const btn = document.getElementById('lg-btn') as HTMLButtonElement; : "All values must be whole numbers.";
const copyBtn = document.getElementById('lg-copy-btn') as HTMLButtonElement; const ERR_FROM_TO = isRu
const resultEl = document.getElementById('lg-result') as HTMLDivElement; ? "«От» должно быть меньше «До»."
const errorEl = document.getElementById('lg-error') as HTMLParagraphElement; : '"From" must be less than "To".';
const copyLabel = document.getElementById('lg-copy-label') as HTMLSpanElement; const ERR_PICK_MIN = isRu
const copyIcon = document.getElementById('lg-copy-icon') as HTMLSpanElement; ? "«Выбрать» должно быть не менее 1."
const checkIcon = document.getElementById('lg-check-icon') as HTMLSpanElement; : '"Pick" must be at least 1.';
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null; const COPY_LABEL = isRu ? "Копировать" : "Copy";
const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
function isInteger(val: string) { return /^-?\d+$/.test(val.trim()); } const fromInput = document.getElementById("lg-from") as HTMLInputElement;
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); } const toInput = document.getElementById("lg-to") as HTMLInputElement;
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); } const pickInput = document.getElementById("lg-pick") as HTMLInputElement;
const btn = document.getElementById("lg-btn") as HTMLButtonElement;
const copyBtn = document.getElementById("lg-copy-btn") as HTMLButtonElement;
const resultEl = document.getElementById("lg-result") as HTMLDivElement;
const errorEl = document.getElementById("lg-error") as HTMLParagraphElement;
const copyLabel = document.getElementById(
"lg-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById("lg-copy-icon") as HTMLSpanElement;
const checkIcon = document.getElementById(
"lg-check-icon",
) as HTMLSpanElement;
const errors = createErrorDisplay(errorEl);
const clipboard = new CopyFeedback(copyIcon, checkIcon);
function draw() { function draw() {
if (!isInteger(fromInput.value) || !isInteger(toInput.value) || !isInteger(pickInput.value)) { showError(ERR_INTEGERS); return; } if (
!isInteger(fromInput.value) ||
!isInteger(toInput.value) ||
!isInteger(pickInput.value)
) {
errors.show(ERR_INTEGERS);
return;
}
const min = parseInt(fromInput.value, 10); const min = parseInt(fromInput.value, 10);
const max = parseInt(toInput.value, 10); const max = parseInt(toInput.value, 10);
const pick = parseInt(pickInput.value, 10); const pick = parseInt(pickInput.value, 10);
const pool = max - min + 1; const pool = max - min + 1;
if (min >= max) { showError(ERR_FROM_TO); return; } if (min >= max) {
if (pick < 1) { showError(ERR_PICK_MIN); return; } errors.show(ERR_FROM_TO);
if (pick > pool) {
showError(isRu ? `Нельзя выбрать ${pick} уникальных чисел из диапазона ${pool}.` : `Cannot pick ${pick} unique numbers from a range of ${pool}.`);
return; return;
} }
clearError(); if (pick < 1) {
errors.show(ERR_PICK_MIN);
return;
}
if (pick > pool) {
errors.show(
isRu
? `Нельзя выбрать ${pick} уникальных чисел из диапазона ${pool}.`
: `Cannot pick ${pick} unique numbers from a range of ${pool}.`,
);
return;
}
errors.clear();
const nums = Array.from({ length: pool }, (_, i) => min + i); const nums = Array.from({ length: pool }, (_, i) => min + i);
for (let i = 0; i < pick; i++) { for (let i = 0; i < pick; i++) {
const j = i + Math.floor(Math.random() * (pool - i)); const j = i + Math.floor(Math.random() * (pool - i));
[nums[i], nums[j]] = [nums[j], nums[i]]; [nums[i], nums[j]] = [nums[j], nums[i]];
} }
const picked = nums.slice(0, pick).sort((a, b) => a - b); const picked = nums.slice(0, pick).sort((a, b) => a - b);
resultEl.innerHTML = ''; resultEl.innerHTML = "";
picked.forEach((n) => { picked.forEach((n) => {
const ball = document.createElement('span'); const ball = document.createElement("span");
ball.textContent = String(n); ball.textContent = String(n);
ball.className = 'inline-flex items-center justify-center min-w-[2.5rem] h-10 px-2 rounded-full bg-[#534AB7]/15 border border-[#534AB7]/40 text-zinc-100 font-bold tabular-nums text-sm'; ball.className =
"inline-flex items-center justify-center min-w-[2.5rem] h-10 px-2 rounded-full bg-[#534AB7]/15 border border-[#534AB7]/40 text-zinc-100 font-bold tabular-nums text-sm";
resultEl.appendChild(ball); resultEl.appendChild(ball);
}); });
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
} }
async function copyNumbers() { async function copyNumbers() {
const balls = resultEl.querySelectorAll('span'); const balls = resultEl.querySelectorAll("span");
const value = Array.from(balls).map((b) => b.textContent).join(', '); const value = Array.from(balls)
.map((b) => b.textContent)
.join(", ");
if (!value) return; if (!value) return;
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
}, 1500); }, 1500);
} }
btn.addEventListener('click', draw); btn.addEventListener("click", draw);
copyBtn.addEventListener('click', copyNumbers); copyBtn.addEventListener("click", copyNumbers);
[fromInput, toInput, pickInput].forEach((input) => { [fromInput, toInput, pickInput].forEach((input) => {
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') draw(); }); input.addEventListener("keydown", (e) => {
if (e.key === "Enter") draw();
});
}); });
</script> </script>
+109 -53
View File
@@ -1,13 +1,17 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="number-generator" class="mt-8" data-ru={isRu ? '1' : '0'}> <div id="number-generator" class="mt-8" data-ru={isRu ? "1" : "0"}>
<div class="flex flex-col sm:flex-row gap-4"> <div class="flex flex-col sm:flex-row gap-4">
<div class="flex-1"> <div class="flex-1">
<label for="ng-from" class="block text-sm font-medium text-zinc-400 mb-1">{T.from}</label> <label
for="ng-from"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.from}</label
>
<input <input
id="ng-from" id="ng-from"
type="number" type="number"
@@ -16,7 +20,11 @@ const T = useT(isRu ? 'ru' : 'en');
/> />
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label for="ng-to" class="block text-sm font-medium text-zinc-400 mb-1">{T.to}</label> <label
for="ng-to"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.to}</label
>
<input <input
id="ng-to" id="ng-to"
type="number" type="number"
@@ -26,7 +34,13 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
</div> </div>
<p id="ng-error" role="alert" aria-live="polite" class="mt-2 text-sm text-red-600 hidden"></p> <p
id="ng-error"
role="alert"
aria-live="polite"
class="mt-2 text-sm text-red-600 hidden"
>
</p>
<div class="my-10 min-h-36 flex flex-col items-center justify-center gap-3"> <div class="my-10 min-h-36 flex flex-col items-center justify-center gap-3">
<button <button
@@ -40,14 +54,52 @@ const T = useT(isRu ? 'ru' : 'en');
class="text-8xl font-bold tabular-nums tracking-tight text-zinc-100 select-none group-hover:text-zinc-300" class="text-8xl font-bold tabular-nums tracking-tight text-zinc-100 select-none group-hover:text-zinc-300"
style="transition: transform 0.12s cubic-bezier(0.34,1.56,0.64,1), opacity 0.08s ease, color 0.15s ease;" style="transition: transform 0.12s cubic-bezier(0.34,1.56,0.64,1), opacity 0.08s ease, color 0.15s ease;"
></span> ></span>
<span id="ng-copy-icon" class="absolute -right-7 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-zinc-500" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg> id="ng-copy-icon"
class="absolute -right-7 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-zinc-500"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
><rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect><path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path></svg
>
</span> </span>
<span id="ng-check-icon" class="absolute -right-7 top-1/2 -translate-y-1/2 hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> id="ng-check-icon"
class="absolute -right-7 top-1/2 -translate-y-1/2 hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
><path d="M20 6 9 17l-5-5"></path></svg
>
</span> </span>
</button> </button>
<span id="ng-copied-label" class="text-xs font-medium text-[#534AB7] opacity-0 transition-opacity duration-200" aria-live="polite" aria-atomic="true">{T.copied}</span> <span
id="ng-copied-label"
class="text-xs font-medium text-[#534AB7] opacity-0 transition-opacity duration-200"
aria-live="polite"
aria-atomic="true">{T.copied}</span
>
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
@@ -62,65 +114,69 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const ERR_INTEGERS = isRu ? 'Оба значения должны быть целыми числами.' : 'Both values must be whole numbers.'; import { createErrorDisplay, isInteger } from "@/lib/client/validation";
const ERR_FROM_TO = isRu ? '«От» должно быть меньше «До».' : '"From" must be less than "To".'; import { popElement } from "@/lib/client/animations";
const fromInput = document.getElementById('ng-from') as HTMLInputElement; const isRu = document.documentElement.lang === "ru";
const toInput = document.getElementById('ng-to') as HTMLInputElement; const ERR_INTEGERS = isRu
const btn = document.getElementById('ng-btn') as HTMLButtonElement; ? "Оба значения должны быть целыми числами."
const copyBtn = document.getElementById('ng-copy-btn') as HTMLButtonElement; : "Both values must be whole numbers.";
const resultEl = document.getElementById('ng-result') as HTMLSpanElement; const ERR_FROM_TO = isRu
const errorEl = document.getElementById('ng-error') as HTMLParagraphElement; ? "«От» должно быть меньше «До»."
const copyIcon = document.getElementById('ng-copy-icon') as HTMLSpanElement; : '"From" must be less than "To".';
const checkIcon = document.getElementById('ng-check-icon') as HTMLSpanElement;
const copiedLabel = document.getElementById('ng-copied-label') as HTMLSpanElement;
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null; const fromInput = document.getElementById("ng-from") as HTMLInputElement;
const toInput = document.getElementById("ng-to") as HTMLInputElement;
const btn = document.getElementById("ng-btn") as HTMLButtonElement;
const copyBtn = document.getElementById("ng-copy-btn") as HTMLButtonElement;
const resultEl = document.getElementById("ng-result") as HTMLSpanElement;
const errorEl = document.getElementById("ng-error") as HTMLParagraphElement;
const copyIcon = document.getElementById("ng-copy-icon") as HTMLSpanElement;
const checkIcon = document.getElementById(
"ng-check-icon",
) as HTMLSpanElement;
const copiedLabel = document.getElementById(
"ng-copied-label",
) as HTMLSpanElement;
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); } const errors = createErrorDisplay(errorEl);
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); } const clipboard = new CopyFeedback(copyIcon, checkIcon);
function isInteger(val: string) { return /^-?\d+$/.test(val.trim()); }
function pop() {
resultEl.style.transform = 'scale(1.18)';
resultEl.style.opacity = '0.7';
requestAnimationFrame(() => requestAnimationFrame(() => {
resultEl.style.transform = 'scale(1)';
resultEl.style.opacity = '1';
}));
}
function generate() { function generate() {
if (!isInteger(fromInput.value) || !isInteger(toInput.value)) { showError(ERR_INTEGERS); return; } if (!isInteger(fromInput.value) || !isInteger(toInput.value)) {
errors.show(ERR_INTEGERS);
return;
}
const min = parseInt(fromInput.value, 10); const min = parseInt(fromInput.value, 10);
const max = parseInt(toInput.value, 10); const max = parseInt(toInput.value, 10);
if (min >= max) { showError(ERR_FROM_TO); return; } if (min >= max) {
clearError(); errors.show(ERR_FROM_TO);
return;
}
errors.clear();
const result = Math.floor(Math.random() * (max - min + 1)) + min; const result = Math.floor(Math.random() * (max - min + 1)) + min;
resultEl.textContent = String(result); resultEl.textContent = String(result);
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
pop(); popElement(resultEl);
} }
async function copyNumber() { async function copyNumber() {
const value = resultEl.textContent?.trim(); const value = resultEl.textContent?.trim();
if (!value) return; if (!value) return;
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden'); copiedLabel.style.opacity = "1";
copiedLabel.style.opacity = '1'; setTimeout(() => {
if (copyRevertTimer) clearTimeout(copyRevertTimer); copiedLabel.style.opacity = "0";
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copiedLabel.style.opacity = '0';
}, 1500); }, 1500);
} }
btn.addEventListener('click', generate); btn.addEventListener("click", generate);
copyBtn.addEventListener('click', copyNumber); copyBtn.addEventListener("click", copyNumber);
[fromInput, toInput].forEach((input) => { [fromInput, toInput].forEach((input) => {
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') generate(); }); input.addEventListener("keydown", (e) => {
if (e.key === "Enter") generate();
});
}); });
</script> </script>
+170 -66
View File
@@ -1,84 +1,180 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="password-generator" class="mt-8"> <div id="password-generator" class="mt-8">
<div class="flex flex-col gap-5"> <div class="flex flex-col gap-5">
<div> <div>
<div class="flex items-center justify-between mb-1"> <div class="flex items-center justify-between mb-1">
<label for="pg-length" class="text-sm font-medium text-zinc-400">{T.length}</label> <label for="pg-length" class="text-sm font-medium text-zinc-400"
<span id="pg-length-val" class="text-sm font-semibold tabular-nums text-zinc-100">16</span> >{T.length}</label
>
<span
id="pg-length-val"
class="text-sm font-semibold tabular-nums text-zinc-100"
>16</span
>
</div>
<input
id="pg-length"
type="range"
min="4"
max="64"
value="16"
class="w-full accent-[#534AB7] cursor-pointer"
/>
<div
class="flex justify-between text-xs text-zinc-600 mt-1 select-none"
>
<span>4</span><span>64</span>
</div> </div>
<input id="pg-length" type="range" min="4" max="64" value="16" class="w-full accent-[#534AB7] cursor-pointer" />
<div class="flex justify-between text-xs text-zinc-600 mt-1 select-none"><span>4</span><span>64</span></div>
</div> </div>
<div class="grid grid-cols-2 gap-3"> <div class="grid grid-cols-2 gap-3">
{[ {
{ id: 'pg-upper', label: T.uppercase }, [
{ id: 'pg-lower', label: T.lowercase }, { id: "pg-upper", label: T.uppercase },
{ id: 'pg-digits', label: T.digits }, { id: "pg-lower", label: T.lowercase },
{ id: 'pg-symbols', label: T.symbols }, { id: "pg-digits", label: T.digits },
{ id: "pg-symbols", label: T.symbols },
].map(({ id, label }) => ( ].map(({ id, label }) => (
<label class="flex items-center gap-2.5 cursor-pointer select-none group"> <label class="flex items-center gap-2.5 cursor-pointer select-none group">
<input id={id} type="checkbox" checked class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer" /> <input
<span class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors">{label}</span> id={id}
type="checkbox"
checked
class="w-4 h-4 rounded accent-[#534AB7] cursor-pointer"
/>
<span class="text-sm text-zinc-400 group-hover:text-zinc-200 transition-colors">
{label}
</span>
</label> </label>
))} ))
}
</div> </div>
</div> </div>
<p id="pg-error" role="alert" aria-live="polite" class="mt-4 text-sm text-red-500 hidden"></p> <p
id="pg-error"
role="alert"
aria-live="polite"
class="mt-4 text-sm text-red-500 hidden"
>
</p>
<div class="my-10 min-h-24 flex flex-col items-center justify-center gap-3"> <div class="my-10 min-h-24 flex flex-col items-center justify-center gap-3">
<button id="pg-copy-btn" type="button" class="group relative invisible cursor-copy rounded-xl px-3 py-2 -mx-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7]"> <button
<span id="pg-result" class="font-mono text-2xl sm:text-3xl font-bold tracking-wide text-zinc-100 break-all select-none group-hover:text-zinc-300" style="transition: opacity 0.08s ease, color 0.15s ease;"></span> id="pg-copy-btn"
<span id="pg-copy-icon" class="absolute -right-7 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-zinc-500" aria-hidden="true"> type="button"
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg> class="group relative invisible cursor-copy rounded-xl px-3 py-2 -mx-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7]"
>
<span
id="pg-result"
class="font-mono text-2xl sm:text-3xl font-bold tracking-wide text-zinc-100 break-all select-none group-hover:text-zinc-300"
style="transition: opacity 0.08s ease, color 0.15s ease;"
></span>
<span
id="pg-copy-icon"
class="absolute -right-7 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-zinc-500"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
><rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect><path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path></svg
>
</span> </span>
<span id="pg-check-icon" class="absolute -right-7 top-1/2 -translate-y-1/2 hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> id="pg-check-icon"
class="absolute -right-7 top-1/2 -translate-y-1/2 hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
><path d="M20 6 9 17l-5-5"></path></svg
>
</span> </span>
</button> </button>
<span id="pg-copied-label" class="text-xs font-medium text-[#534AB7] opacity-0 transition-opacity duration-200" aria-live="polite" aria-atomic="true">{T.copied}</span> <span
id="pg-copied-label"
class="text-xs font-medium text-[#534AB7] opacity-0 transition-opacity duration-200"
aria-live="polite"
aria-atomic="true">{T.copied}</span
>
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<button id="pg-btn" type="button" class="w-full sm:w-auto px-8 py-3 bg-[#534AB7] text-white font-semibold rounded-lg hover:bg-[#4740a0] active:bg-[#3d3990] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 transition-colors duration-100 cursor-pointer"> <button
id="pg-btn"
type="button"
class="w-full sm:w-auto px-8 py-3 bg-[#534AB7] text-white font-semibold rounded-lg hover:bg-[#4740a0] active:bg-[#3d3990] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#534AB7] focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 transition-colors duration-100 cursor-pointer"
>
{T.generate} {T.generate}
</button> </button>
</div> </div>
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const ERR_SELECT_TYPE = isRu ? 'Выберите хотя бы один тип символов.' : 'Select at least one character type.'; import { createErrorDisplay } from "@/lib/client/validation";
const lengthInput = document.getElementById('pg-length') as HTMLInputElement; const isRu = document.documentElement.lang === "ru";
const lengthVal = document.getElementById('pg-length-val') as HTMLSpanElement; const ERR_SELECT_TYPE = isRu
const upperCb = document.getElementById('pg-upper') as HTMLInputElement; ? "Выберите хотя бы один тип символов."
const lowerCb = document.getElementById('pg-lower') as HTMLInputElement; : "Select at least one character type.";
const digitsCb = document.getElementById('pg-digits') as HTMLInputElement;
const symbolsCb = document.getElementById('pg-symbols') as HTMLInputElement;
const btn = document.getElementById('pg-btn') as HTMLButtonElement;
const copyBtn = document.getElementById('pg-copy-btn') as HTMLButtonElement;
const resultEl = document.getElementById('pg-result') as HTMLSpanElement;
const errorEl = document.getElementById('pg-error') as HTMLParagraphElement;
const copyIcon = document.getElementById('pg-copy-icon') as HTMLSpanElement;
const checkIcon = document.getElementById('pg-check-icon') as HTMLSpanElement;
const copiedLabel = document.getElementById('pg-copied-label') as HTMLSpanElement;
const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const lengthInput = document.getElementById(
const LOWER = 'abcdefghijklmnopqrstuvwxyz'; "pg-length",
const DIGITS = '0123456789'; ) as HTMLInputElement;
const SYMBOLS = '!@#$%^&*()-_=+[]{}|;:,.<>?'; const lengthVal = document.getElementById(
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null; "pg-length-val",
) as HTMLSpanElement;
const upperCb = document.getElementById("pg-upper") as HTMLInputElement;
const lowerCb = document.getElementById("pg-lower") as HTMLInputElement;
const digitsCb = document.getElementById("pg-digits") as HTMLInputElement;
const symbolsCb = document.getElementById("pg-symbols") as HTMLInputElement;
const btn = document.getElementById("pg-btn") as HTMLButtonElement;
const copyBtn = document.getElementById("pg-copy-btn") as HTMLButtonElement;
const resultEl = document.getElementById("pg-result") as HTMLSpanElement;
const errorEl = document.getElementById("pg-error") as HTMLParagraphElement;
const copyIcon = document.getElementById("pg-copy-icon") as HTMLSpanElement;
const checkIcon = document.getElementById(
"pg-check-icon",
) as HTMLSpanElement;
const copiedLabel = document.getElementById(
"pg-copied-label",
) as HTMLSpanElement;
lengthInput.addEventListener('input', () => { lengthVal.textContent = lengthInput.value; }); const UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const LOWER = "abcdefghijklmnopqrstuvwxyz";
const DIGITS = "0123456789";
const SYMBOLS = "!@#$%^&*()-_=+[]{}|;:,.<>?";
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); } lengthInput.addEventListener("input", () => {
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); } lengthVal.textContent = lengthInput.value;
});
const errors = createErrorDisplay(errorEl);
const clipboard = new CopyFeedback(copyIcon, checkIcon);
function generate() { function generate() {
const length = parseInt(lengthInput.value, 10); const length = parseInt(lengthInput.value, 10);
@@ -87,37 +183,45 @@ const T = useT(isRu ? 'ru' : 'en');
if (lowerCb.checked) pools.push(LOWER); if (lowerCb.checked) pools.push(LOWER);
if (digitsCb.checked) pools.push(DIGITS); if (digitsCb.checked) pools.push(DIGITS);
if (symbolsCb.checked) pools.push(SYMBOLS); if (symbolsCb.checked) pools.push(SYMBOLS);
if (pools.length === 0) { showError(ERR_SELECT_TYPE); return; } if (pools.length === 0) {
clearError(); errors.show(ERR_SELECT_TYPE);
const required = pools.map((p) => p[Math.floor(Math.random() * p.length)]); return;
const combined = pools.join(''); }
const rest = Array.from({ length: length - required.length }, () => combined[Math.floor(Math.random() * combined.length)]); errors.clear();
const required = pools.map(
(p) => p[Math.floor(Math.random() * p.length)],
);
const combined = pools.join("");
const rest = Array.from(
{ length: length - required.length },
() => combined[Math.floor(Math.random() * combined.length)],
);
const chars = [...required, ...rest]; const chars = [...required, ...rest];
for (let i = chars.length - 1; i > 0; i--) { for (let i = chars.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); const j = Math.floor(Math.random() * (i + 1));
[chars[i], chars[j]] = [chars[j], chars[i]]; [chars[i], chars[j]] = [chars[j], chars[i]];
} }
resultEl.textContent = chars.join(''); resultEl.textContent = chars.join("");
resultEl.style.opacity = '0.5'; resultEl.style.opacity = "0.5";
requestAnimationFrame(() => requestAnimationFrame(() => { resultEl.style.opacity = '1'; })); requestAnimationFrame(() =>
copyBtn.classList.remove('invisible'); requestAnimationFrame(() => {
resultEl.style.opacity = "1";
}),
);
copyBtn.classList.remove("invisible");
} }
async function copyPassword() { async function copyPassword() {
const value = resultEl.textContent?.trim(); const value = resultEl.textContent?.trim();
if (!value) return; if (!value) return;
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden'); copiedLabel.style.opacity = "1";
copiedLabel.style.opacity = '1'; setTimeout(() => {
if (copyRevertTimer) clearTimeout(copyRevertTimer); copiedLabel.style.opacity = "0";
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copiedLabel.style.opacity = '0';
}, 1500); }, 1500);
} }
btn.addEventListener('click', generate); btn.addEventListener("click", generate);
copyBtn.addEventListener('click', copyPassword); copyBtn.addEventListener("click", copyPassword);
</script> </script>
+131 -59
View File
@@ -1,32 +1,50 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="uuid-generator" class="mt-8"> <div id="uuid-generator" class="mt-8">
<div class="flex flex-col gap-4"> <div class="flex flex-col gap-4">
<div> <div>
<label class="block text-sm font-medium text-zinc-400 mb-2">{T.type}</label> <label class="block text-sm font-medium text-zinc-400 mb-2"
<div class="flex flex-wrap gap-2" role="radiogroup" aria-label={T.type}> >{T.type}</label
{[ >
{ value: 'uuid', label: 'UUID v4' }, <div
{ value: 'hex', label: 'Hex' }, class="flex flex-wrap gap-2"
{ value: 'base64', label: 'Base64' }, role="radiogroup"
aria-label={T.type}
>
{
[
{ value: "uuid", label: "UUID v4" },
{ value: "hex", label: "Hex" },
{ value: "base64", label: "Base64" },
].map(({ value, label }) => ( ].map(({ value, label }) => (
<label class="cursor-pointer"> <label class="cursor-pointer">
<input type="radio" name="ug-type" value={value} class="sr-only peer" checked={value === 'uuid'} /> <input
type="radio"
name="ug-type"
value={value}
class="sr-only peer"
checked={value === "uuid"}
/>
<span class="inline-flex items-center justify-center px-4 h-9 rounded-lg border border-zinc-700 text-sm font-medium text-zinc-400 peer-checked:border-[#534AB7] peer-checked:text-[#534AB7] peer-checked:bg-[#534AB7]/10 hover:border-zinc-500 transition-colors select-none cursor-pointer"> <span class="inline-flex items-center justify-center px-4 h-9 rounded-lg border border-zinc-700 text-sm font-medium text-zinc-400 peer-checked:border-[#534AB7] peer-checked:text-[#534AB7] peer-checked:bg-[#534AB7]/10 hover:border-zinc-500 transition-colors select-none cursor-pointer">
{label} {label}
</span> </span>
</label> </label>
))} ))
}
</div> </div>
</div> </div>
<div class="flex flex-col sm:flex-row gap-4"> <div class="flex flex-col sm:flex-row gap-4">
<div id="ug-length-wrap" class="flex-1 hidden"> <div id="ug-length-wrap" class="flex-1 hidden">
<label for="ug-length" class="block text-sm font-medium text-zinc-400 mb-1">{T.lengthBytes}</label> <label
for="ug-length"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.lengthBytes}</label
>
<input <input
id="ug-length" id="ug-length"
type="number" type="number"
@@ -38,7 +56,11 @@ const T = useT(isRu ? 'ru' : 'en');
/> />
</div> </div>
<div class="flex-1"> <div class="flex-1">
<label for="ug-count" class="block text-sm font-medium text-zinc-400 mb-1">{T.count}</label> <label
for="ug-count"
class="block text-sm font-medium text-zinc-400 mb-1"
>{T.count}</label
>
<input <input
id="ug-count" id="ug-count"
type="number" type="number"
@@ -52,7 +74,11 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
</div> </div>
<div class="my-8 min-h-16 flex flex-col gap-2" aria-live="polite" aria-label="Generated tokens"> <div
class="my-8 min-h-16 flex flex-col gap-2"
aria-live="polite"
aria-label="Generated tokens"
>
<div id="ug-result" class="flex flex-col gap-2"></div> <div id="ug-result" class="flex flex-col gap-2"></div>
<button <button
@@ -63,14 +89,41 @@ const T = useT(isRu ? 'ru' : 'en');
> >
<span id="ug-copy-label">{T.copyAll}</span> <span id="ug-copy-label">{T.copyAll}</span>
<span id="ug-copy-icon" aria-hidden="true"> <span id="ug-copy-icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/> xmlns="http://www.w3.org/2000/svg"
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/> width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect>
<path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path>
</svg> </svg>
</span> </span>
<span id="ug-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> id="ug-check-icon"
<path d="M20 6 9 17l-5-5"/> class="hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5"></path>
</svg> </svg>
</span> </span>
</button> </button>
@@ -88,38 +141,55 @@ const T = useT(isRu ? 'ru' : 'en');
</div> </div>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const COPY_ALL_LABEL = isRu ? 'Копировать всё' : 'Copy all';
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const lengthWrap = document.getElementById('ug-length-wrap') as HTMLDivElement; const isRu = document.documentElement.lang === "ru";
const lengthInput = document.getElementById('ug-length') as HTMLInputElement; const COPY_ALL_LABEL = isRu ? "Копировать всё" : "Copy all";
const countInput = document.getElementById('ug-count') as HTMLInputElement; const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
const btn = document.getElementById('ug-btn') as HTMLButtonElement;
const copyBtn = document.getElementById('ug-copy-btn') as HTMLButtonElement; const lengthWrap = document.getElementById(
const resultEl = document.getElementById('ug-result') as HTMLDivElement; "ug-length-wrap",
const copyLabel = document.getElementById('ug-copy-label') as HTMLSpanElement; ) as HTMLDivElement;
const copyIcon = document.getElementById('ug-copy-icon') as HTMLSpanElement; const lengthInput = document.getElementById(
const checkIcon = document.getElementById('ug-check-icon') as HTMLSpanElement; "ug-length",
) as HTMLInputElement;
const countInput = document.getElementById("ug-count") as HTMLInputElement;
const btn = document.getElementById("ug-btn") as HTMLButtonElement;
const copyBtn = document.getElementById("ug-copy-btn") as HTMLButtonElement;
const resultEl = document.getElementById("ug-result") as HTMLDivElement;
const copyLabel = document.getElementById(
"ug-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById("ug-copy-icon") as HTMLSpanElement;
const checkIcon = document.getElementById(
"ug-check-icon",
) as HTMLSpanElement;
let lastTokens: string[] = []; let lastTokens: string[] = [];
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null;
const clipboard = new CopyFeedback(copyIcon, checkIcon);
function getType(): string { function getType(): string {
return (document.querySelector('input[name="ug-type"]:checked') as HTMLInputElement)?.value ?? 'uuid'; return (
(
document.querySelector(
'input[name="ug-type"]:checked',
) as HTMLInputElement
)?.value ?? "uuid"
);
} }
document.querySelectorAll('input[name="ug-type"]').forEach((radio) => { document.querySelectorAll('input[name="ug-type"]').forEach((radio) => {
radio.addEventListener('change', () => { radio.addEventListener("change", () => {
const type = getType(); const type = getType();
lengthWrap.classList.toggle('hidden', type === 'uuid'); lengthWrap.classList.toggle("hidden", type === "uuid");
}); });
}); });
function uuidV4(): string { function uuidV4(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (crypto.getRandomValues(new Uint8Array(1))[0] & 0xf); const r = crypto.getRandomValues(new Uint8Array(1))[0] & 0xf;
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
}); });
} }
@@ -130,12 +200,16 @@ const T = useT(isRu ? 'ru' : 'en');
} }
function toHex(bytes: Uint8Array): string { function toHex(bytes: Uint8Array): string {
return Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join(''); return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
} }
function toBase64(bytes: Uint8Array): string { function toBase64(bytes: Uint8Array): string {
return btoa(String.fromCharCode(...bytes)) return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); .replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
} }
function generate() { function generate() {
@@ -144,48 +218,46 @@ const T = useT(isRu ? 'ru' : 'en');
const length = parseInt(lengthInput.value, 10); const length = parseInt(lengthInput.value, 10);
lastTokens = Array.from({ length: count }, () => { lastTokens = Array.from({ length: count }, () => {
if (type === 'uuid') return uuidV4(); if (type === "uuid") return uuidV4();
if (type === 'hex') return toHex(randomBytes(length)); if (type === "hex") return toHex(randomBytes(length));
return toBase64(randomBytes(length)); return toBase64(randomBytes(length));
}); });
resultEl.innerHTML = ''; resultEl.innerHTML = "";
lastTokens.forEach((token) => { lastTokens.forEach((token) => {
const row = document.createElement('div'); const row = document.createElement("div");
row.className = row.className =
'flex items-center justify-between gap-3 bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2'; "flex items-center justify-between gap-3 bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2";
const code = document.createElement('code'); const code = document.createElement("code");
code.textContent = token; code.textContent = token;
code.className = 'text-sm font-mono text-zinc-100 break-all'; code.className = "text-sm font-mono text-zinc-100 break-all";
row.appendChild(code); row.appendChild(code);
resultEl.appendChild(row); resultEl.appendChild(row);
}); });
copyBtn.classList.remove('invisible'); copyBtn.classList.remove("invisible");
copyLabel.textContent = COPY_ALL_LABEL; copyLabel.textContent = COPY_ALL_LABEL;
} }
async function copyAll() { async function copyAll() {
if (!lastTokens.length) return; if (!lastTokens.length) return;
await navigator.clipboard.writeText(lastTokens.join('\n')); await navigator.clipboard.writeText(lastTokens.join("\n"));
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_ALL_LABEL; copyLabel.textContent = COPY_ALL_LABEL;
}, 1500); }, 1500);
} }
btn.addEventListener('click', generate); btn.addEventListener("click", generate);
copyBtn.addEventListener('click', copyAll); copyBtn.addEventListener("click", copyAll);
[countInput, lengthInput].forEach((el) => { [countInput, lengthInput].forEach((el) => {
el.addEventListener('keydown', (e) => { if (e.key === 'Enter') generate(); }); el.addEventListener("keydown", (e) => {
if (e.key === "Enter") generate();
});
}); });
</script> </script>
+194 -90
View File
@@ -1,29 +1,34 @@
--- ---
import { useT } from '../../i18n/translations'; import { useT } from "../../i18n/translations";
const isRu = Astro.url.pathname.startsWith('/ru'); const isRu = Astro.url.pathname.startsWith("/ru");
const T = useT(isRu ? 'ru' : 'en'); const T = useT(isRu ? "ru" : "en");
--- ---
<div id="wheel-spinner" class="mt-8"> <div id="wheel-spinner" class="mt-8">
<!-- Items input --> <!-- Items input -->
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">
<div> <div>
<label for="ws-items" class="block text-sm font-medium text-zinc-400 mb-1"> <label
{T.items} <span class="text-zinc-600">({T.itemsOneLine224})</span> for="ws-items"
class="block text-sm font-medium text-zinc-400 mb-1"
>
{T.items}
<span class="text-zinc-600">({T.itemsOneLine224})</span>
</label> </label>
<textarea <textarea
id="ws-items" id="ws-items"
rows="6" rows="6"
class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-sm font-mono focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors resize-y" class="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-3 py-2 text-zinc-100 text-sm font-mono focus:outline-none focus:border-[#534AB7] focus:ring-1 focus:ring-[#534AB7] transition-colors resize-y"
>Alice >Alice Bob Carol Dave Eve Frank</textarea
Bob >
Carol
Dave
Eve
Frank</textarea>
</div> </div>
<p id="ws-error" role="alert" aria-live="polite" class="text-sm text-red-500 hidden"></p> <p
id="ws-error"
role="alert"
aria-live="polite"
class="text-sm text-red-500 hidden"
>
</p>
</div> </div>
<!-- Wheel area --> <!-- Wheel area -->
@@ -35,12 +40,12 @@ Frank</textarea>
class="absolute left-1/2 top-0 z-10 -translate-x-1/2 -translate-y-1/2" class="absolute left-1/2 top-0 z-10 -translate-x-1/2 -translate-y-1/2"
style="width:0;height:0;border-left:14px solid transparent;border-right:14px solid transparent;border-top:24px solid #534AB7;filter:drop-shadow(0 2px 8px rgba(83,74,183,0.6));" style="width:0;height:0;border-left:14px solid transparent;border-right:14px solid transparent;border-top:24px solid #534AB7;filter:drop-shadow(0 2px 8px rgba(83,74,183,0.6));"
aria-hidden="true" aria-hidden="true"
></div> >
</div>
<canvas <canvas
id="ws-canvas" id="ws-canvas"
class="block w-full" class="block w-full"
aria-label="Wheel of fortune" aria-label="Wheel of fortune"></canvas>
></canvas>
</div> </div>
<button <button
@@ -53,9 +58,21 @@ Frank</textarea>
</div> </div>
<!-- Result card (hidden until first spin) --> <!-- Result card (hidden until first spin) -->
<div id="ws-result-card" class="hidden mt-10 flex flex-col items-center gap-3" aria-live="polite"> <div
<p id="ws-winner-label" class="text-xs font-semibold uppercase tracking-widest text-zinc-500">{T.winner}</p> id="ws-result-card"
<span id="ws-result-text" class="text-3xl sm:text-4xl font-bold text-zinc-100 text-center break-words max-w-full"></span> class="hidden mt-10 flex flex-col items-center gap-3"
aria-live="polite"
>
<p
id="ws-winner-label"
class="text-xs font-semibold uppercase tracking-widest text-zinc-500"
>
{T.winner}
</p>
<span
id="ws-result-text"
class="text-3xl sm:text-4xl font-bold text-zinc-100 text-center break-words max-w-full"
></span>
<button <button
id="ws-copy-btn" id="ws-copy-btn"
type="button" type="button"
@@ -63,56 +80,116 @@ Frank</textarea>
> >
<span id="ws-copy-label">{T.copy}</span> <span id="ws-copy-label">{T.copy}</span>
<span id="ws-copy-icon" aria-hidden="true"> <span id="ws-copy-icon" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/> xmlns="http://www.w3.org/2000/svg"
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/> width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2"
></rect>
<path
d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"
></path>
</svg> </svg>
</span> </span>
<span id="ws-check-icon" class="hidden text-[#534AB7]" aria-hidden="true"> <span
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> id="ws-check-icon"
<path d="M20 6 9 17l-5-5"/> class="hidden text-[#534AB7]"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5"></path>
</svg> </svg>
</span> </span>
</button> </button>
</div> </div>
</div> </div>
<style> <style>
@keyframes ws-pop { @keyframes ws-pop {
from { transform: scale(0.6); opacity: 0; } from {
to { transform: scale(1); opacity: 1; } transform: scale(0.6);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
.ws-pop {
animation: ws-pop 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) both;
} }
.ws-pop { animation: ws-pop 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) both; }
</style> </style>
<script> <script>
const isRu = document.documentElement.lang === 'ru'; import { CopyFeedback } from "@/lib/client/clipboard";
const COPY_LABEL = isRu ? 'Копировать' : 'Copy'; import { createErrorDisplay } from "@/lib/client/validation";
const COPIED_LABEL = isRu ? 'Скопировано' : 'Copied';
const ERR_MIN2 = isRu ? 'Добавьте хотя бы 2 элемента.' : 'Add at least 2 items.';
const ERR_MAX24 = isRu ? 'Максимум 24 элемента.' : 'Maximum 24 items.';
const COLORS = ['#534AB7','#0F6E56','#993C1D','#185FA5','#854F0B','#993556','#3B6D11','#A32D2D']; const isRu = document.documentElement.lang === "ru";
const COPY_LABEL = isRu ? "Копировать" : "Copy";
const COPIED_LABEL = isRu ? "Скопировано" : "Copied";
const ERR_MIN2 = isRu
? "Добавьте хотя бы 2 элемента."
: "Add at least 2 items.";
const ERR_MAX24 = isRu ? "Максимум 24 элемента." : "Maximum 24 items.";
const COLORS = [
"#534AB7",
"#0F6E56",
"#993C1D",
"#185FA5",
"#854F0B",
"#993556",
"#3B6D11",
"#A32D2D",
];
const TAU = 2 * Math.PI; const TAU = 2 * Math.PI;
const textarea = document.getElementById('ws-items') as HTMLTextAreaElement; const textarea = document.getElementById("ws-items") as HTMLTextAreaElement;
const errorEl = document.getElementById('ws-error') as HTMLParagraphElement; const errorEl = document.getElementById("ws-error") as HTMLParagraphElement;
const canvas = document.getElementById('ws-canvas') as HTMLCanvasElement; const canvas = document.getElementById("ws-canvas") as HTMLCanvasElement;
const spinBtn = document.getElementById('ws-spin-btn') as HTMLButtonElement; const spinBtn = document.getElementById("ws-spin-btn") as HTMLButtonElement;
const resultCard = document.getElementById('ws-result-card') as HTMLDivElement; const resultCard = document.getElementById(
const resultText = document.getElementById('ws-result-text') as HTMLSpanElement; "ws-result-card",
const copyBtn = document.getElementById('ws-copy-btn') as HTMLButtonElement; ) as HTMLDivElement;
const copyLabel = document.getElementById('ws-copy-label') as HTMLSpanElement; const resultText = document.getElementById(
const copyIcon = document.getElementById('ws-copy-icon') as HTMLSpanElement; "ws-result-text",
const checkIcon = document.getElementById('ws-check-icon') as HTMLSpanElement; ) as HTMLSpanElement;
const wheelWrap = document.getElementById('ws-wheel-wrap') as HTMLDivElement; const copyBtn = document.getElementById("ws-copy-btn") as HTMLButtonElement;
const copyLabel = document.getElementById(
"ws-copy-label",
) as HTMLSpanElement;
const copyIcon = document.getElementById("ws-copy-icon") as HTMLSpanElement;
const checkIcon = document.getElementById(
"ws-check-icon",
) as HTMLSpanElement;
const wheelWrap = document.getElementById(
"ws-wheel-wrap",
) as HTMLDivElement;
const ctx = canvas.getContext('2d')!; const ctx = canvas.getContext("2d")!;
let items: string[] = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank']; let items: string[] = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank"];
let currentRotation = 0; let currentRotation = 0;
let isSpinning = false; let isSpinning = false;
let copyRevertTimer: ReturnType<typeof setTimeout> | null = null;
const errors = createErrorDisplay(errorEl);
const clipboard = new CopyFeedback(copyIcon, checkIcon);
// ── Canvas sizing ──────────────────────────────────────────────── // ── Canvas sizing ────────────────────────────────────────────────
function resize() { function resize() {
@@ -128,8 +205,9 @@ Frank</textarea>
function clampText(text: string, maxWidth: number): string { function clampText(text: string, maxWidth: number): string {
if (ctx.measureText(text).width <= maxWidth) return text; if (ctx.measureText(text).width <= maxWidth) return text;
let s = text; let s = text;
while (s.length > 0 && ctx.measureText(s + '…').width > maxWidth) s = s.slice(0, -1); while (s.length > 0 && ctx.measureText(s + "…").width > maxWidth)
return s + '…'; s = s.slice(0, -1);
return s + "…";
} }
function draw(rotation: number) { function draw(rotation: number) {
@@ -153,16 +231,19 @@ Frank</textarea>
ctx.fillStyle = COLORS[i % COLORS.length]; ctx.fillStyle = COLORS[i % COLORS.length];
ctx.fill(); ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.13)'; ctx.strokeStyle = "rgba(255,255,255,0.13)";
ctx.lineWidth = 1.5; ctx.lineWidth = 1.5;
ctx.stroke(); ctx.stroke();
const mid = a0 + seg / 2; const mid = a0 + seg / 2;
const fontSize = Math.max(9, Math.min(14, Math.floor(r * seg * 0.4))); const fontSize = Math.max(
9,
Math.min(14, Math.floor(r * seg * 0.4)),
);
ctx.save(); ctx.save();
ctx.rotate(mid); ctx.rotate(mid);
ctx.textAlign = 'right'; ctx.textAlign = "right";
ctx.fillStyle = 'rgba(255,255,255,0.92)'; ctx.fillStyle = "rgba(255,255,255,0.92)";
ctx.font = `bold ${fontSize}px 'Space Grotesk', sans-serif`; ctx.font = `bold ${fontSize}px 'Space Grotesk', sans-serif`;
const label = clampText(items[i], r * 0.54); const label = clampText(items[i], r * 0.54);
ctx.fillText(label, r - 10, fontSize * 0.38); ctx.fillText(label, r - 10, fontSize * 0.38);
@@ -171,15 +252,15 @@ Frank</textarea>
ctx.beginPath(); ctx.beginPath();
ctx.arc(0, 0, r, 0, TAU); ctx.arc(0, 0, r, 0, TAU);
ctx.strokeStyle = 'rgba(255,255,255,0.2)'; ctx.strokeStyle = "rgba(255,255,255,0.2)";
ctx.lineWidth = 3; ctx.lineWidth = 3;
ctx.stroke(); ctx.stroke();
ctx.beginPath(); ctx.beginPath();
ctx.arc(0, 0, 15, 0, TAU); ctx.arc(0, 0, 15, 0, TAU);
ctx.fillStyle = '#18181b'; ctx.fillStyle = "#18181b";
ctx.fill(); ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.22)'; ctx.strokeStyle = "rgba(255,255,255,0.22)";
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.stroke(); ctx.stroke();
@@ -188,29 +269,38 @@ Frank</textarea>
// ── Items ──────────────────────────────────────────────────────── // ── Items ────────────────────────────────────────────────────────
function parseItems(): string[] | null { function parseItems(): string[] | null {
const lines = textarea.value.split('\n').map(l => l.trim()).filter(Boolean); const lines = textarea.value
if (lines.length < 2) { showError(ERR_MIN2); return null; } .split("\n")
if (lines.length > 24) { showError(ERR_MAX24); return null; } .map((l) => l.trim())
clearError(); .filter(Boolean);
if (lines.length < 2) {
errors.show(ERR_MIN2);
return null;
}
if (lines.length > 24) {
errors.show(ERR_MAX24);
return null;
}
errors.clear();
return lines; return lines;
} }
function showError(msg: string) { errorEl.textContent = msg; errorEl.classList.remove('hidden'); }
function clearError() { errorEl.textContent = ''; errorEl.classList.add('hidden'); }
function applyItems() { function applyItems() {
const parsed = parseItems(); const parsed = parseItems();
if (parsed) { items = parsed; draw(currentRotation); } if (parsed) {
items = parsed;
draw(currentRotation);
}
} }
let debounceTimer: ReturnType<typeof setTimeout> | null = null; let debounceTimer: ReturnType<typeof setTimeout> | null = null;
textarea.addEventListener('input', () => { textarea.addEventListener("input", () => {
if (debounceTimer) clearTimeout(debounceTimer); if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(applyItems, 300); debounceTimer = setTimeout(applyItems, 300);
}); });
// ── Spin ───────────────────────────────────────────────────────── // ── Spin ─────────────────────────────────────────────────────────
spinBtn.addEventListener('click', () => { spinBtn.addEventListener("click", () => {
if (isSpinning) return; if (isSpinning) return;
const parsed = parseItems(); const parsed = parseItems();
if (!parsed) return; if (!parsed) return;
@@ -221,7 +311,7 @@ Frank</textarea>
const seg = TAU / n; const seg = TAU / n;
const winnerIdx = Math.floor(Math.random() * n); const winnerIdx = Math.floor(Math.random() * n);
const desiredPhase = (-(winnerIdx + 0.5) * seg % TAU + TAU) % TAU; const desiredPhase = (((-(winnerIdx + 0.5) * seg) % TAU) + TAU) % TAU;
const currentPhase = ((currentRotation % TAU) + TAU) % TAU; const currentPhase = ((currentRotation % TAU) + TAU) % TAU;
let delta = (desiredPhase - currentPhase + TAU) % TAU; let delta = (desiredPhase - currentPhase + TAU) % TAU;
if (delta < 0.5) delta += TAU; if (delta < 0.5) delta += TAU;
@@ -236,7 +326,7 @@ Frank</textarea>
isSpinning = true; isSpinning = true;
spinBtn.disabled = true; spinBtn.disabled = true;
resultCard.classList.add('hidden'); resultCard.classList.add("hidden");
(function animate(now: number) { (function animate(now: number) {
const p = Math.min((now - t0) / duration, 1); const p = Math.min((now - t0) / duration, 1);
@@ -259,29 +349,27 @@ Frank</textarea>
// ── Result ─────────────────────────────────────────────────────── // ── Result ───────────────────────────────────────────────────────
function showResult(winner: string) { function showResult(winner: string) {
resultText.textContent = winner; resultText.textContent = winner;
resultCard.classList.remove('hidden'); resultCard.classList.remove("hidden");
resultText.classList.remove('ws-pop'); resultText.classList.remove("ws-pop");
void resultText.offsetWidth; void resultText.offsetWidth;
resultText.classList.add('ws-pop'); resultText.classList.add("ws-pop");
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
copyIcon.classList.remove('hidden'); copyIcon.classList.remove("hidden");
checkIcon.classList.add('hidden'); checkIcon.classList.add("hidden");
} }
copyBtn.addEventListener('click', async () => { async function copyResult() {
const value = resultText.textContent?.trim(); const value = resultText.textContent?.trim();
if (!value) return; if (!value) return;
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
copyIcon.classList.add('hidden'); clipboard.showCopied();
checkIcon.classList.remove('hidden');
copyLabel.textContent = COPIED_LABEL; copyLabel.textContent = COPIED_LABEL;
if (copyRevertTimer) clearTimeout(copyRevertTimer); setTimeout(() => {
copyRevertTimer = setTimeout(() => {
checkIcon.classList.add('hidden');
copyIcon.classList.remove('hidden');
copyLabel.textContent = COPY_LABEL; copyLabel.textContent = COPY_LABEL;
}, 1500); }, 1500);
}); }
copyBtn.addEventListener("click", copyResult);
// ── Confetti ───────────────────────────────────────────────────── // ── Confetti ─────────────────────────────────────────────────────
function spawnConfetti() { function spawnConfetti() {
@@ -289,14 +377,21 @@ Frank</textarea>
const cx = cr.left + cr.width / 2; const cx = cr.left + cr.width / 2;
const cy = cr.top + cr.height / 2; const cy = cr.top + cr.height / 2;
type Particle = { el: HTMLDivElement; x: number; y: number; vx: number; vy: number }; type Particle = {
el: HTMLDivElement;
x: number;
y: number;
vx: number;
vy: number;
};
const particles: Particle[] = []; const particles: Particle[] = [];
for (let i = 0; i < 60; i++) { for (let i = 0; i < 60; i++) {
const el = document.createElement('div'); const el = document.createElement("div");
const w = 4 + Math.random() * 6; const w = 4 + Math.random() * 6;
const h = 4 + Math.random() * 6; const h = 4 + Math.random() * 6;
el.style.cssText = `position:fixed;width:${w}px;height:${h}px;` + el.style.cssText =
`position:fixed;width:${w}px;height:${h}px;` +
`background:${COLORS[i % COLORS.length]};border-radius:1px;` + `background:${COLORS[i % COLORS.length]};border-radius:1px;` +
`pointer-events:none;left:${cx}px;top:${cy}px;will-change:transform,opacity;z-index:9999;`; `pointer-events:none;left:${cx}px;top:${cy}px;will-change:transform,opacity;z-index:9999;`;
document.body.appendChild(el); document.body.appendChild(el);
@@ -304,9 +399,15 @@ Frank</textarea>
const angle = Math.random() * TAU; const angle = Math.random() * TAU;
const speed = 4 + Math.random() * 7; const speed = 4 + Math.random() * 7;
particles.push({ particles.push({
el, x: cx, y: cy, el,
x: cx,
y: cy,
vx: Math.cos(angle) * speed, vx: Math.cos(angle) * speed,
vy: -(Math.abs(Math.sin(angle)) * speed + 2 + Math.random() * 4), vy: -(
Math.abs(Math.sin(angle)) * speed +
2 +
Math.random() * 4
),
}); });
} }
@@ -316,9 +417,12 @@ Frank</textarea>
(function tick(now: number) { (function tick(now: number) {
const elapsed = now - t0; const elapsed = now - t0;
if (elapsed >= dur) { particles.forEach(p => p.el.remove()); return; } if (elapsed >= dur) {
particles.forEach((p) => p.el.remove());
return;
}
const opacity = 1 - elapsed / dur; const opacity = 1 - elapsed / dur;
particles.forEach(p => { particles.forEach((p) => {
p.vy += gravity; p.vy += gravity;
p.vx *= 0.99; p.vx *= 0.99;
p.x += p.vx; p.x += p.vx;
+10
View File
@@ -0,0 +1,10 @@
export function popElement(el: HTMLElement) {
el.style.transform = 'scale(1.18)';
el.style.opacity = '0.7';
requestAnimationFrame(() =>
requestAnimationFrame(() => {
el.style.transform = 'scale(1)';
el.style.opacity = '1';
})
);
}
+25
View File
@@ -0,0 +1,25 @@
export class CopyFeedback {
private timer: ReturnType<typeof setTimeout> | null = null;
constructor(
private copyIcon: HTMLElement,
private checkIcon: HTMLElement,
private duration = 1500
) {}
showCopied() {
this.copyIcon.classList.add('hidden');
this.checkIcon.classList.remove('hidden');
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => this.revert(), this.duration);
}
revert() {
this.checkIcon.classList.add('hidden');
this.copyIcon.classList.remove('hidden');
}
cleanup() {
if (this.timer) clearTimeout(this.timer);
}
}
+16
View File
@@ -0,0 +1,16 @@
export function createErrorDisplay(errorEl: HTMLElement) {
return {
show(msg: string) {
errorEl.textContent = msg;
errorEl.classList.remove('hidden');
},
clear() {
errorEl.textContent = '';
errorEl.classList.add('hidden');
},
};
}
export function isInteger(val: string): boolean {
return /^-?\d+$/.test(val.trim());
}