From f596e6698343a310823da954e7d211559210c036 Mon Sep 17 00:00:00 2001 From: hypercross Date: Thu, 26 Feb 2026 09:18:05 +0800 Subject: [PATCH] fix: dice url key --- content/index.md | 2 +- src/components/dice.tsx | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/content/index.md b/content/index.md index d3d98e1..173d50b 100644 --- a/content/index.md +++ b/content/index.md @@ -10,7 +10,7 @@ :md-dice[2d6] -:md-dice[1d20+d8] +:md-dice[3d6kh1] :md-dice[3d6dl2-1] :md-dice[3d6+5]{key="attack"} diff --git a/src/components/dice.tsx b/src/components/dice.tsx index 87974de..265310b 100644 --- a/src/components/dice.tsx +++ b/src/components/dice.tsx @@ -128,8 +128,17 @@ function getDiceResultFromUrl(key: string): number | null { return value ? parseInt(value) : null; } -// TODO:使用history.pushState -function setDiceResultToUrl(key: string, value: number) {} +function setDiceResultToUrl(key: string, value: number | null) { + if (typeof window === "undefined") return; + const params = new URLSearchParams(window.location.search); + if (value === null) { + params.delete(`dice-${key}`); + } else { + params.set(`dice-${key}`, value.toString()); + } + const newUrl = `${window.location.pathname}${params.toString() ? `?${params.toString()}` : ""}${window.location.hash}`; + window.history.pushState({}, "", newUrl); +} customElement("md-dice", { key: "" }, (props, { element }) => { noShadowDOM(); @@ -160,7 +169,9 @@ customElement("md-dice", { key: "" }, (props, { element }) => { setResult(rollResult.total); setRollDetail(rollResult.detail); setIsRolled(true); - // TODO:保存结果到url + if (effectiveKey()) { + setDiceResultToUrl(effectiveKey(), rollResult.total); + } }; const handleTextClick = () => { @@ -168,7 +179,9 @@ customElement("md-dice", { key: "" }, (props, { element }) => { setResult(null); setIsRolled(false); setRollDetail(""); - // TODO:从url中移除结果 + if (effectiveKey()) { + setDiceResultToUrl(effectiveKey(), null); + } }; const displayText = () => (isRolled() ? `${result()}` : formula);