Sticky Note Slap Animation UI | React + CSS example
A React block that sticks a note wherever you press on the board (stored as a percentage of the board), unrolls the curled paper until it lands, and keeps the count in a tally. The unfold needs no images and no 3D: the face is clipped to a half-plane and a mirrored back-of-paper layer is stacked on top through the same fold, with a single custom property driving the fold from 0 to 1. The chosen note and a "press the board" hint sit right above the board; a ring spreads from the press point, the paper opens, presses down as it lands and the total ticks up, so choice and result stay on one screen. On narrow widths the three groups collapse into tabs so the selection and a 220px board fit in the first view, and the tally shows the total and the used items first with the full breakdown behind a toggle. Below the preview you can switch between the unpicked, peeling, settled, full and undone states, followed by a minimal usage example and a props table (groups for labels and colours, limit, peelMs, defaultPicked, and onChange to read the counts). All geometry is a fraction of the element's own edge, so the note size can stay fluid via clamp without touching the JavaScript. Once flat, a note drops the clip-path and mirror layer and becomes a single face, so 24 notes still only cost the few that are mid-unroll. Under prefers-reduced-motion nothing unrolls, ripples or bounces — the note simply appears where you pressed. The board is aria-hidden and the same information is carried by the tally list plus a role=status announcement; keyboard users get golden-ratio scattered positions. No dependencies, no image assets.
Preview
BLK-67標本 / 付箋の貼り板
押した場所に、付箋が開いて残る
詳しい説明
付箋を選んで、板の好きな場所を押してください。お引き受けできることを9枚の付箋にしました。貼った付箋は丸まった状態から紙が開いて着地し、そのまま板に残ります。控えの件数と内訳は、消さずにそのままご相談の内容にできます。貼った内容はこの画面の中だけで、送信も保存もされません。
LP・特設→ 板を押して貼る→ 板をタップして貼る
4/ 24- コーポレート1
- 採用ページ0
- LP・特設1
- 予約フォーム1
- 業務システム0
- データ連携0
- 保守・運用1
- 記事の更新0
- AI活用0
上限は24枚で、超えた分は古いものから外れます。送信も保存もされません。
状態の見本
押すと上の板がその状態になります。組み込む前に、各状態の見た目と案内文を確かめられます。
組み込み方
props を省けば、この見本と同じ9枚・24枚・720ms で動きます。件数は onChange で受け取り、フォームの本文などへ入れます。
import TagSlapBoard from "@/components/tag-slap-board";
<TagSlapBoard
groups={[
{ name: "メニュー", tone: "amber", items: [
{ id: "cut", label: "カット" },
{ id: "color", label: "カラー" },
]},
]}
limit={12}
peelMs={600}
onChange={(tally, total) => setRequest({ tally, total })}
/>- groups
- SlapGroup[]
- 束の名前・色(tone)・付箋のラベル。束は3つまでが狭い幅のタブに収まる
- groups[].tone
- "paper" | "amber" | "ink"
- 色。中身は TONE_FACE などの4つの表で、ここを書き換えると色が変わる
- limit
- number = 24
- 上限枚数。超えると古いものから外れる
- peelMs
- number = 720
- 紙が開き切るまでの時間(ms)。動きを減らす設定では使わず即座に貼る
- defaultPicked
- string | null
- 最初に選んでおく付箋の id。null で未選択から始める
- onChange
- (tally, total) => void
- 貼る・はがすたびに、項目ごとの件数と合計を受け取る(送信や保存はこちらで行う)
- guide
- boolean = true
- この「状態の見本・組み込み方」の欄を出すか
- headingTag
- "h1" | "h2" | "p"
- 見出しのタグ。置くページの見出しの順に合わせる
使っている機能の対応状況
- clip-path(半平面で紙を切る): Baseline 広く利用可能・2020年1月から主要ブラウザで利用可
- translate / rotate プロパティ(位置と傾きを transform と分ける): Baseline 広く利用可能・2022年8月から
- Element.animate()(出現・着地・押した位置の輪): Baseline 広く利用可能・2020年3月から
出典: MDN Web Docs の各ページ(clip-path・translate・rotate・Element.animate())の Baseline 表示。2026-11-17 確認。
Read the full description
A React block that sticks a note wherever you press on the board (stored as a percentage of the board), unrolls the curled paper until it lands, and keeps the count in a tally. The unfold needs no images and no 3D: the face is clipped to a half-plane and a mirrored back-of-paper layer is stacked on top through the same fold, with a single custom property driving the fold from 0 to 1. The chosen note and a "press the board" hint sit right above the board; a ring spreads from the press point, the paper opens, presses down as it lands and the total ticks up, so choice and result stay on one screen. On narrow widths the three groups collapse into tabs so the selection and a 220px board fit in the first view, and the tally shows the total and the used items first with the full breakdown behind a toggle. Below the preview you can switch between the unpicked, peeling, settled, full and undone states, followed by a minimal usage example and a props table (groups for labels and colours, limit, peelMs, defaultPicked, and onChange to read the counts). All geometry is a fraction of the element's own edge, so the note size can stay fluid via clamp without touching the JavaScript. Once flat, a note drops the clip-path and mirror layer and becomes a single face, so 24 notes still only cost the few that are mid-unroll. Under prefers-reduced-motion nothing unrolls, ripples or bounces — the note simply appears where you pressed. The board is aria-hidden and the same information is carried by the tally list plus a role=status announcement; keyboard users get golden-ratio scattered positions. No dependencies, no image assets.
- Added:
- 2026-09-18
- Updated:
- 2026-11-17
- Dependencies:
- None
- tags
- #block #interactive #sticky-note #paper #pointer #clip-path #stateful #tally #motion #no-image #no-dependency
"use client";
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { Montserrat } from "next/font/google";
const montserrat = Montserrat({
weight: ["500", "600", "700"],
subsets: ["latin"],
display: "swap",
preload: false,
});
/**
* 付箋を貼るアニメーションUI(BLK-67)
*
* 押した位置(板に対する%座標)に付箋を貼り、丸まった紙が開いて着地し、貼った件数を控えに残す。
* 動きは利用者の操作にだけ反応する(スクロール出現・自動再生なし)。
*
* 汎用技法メモ:
*
* 1. 「めくれた紙が開いて貼り付く」は clip-path の半平面+鏡像レイヤーの2枚で作れる
* 紙を角度θの折り目で2つに割り、①表面を「折り目の手前側」だけに clip し、②その上に
* 「紙の裏面(グラデーション)を折り目で鏡像反転させたもの」を同じ clip で重ねる。
* 折り目の位置 --p を 0→1 へ動かすと、裏面が減って表面が現れる=紙が開く。画像も3Dも要らない。
* 半平面の clip-path は、折り目上の点 P=fold*u と法線 u・接線 w から
* polygon(P+Bw, P-Bw, P-Bw-Bu, P+Bw-Bu) ※B は要素より十分大きい定数
* で書ける(辺を4点で囲むのではなく「十分大きい帯」で塗り潰す発想)。
*
* 2. 鏡映変換は matrix() を組まずに translate→rotate→scaleY(-1)→rotate→translate で書く
* matrix() の各引数に calc() を入れる書き方は環境差が出るうえ読めない。折り目の点へ原点を運び、
* 折り目の向きへ回し、Y反転し、戻す——の5段で同じ鏡映になる。transform-origin: 0 0 が条件。
*
* 3. 幾何をすべて「自分の辺長に対する割合」で持つと、要素サイズをCSS側で自由に決められる
* clip-path の座標も translate() の量も % が使えるので、単位正方形(1辺=1)で計算した値に
* 100% を掛けるだけでよい。付箋の大きさを clamp で可変にしてもJS側の計算は変わらない。
*
* 4. めくれ機構は「開き終わったら捨てる」
* 開き切った紙は clip-path も鏡像レイヤーも要らない。settled になった時点で表面1枚だけの
* 軽い状態に置き換える。貼った枚数が増えても、毎フレームの負荷は開いている最中の数枚だけ。
*
* 5. 位置は px でなく板に対する % で持つ
* 中心座標を % で持ち `translate: -50% -50%` で中央合わせすれば、リサイズしても相対位置が保たれる。
* 回転は rotate プロパティ、寄せは translate プロパティに分けると transform が空くので、
* 出現と着地の scale アニメーション(WAAPI)と喧嘩しない。
*
* 6. 盤面は読み上げ対象にしない
* 盤面は aria-hidden にし、同じ情報を控えのリストで持たせ、貼った瞬間だけ role="status" で知らせる。
* キーボード操作では座標が無いので、黄金比で散らした既定位置へ落とす。
*/
export type SlapTone = "paper" | "amber" | "ink";
export type SlapGroup = { name: string; tone: SlapTone; items: { id: string; label: string }[] };
export type SlapTally = { id: string; label: string; group: string; count: number }[];
type Item = { id: string; label: string; group: string; tone: SlapTone };
const DEFAULT_GROUPS: SlapGroup[] = [
{
name: "つくる",
tone: "paper",
items: [
{ id: "corp", label: "コーポレート" },
{ id: "recruit", label: "採用ページ" },
{ id: "lp", label: "LP・特設" },
],
},
{
name: "つなぐ",
tone: "amber",
items: [
{ id: "form", label: "予約フォーム" },
{ id: "system", label: "業務システム" },
{ id: "link", label: "データ連携" },
],
},
{
name: "つづける",
tone: "ink",
items: [
{ id: "ops", label: "保守・運用" },
{ id: "post", label: "記事の更新" },
{ id: "ai", label: "AI活用" },
],
},
];
const TONE_FACE: Record<SlapTone, string> = {
paper: "border-gray-300 bg-[#fffdf8] text-gray-900",
amber: "border-amber-700 bg-amber-600 text-white",
ink: "border-gray-900 bg-gray-900 text-white",
};
/** 付箋の上端の糊の帯(紙の向きが分かる程度にごく薄く) */
const TONE_GLUE: Record<SlapTone, string> = {
paper: "bg-gray-900/[0.045]",
amber: "bg-black/[0.07]",
ink: "bg-white/[0.07]",
};
const TONE_CHIP: Record<SlapTone, string> = {
paper: "border-gray-900 bg-gray-900 text-white",
amber: "border-amber-600 bg-amber-600 text-white",
ink: "border-gray-900 bg-gray-900 text-white",
};
const TONE_SWATCH: Record<SlapTone, string> = {
paper: "border-gray-400 bg-[#fffdf8]",
amber: "border-amber-700 bg-amber-600",
ink: "border-gray-900 bg-gray-900",
};
type Slap = {
id: number;
item: string;
/** 板に対する中心座標(%) */
x: number;
y: number;
/** 静止時の傾き(度) */
rot: number;
/** 折り目の向き(度) */
ang: number;
/** 開き終わって、めくれ機構を捨てた状態 */
settled: boolean;
/** 開きかけで止めておく見本(0〜1)。次に貼ったときに続きから開き切る */
hold?: number;
/** 止めていた見本を続きから開くときの開始値 */
from?: number;
};
/** 貼られた瞬間の開き具合(0=完全に丸まっている / 1=平ら) */
const START_P = 0.12;
/** 付箋の一辺。CSS側の clamp と同じ値をJS側の内側判定にも使う */
const SIZE_CSS = "clamp(4.25rem, 17%, 7.875rem)";
const SIZE_MIN = 68;
const SIZE_MAX = 126;
const SIZE_RATIO = 0.17;
/** 初期状態(SSRとクライアントで同じ値になるよう乱数を使わず直書きする)。1枚は開きかけで止めて技法を見せる */
const SEEDED: Slap[] = [
{ id: -4, item: "corp", x: 22, y: 34, rot: -7, ang: 34, settled: true },
{ id: -3, item: "form", x: 47, y: 64, rot: 5, ang: 128, settled: true },
{ id: -2, item: "ops", x: 80, y: 30, rot: -3, ang: 214, settled: true },
{ id: -1, item: "lp", x: 68, y: 66, rot: 8, ang: 312, settled: false, hold: 0.5 },
];
/** 状態の見本で使う、位置を固定した貼り跡 */
const scatter = (k: number, item: string, settled = true): Slap => ({
id: -100 - k,
item,
x: 14 + ((k * 61.803) % 72),
y: 18 + ((k * 38.197 + 21) % 64),
rot: -9 + ((k * 7.3) % 18),
ang: (k * 97) % 360,
settled,
});
/** groups の中身の鍵。配列リテラルで毎回作り直されても、中身が同じなら同じ値になる */
export function groupsKey(groups: SlapGroup[]): string {
return JSON.stringify(groups.map((g) => [g.name, g.tone, g.items.map((it) => [it.id, it.label])]));
}
/** onChange に渡す控えの鍵。前回と同じなら呼ばない(親が state に入れて再描画しても往復しない) */
export function tallyKey(tally: SlapTally, total: number): string {
return `${total}|${tally.map((t) => `${t.id}:${t.label}:${t.group}:${t.count}`).join(",")}`;
}
/** 説明文。既定の9枚のときだけ自社の前提を書き、onChange で受け取る側がいるなら「送らない」とは書かない */
export function guideCopy(isDefault: boolean, count: number, hasOnChange: boolean): { intro: string; privacy: string } {
const intro = isDefault
? "付箋を選んで、板の好きな場所を押してください。お引き受けできることを9枚の付箋にしました。貼った付箋は丸まった状態から紙が開いて着地し、そのまま板に残ります。控えの件数と内訳は、消さずにそのままご相談の内容にできます。"
: `付箋を選んで、板の好きな場所を押してください。選べる付箋は${count}枚です。貼った付箋は丸まった状態から紙が開いて着地し、そのまま板に残ります。控えに件数と内訳が出ます。`;
return { intro, privacy: hasOnChange ? "" : "貼った内容はこの画面の中だけで、送信も保存もされません。" };
}
/** 開きかけで止めていた見本を放す。通常は続きから開き、動きを減らす設定では貼り終えた状態にする */
export function releaseHeld<T extends { settled: boolean; hold?: number; from?: number }>(slaps: T[], reduced: boolean): T[] {
return slaps.map((s) => {
if (s.hold === undefined) return s;
return reduced ? { ...s, hold: undefined, from: undefined, settled: true } : { ...s, hold: undefined, from: s.hold };
});
}
type Preset = "unpicked" | "peeling" | "settled" | "full" | "undone";
const PRESETS: { key: Preset; label: string }[] = [
{ key: "unpicked", label: "未選択" },
{ key: "peeling", label: "貼付け中" },
{ key: "settled", label: "貼付け済み" },
{ key: "full", label: "上限" },
{ key: "undone", label: "取り消し後" },
];
/**
* 折り目の幾何。単位正方形(1辺=1)の4隅を折り目の法線 u へ射影し、
* 折り目が動く範囲 [min, min+span] を出す。すべて辺長に対する割合なので px に依存しない。
*/
function foldGeometry(angleDeg: number) {
const a = (angleDeg * Math.PI) / 180;
const u0 = Math.cos(a);
const u1 = Math.sin(a);
const projections = [
[0, 0],
[1, 0],
[1, 1],
[0, 1],
].map(([x, y]) => x * u0 + y * u1);
const min = Math.min(...projections);
const span = Math.max(...projections) - min;
return { u0, u1, w0: -u1, w1: u0, min, span };
}
/** 折り目より手前(=もう貼り付いた側)だけを残す半平面 */
const HALF_PLANE = [
"polygon(",
"calc((var(--fold) * var(--u0) + var(--big) * var(--w0)) * 100%)",
"calc((var(--fold) * var(--u1) + var(--big) * var(--w1)) * 100%),",
"calc((var(--fold) * var(--u0) - var(--big) * var(--w0)) * 100%)",
"calc((var(--fold) * var(--u1) - var(--big) * var(--w1)) * 100%),",
"calc((var(--fold) * var(--u0) - var(--big) * var(--w0) - var(--big) * var(--u0)) * 100%)",
"calc((var(--fold) * var(--u1) - var(--big) * var(--w1) - var(--big) * var(--u1)) * 100%),",
"calc((var(--fold) * var(--u0) + var(--big) * var(--w0) - var(--big) * var(--u0)) * 100%)",
"calc((var(--fold) * var(--u1) + var(--big) * var(--w1) - var(--big) * var(--u1)) * 100%)",
")",
].join(" ");
/** 折り目を軸にした鏡映(matrix を組まず5段の変換で書く) */
const REFLECT = [
"translate(calc(var(--fold) * var(--u0) * 100%), calc(var(--fold) * var(--u1) * 100%))",
"rotate(calc(var(--ca) * 1deg))",
"scaleY(-1)",
"rotate(calc(var(--ca) * -1deg))",
"translate(calc(var(--fold) * var(--u0) * -1 * 100%), calc(var(--fold) * var(--u1) * -1 * 100%))",
].join(" ");
/** めくれ上がった紙が落とす影。開くほど薄く、近くなる */
const FLAP_SHADOW =
"drop-shadow(0 calc((1 - var(--p)) * 0.45rem) calc((1 - var(--p)) * 0.55rem) rgb(28 25 23 / calc(0.3 * (1 - var(--p)))))";
const FLAP_BACK = "linear-gradient(calc(var(--ca) * 1deg), #f8f5f1, #d8d1c7)";
/** 着地後の接地感: 真下の薄い接地影+右下だけ浮いた角の影+角の反りの陰り */
const SETTLED_SHADOW =
"shadow-[0_1px_1px_rgb(28_25_23/0.16),3px_7px_9px_-7px_rgb(28_25_23/0.45)]";
const CURL = "linear-gradient(135deg, transparent 74%, rgb(255 255 255 / 0.14) 86%, rgb(28 25 23 / 0.1))";
const USAGE = `import TagSlapBoard from "@/components/tag-slap-board";
<TagSlapBoard
groups={[
{ name: "メニュー", tone: "amber", items: [
{ id: "cut", label: "カット" },
{ id: "color", label: "カラー" },
]},
]}
limit={12}
peelMs={600}
onChange={(tally, total) => setRequest({ tally, total })}
/>`;
const PROPS: { name: string; type: string; note: string }[] = [
{ name: "groups", type: "SlapGroup[]", note: "束の名前・色(tone)・付箋のラベル。束は3つまでが狭い幅のタブに収まる" },
{ name: "groups[].tone", type: '"paper" | "amber" | "ink"', note: "色。中身は TONE_FACE などの4つの表で、ここを書き換えると色が変わる" },
{ name: "limit", type: "number = 24", note: "上限枚数。超えると古いものから外れる" },
{ name: "peelMs", type: "number = 720", note: "紙が開き切るまでの時間(ms)。動きを減らす設定では使わず即座に貼る" },
{ name: "defaultPicked", type: "string | null", note: "最初に選んでおく付箋の id。null で未選択から始める" },
{ name: "onChange", type: "(tally, total) => void", note: "貼る・はがすたびに、項目ごとの件数と合計を受け取る(送信や保存はこちらで行う)" },
{ name: "guide", type: "boolean = true", note: "この「状態の見本・組み込み方」の欄を出すか" },
{ name: "headingTag", type: '"h1" | "h2" | "p"', note: "見出しのタグ。置くページの見出しの順に合わせる" },
];
export default function TagSlapBoard({
headingTag: Heading = "h2",
groups = DEFAULT_GROUPS,
limit = 24,
peelMs = 720,
defaultPicked = "lp",
onChange,
guide = true,
}: {
/** 見出しのタグ。ギャラリーのプレビューは "p" を渡して見出しの重複を避ける */
headingTag?: "h1" | "h2" | "p";
groups?: SlapGroup[];
limit?: number;
peelMs?: number;
defaultPicked?: string | null;
onChange?: (tally: SlapTally, total: number) => void;
guide?: boolean;
}) {
// 配列リテラルで渡されても再計算しないよう、中身の鍵で覚える
const gKey = groupsKey(groups);
const items = useMemo<Item[]>(
() => groups.flatMap((g) => g.items.map((it) => ({ id: it.id, label: it.label, group: g.name, tone: g.tone }))),
// eslint-disable-next-line react-hooks/exhaustive-deps
[gKey],
);
const copy = guideCopy(groups === DEFAULT_GROUPS, items.length, !!onChange);
const byId = useMemo(() => new Map(items.map((it) => [it.id, it])), [items]);
const [slaps, setSlaps] = useState<Slap[]>(() => SEEDED.filter((s) => byId.has(s.item)));
const [picked, setPicked] = useState<string | null>(defaultPicked);
const [tab, setTab] = useState(() => Math.max(0, groups.findIndex((g) => g.items.some((it) => it.id === defaultPicked))));
const [notice, setNotice] = useState("");
const [warn, setWarn] = useState(false);
const [tallyOpen, setTallyOpen] = useState(false);
const [preset, setPreset] = useState<Preset | null>(null);
const [mark, setMark] = useState<{ id: number; x: number; y: number } | null>(null);
const boardRef = useRef<HTMLDivElement>(null);
const markRef = useRef<HTMLSpanElement>(null);
const totalRef = useRef<HTMLSpanElement>(null);
const wideTotalRef = useRef<HTMLSpanElement>(null);
const chipsRef = useRef<HTMLDivElement>(null);
const seqRef = useRef(1);
const keySeqRef = useRef(0);
/** 開いている最中の付箋: id → [開き始めた時刻, 開き始めの --p] */
const activeRef = useRef(new Map<number, [number, number]>());
const reducedRef = useRef(false);
const onChangeRef = useRef(onChange);
const lastTotalRef = useRef(slaps.length);
const lastTallyRef = useRef("");
useEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);
useEffect(() => {
const mql = window.matchMedia("(prefers-reduced-motion: reduce)");
const sync = () => {
reducedRef.current = mql.matches;
};
sync();
mql.addEventListener("change", sync);
// 動きを減らす設定では、開きかけの見本も最初から貼り終えた状態で見せる
if (mql.matches) setSlaps((prev) => prev.map((s) => (s.settled ? s : { ...s, settled: true, hold: undefined })));
return () => mql.removeEventListener("change", sync);
}, []);
// 貼られた直後の付箋を登録し、開いている最中のものだけを毎フレーム進める。
// slaps が変わるたびにループを張り直すが、経過時間は activeRef が持っているので進行は途切れない。
useEffect(() => {
const board = boardRef.current;
if (!board) return;
for (const s of slaps) {
if (s.settled || s.hold !== undefined || activeRef.current.has(s.id)) continue;
const el = board.querySelector<HTMLElement>(`[data-slap="${s.id}"]`);
if (!el) continue;
const from = s.from ?? START_P;
activeRef.current.set(s.id, [performance.now(), from]);
if (s.from === undefined) {
el.animate(
[
{ opacity: 0, transform: "scale(1.08)" },
{ opacity: 1, transform: "scale(1)" },
],
{ duration: 220, easing: "cubic-bezier(0.22, 0.8, 0.3, 1)" },
);
}
}
if (activeRef.current.size === 0) return;
let raf = 0;
const loop = (now: number) => {
const finished: number[] = [];
activeRef.current.forEach(([start, from], id) => {
const el = board.querySelector<HTMLElement>(`[data-slap="${id}"]`);
if (!el) {
activeRef.current.delete(id);
return;
}
const t = Math.min(1, (now - start) / peelMs);
const eased = 1 - Math.pow(1 - t, 3);
el.style.setProperty("--p", (from + (1 - from) * eased).toFixed(4));
if (t >= 1) {
finished.push(id);
// 着地: 紙が板に押さえ付けられるように一瞬だけ縮む
el.animate([{ transform: "scale(1.035)" }, { transform: "scale(0.985)" }, { transform: "scale(1)" }], {
duration: 200,
easing: "ease-out",
});
}
});
finished.forEach((id) => activeRef.current.delete(id));
if (finished.length > 0) {
setSlaps((prev) => prev.map((s) => (finished.includes(s.id) ? { ...s, settled: true } : s)));
return;
}
if (activeRef.current.size > 0) raf = requestAnimationFrame(loop);
};
raf = requestAnimationFrame(loop);
return () => cancelAnimationFrame(raf);
}, [slaps, peelMs]);
// 件数の変化: 合計の数字を小さく跳ねさせ、利用側へ渡す
useEffect(() => {
const total = slaps.length;
if (total !== lastTotalRef.current) {
lastTotalRef.current = total;
if (!reducedRef.current) {
for (const el of [totalRef.current, wideTotalRef.current]) {
el?.animate([{ transform: "translateY(-0.18em)", color: "#b45309" }, { transform: "none" }], {
duration: 320,
easing: "cubic-bezier(0.22, 0.8, 0.3, 1)",
});
}
}
}
const counts = new Map<string, number>();
for (const s of slaps) counts.set(s.item, (counts.get(s.item) ?? 0) + 1);
const tally = items.map((it) => ({ id: it.id, label: it.label, group: it.group, count: counts.get(it.id) ?? 0 }));
const key = tallyKey(tally, total);
if (key === lastTallyRef.current) return;
lastTallyRef.current = key;
onChangeRef.current?.(tally, total);
}, [slaps, items]);
// 押した位置の反応: 輪が広がって消える
useEffect(() => {
if (!mark || reducedRef.current) return;
markRef.current?.animate(
[
{ opacity: 0.7, transform: "scale(0.35)" },
{ opacity: 0, transform: "scale(1.5)" },
],
{ duration: 460, easing: "cubic-bezier(0.22, 0.8, 0.3, 1)", fill: "forwards" },
);
}, [mark]);
const pick = (id: string) => {
setPicked(id);
setWarn(false);
setNotice("");
setPreset(null);
};
const place = useCallback(
(clientX: number | null, clientY: number | null) => {
const board = boardRef.current;
if (!board) return;
const item = picked ? byId.get(picked) : undefined;
if (!item) {
// 未選択のまま押された: 選ぶ場所を示す
setWarn(true);
setNotice("");
if (!reducedRef.current) {
chipsRef.current?.animate([{ backgroundColor: "#fef3c7" }, { backgroundColor: "transparent" }], { duration: 700 });
}
return;
}
const rect = board.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const size = Math.min(SIZE_MAX, Math.max(SIZE_MIN, rect.width * SIZE_RATIO));
// 傾くぶん外接する箱は少し大きい。1.12 を掛けて端でもはみ出させない
const marginX = ((size * 1.12) / 2 / rect.width) * 100;
const marginY = ((size * 1.12) / 2 / rect.height) * 100;
let x: number;
let y: number;
if (clientX === null || clientY === null) {
// キーボード操作には座標が無いので、黄金比で散らした既定位置へ落とす
const k = keySeqRef.current++;
x = 14 + ((k * 61.803) % 72);
y = 16 + ((k * 38.197 + 21) % 68);
} else {
x = ((clientX - rect.left) / rect.width) * 100;
y = ((clientY - rect.top) / rect.height) * 100;
setMark({ id: seqRef.current, x, y });
}
const slap: Slap = {
id: seqRef.current++,
item: item.id,
x: Math.min(100 - marginX, Math.max(marginX, x)),
y: Math.min(100 - marginY, Math.max(marginY, y)),
rot: -11 + Math.random() * 22,
ang: Math.random() * 360,
settled: reducedRef.current,
};
const dropped = slaps.length + 1 > limit;
setSlaps((prev) => {
// 開きかけで止めていた見本は、続きから開き切らせる(動きを減らす設定では貼り終えた状態にする)
const next = [...releaseHeld(prev, reducedRef.current), slap];
return next.length > limit ? next.slice(next.length - limit) : next;
});
setWarn(false);
setPreset(null);
setNotice(dropped ? `上限${limit}枚のため、古い1枚を外して貼りました` : `${item.label}を貼りました`);
},
[picked, byId, limit, slaps.length],
);
const showPreset = (key: Preset) => {
activeRef.current.clear();
keySeqRef.current = 0;
const first = items[0]?.id ?? "";
const pickedId = picked ?? items[2]?.id ?? first;
const at = (i: number) => items[i % Math.max(1, items.length)]?.id ?? first;
const base = SEEDED.filter((s) => byId.has(s.item)).map((s) => ({ ...s, settled: true, hold: undefined }));
const settledFive = [...base, scatter(1, at(4)), scatter(2, at(7))];
setPreset(key);
setWarn(false);
setMark(null);
if (key === "unpicked") {
setPicked(null);
setSlaps(base);
setNotice("");
} else if (key === "peeling") {
setPicked(pickedId);
setSlaps([...base, { id: seqRef.current++, item: pickedId, x: 50, y: 50, rot: -4, ang: 150, settled: false, hold: 0.42 }]);
setNotice("開いている途中で止めています(次に貼ると続きから開きます)");
} else if (key === "settled") {
setPicked(pickedId);
setSlaps(settledFive);
setNotice(`${byId.get(at(7))?.label ?? ""}を貼りました`);
} else if (key === "full") {
setPicked(pickedId);
setSlaps(Array.from({ length: limit }, (_, k) => scatter(k, at(k))));
setNotice(`上限の${limit}枚。次は古いものから外れます`);
} else {
setPicked(pickedId);
setSlaps(settledFive.slice(0, -1));
setNotice("1枚はがしました");
}
};
const counts = useMemo(() => {
const map = new Map<string, number>();
for (const s of slaps) map.set(s.item, (map.get(s.item) ?? 0) + 1);
return map;
}, [slaps]);
const peak = useMemo(() => Math.max(1, ...Array.from(counts.values())), [counts]);
const pickedItem = picked ? byId.get(picked) : undefined;
const used = items.filter((it) => (counts.get(it.id) ?? 0) > 0);
return (
<section aria-labelledby="tag-slap-board-heading" className="@container w-full max-w-4xl bg-white px-1">
<header className="max-w-[42rem]">
<p className="hidden items-center gap-2.5 text-[11px] text-gray-400 @md:flex">
<span aria-hidden="true" className="h-px w-5 bg-amber-600" />
<span className={`${montserrat.className} font-semibold text-gray-500`}>BLK-67</span>
<span>標本 / 付箋の貼り板</span>
</p>
<Heading
id="tag-slap-board-heading"
className="text-[clamp(1.3rem,3vw,1.85rem)] leading-[1.35] font-bold tracking-tight text-balance text-gray-900 @md:mt-2.5"
>
押した場所に、付箋が開いて残る
</Heading>
<p className="mt-1.5 hidden text-[14px] leading-[1.8] font-medium text-gray-600 @md:block">
付箋を選んで、板の好きな場所を押してください。貼った数は控えに残ります。
</p>
<details className="group text-[12.5px] leading-[1.9] text-gray-500">
<summary className="inline-flex min-h-8 cursor-pointer items-center gap-1 font-bold text-gray-700 marker:content-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600">
<span aria-hidden="true" className="text-amber-700 transition-transform group-open:rotate-90 motion-reduce:transition-none">
›
</span>
詳しい説明
</summary>
<p className="mt-1 pb-1">
{copy.intro}
{copy.privacy}
</p>
</details>
</header>
{/* 付箋立て: 狭い幅は束のタブ+その束の3枚、広い幅は3つの束を hairline で仕切って並べる */}
<div ref={chipsRef} className="mt-3 border-t border-gray-200 pt-3 @2xl:pt-4">
<div className="mb-2.5 flex border-b border-gray-200 @2xl:hidden">
{groups.map((group, gi) => (
<button
key={group.name}
type="button"
aria-pressed={tab === gi}
onClick={() => setTab(gi)}
className={`-mb-px flex-1 border-b-2 py-1.5 text-[12px] leading-none font-bold tracking-[0.04em] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-amber-600 ${
tab === gi ? "border-amber-600 text-gray-900" : "border-transparent text-gray-400"
}`}
>
{group.name}
</button>
))}
</div>
<div className="@2xl:flex">
{groups.map((group, gi) => (
<div
key={group.name}
className={`${tab === gi ? "flex" : "hidden"} flex-wrap items-center gap-x-2 gap-y-2 @2xl:flex @2xl:flex-1 @2xl:gap-x-3 ${
gi === 0 ? "" : "@2xl:border-l @2xl:border-gray-200 @2xl:pl-5"
} ${gi === groups.length - 1 ? "" : "@2xl:pr-5"}`}
>
<span className="hidden w-full text-[11px] leading-none font-bold tracking-[0.06em] text-gray-400 @2xl:block">
{group.name}
</span>
{group.items.map((it) => {
const on = picked === it.id;
return (
<button
key={it.id}
type="button"
aria-pressed={on}
onClick={() => pick(it.id)}
className={`border px-2.5 py-2 text-[12px] leading-none font-bold tracking-tight transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 motion-reduce:transition-none @2xl:py-1.5 ${
on
? TONE_CHIP[group.tone]
: "border-gray-200 bg-white text-gray-600 hover:border-gray-400 hover:text-gray-900"
}`}
>
{it.label}
</button>
);
})}
</div>
))}
</div>
</div>
{/* 選択と結果をつなぐ1行: 何を選んでいるか・次に何をするか・今何枚か */}
<div className="mt-3 flex min-h-9 items-center justify-between gap-3 border border-b-0 border-gray-200 bg-gray-50/70 px-3 py-1.5">
<p className="flex min-w-0 items-center gap-2 text-[12px] leading-[1.5] font-medium text-gray-600">
{pickedItem ? (
<>
<span aria-hidden="true" className={`h-3 w-3 shrink-0 border ${TONE_SWATCH[pickedItem.tone]}`} />
<span className="shrink-0 font-bold text-gray-900">{pickedItem.label}</span>
<span className="min-w-0 leading-[1.4] text-gray-500">
{notice ? (
// 名前は左に出ているので、貼った知らせは名前を省いて短く出す
notice.startsWith(`${pickedItem.label}を`) ? `→ ${notice.slice(pickedItem.label.length + 1)}` : notice
) : (
<>
<span className="[@media(pointer:coarse)]:hidden">→ 板を押して貼る</span>
<span className="hidden [@media(pointer:coarse)]:inline">→ 板をタップして貼る</span>
</>
)}
</span>
</>
) : (
<span className={warn ? "font-bold text-amber-700" : ""}>
{warn ? "先に上の付箋を1枚選んでください" : "付箋を1枚選んでください"}
</span>
)}
</p>
<span className={`${montserrat.className} flex shrink-0 items-baseline gap-1 text-gray-900 @2xl:hidden`}>
<span ref={totalRef} className="inline-block text-[1.15rem] leading-none font-semibold tabular-nums">
{slaps.length}
</span>
<span className="text-[10px] font-semibold text-gray-400">/ {limit}</span>
</span>
</div>
<div className="flex flex-col border border-gray-200 @2xl:flex-row">
{/* 板 */}
<div
ref={boardRef}
className="relative min-h-[13.75rem] flex-1 overflow-hidden bg-[radial-gradient(rgb(28_25_23/0.07)_1px,transparent_1px)] [background-size:14px_14px] @md:min-h-[19rem]"
>
{slaps.length === 0 && (
<p className="pointer-events-none absolute inset-0 flex items-center justify-center text-[13px] font-medium text-gray-300">
板が空になりました
</p>
)}
<div aria-hidden="true" className="absolute inset-0 select-none">
{slaps.map((s) => {
const item = byId.get(s.item);
if (!item) return null;
const g = foldGeometry(s.ang);
const base: Record<string, string | number> = {
left: `${s.x}%`,
top: `${s.y}%`,
width: SIZE_CSS,
aspectRatio: "1",
translate: "-50% -50%",
rotate: `${s.rot.toFixed(2)}deg`,
};
if (!s.settled) {
Object.assign(base, {
"--u0": g.u0.toFixed(5),
"--u1": g.u1.toFixed(5),
"--w0": g.w0.toFixed(5),
"--w1": g.w1.toFixed(5),
"--min": g.min.toFixed(5),
"--span": g.span.toFixed(5),
"--ca": (s.ang + 90).toFixed(2),
"--big": 6,
"--p": s.hold ?? s.from ?? START_P,
"--fold": "calc(var(--min) + var(--span) * var(--p))",
});
}
return (
<div key={s.id} data-slap={s.id} className="pointer-events-none absolute" style={base as CSSProperties}>
<div
className={`absolute inset-0 flex flex-col justify-between overflow-hidden border p-2 ${TONE_FACE[item.tone]} ${
s.settled ? SETTLED_SHADOW : ""
}`}
style={s.settled ? { backgroundImage: CURL } : { clipPath: HALF_PLANE }}
>
<span aria-hidden="true" className={`absolute inset-x-0 top-0 h-[22%] ${TONE_GLUE[item.tone]}`} />
<span className="relative text-[8.5px] leading-none font-bold tracking-[0.08em] opacity-65">
{item.group}
</span>
<span className="relative text-[10.5px] leading-[1.4] font-bold tracking-tight break-words">
{item.label}
</span>
</div>
{!s.settled && (
<div className="absolute inset-0" style={{ clipPath: HALF_PLANE, filter: FLAP_SHADOW }}>
<div className="absolute inset-0" style={{ transformOrigin: "0 0", transform: REFLECT }}>
<div className="absolute inset-0 border border-gray-300" style={{ backgroundImage: FLAP_BACK }} />
</div>
</div>
)}
</div>
);
})}
</div>
{mark && (
<span
key={mark.id}
ref={markRef}
aria-hidden="true"
className="pointer-events-none absolute h-14 w-14 rounded-full border-2 border-amber-600 opacity-0"
style={{ left: `${mark.x}%`, top: `${mark.y}%`, translate: "-50% -50%" }}
/>
)}
{/* 板全面が貼り付けボタン。ポインタは押した瞬間、キーボードは click(detail=0)で拾う */}
<button
type="button"
aria-label={pickedItem ? `板に「${pickedItem.label}」を貼る` : "板(先に付箋を選んでください)"}
onPointerDown={(e) => place(e.clientX, e.clientY)}
onClick={(e) => {
if (e.detail === 0) place(null, null);
}}
className={`absolute inset-0 z-10 bg-transparent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-amber-600 ${
pickedItem ? "cursor-crosshair" : "cursor-not-allowed"
}`}
/>
</div>
{/* 控え: 狭い幅は合計と使った項目を先に出し、全項目の内訳は開閉式 */}
<div className="shrink-0 border-t border-gray-200 @2xl:w-[13.5rem] @2xl:border-t-0 @2xl:border-l">
<div className="flex items-center justify-between gap-3 px-4 py-2.5 @2xl:border-b @2xl:border-gray-200 @2xl:py-3.5">
<span className="min-w-0">
<span className="block text-[11px] font-bold tracking-[0.06em] text-gray-500">貼った控え</span>
<span className="mt-1 block truncate text-[11.5px] text-gray-500 @2xl:hidden">
{used.length === 0 ? "まだありません" : used.map((it) => `${it.label} ${counts.get(it.id)}`).join("・")}
</span>
</span>
<button
type="button"
aria-expanded={tallyOpen}
aria-controls="tag-slap-board-tally"
onClick={() => setTallyOpen((v) => !v)}
className="min-h-9 shrink-0 border border-gray-300 px-2.5 text-[11.5px] leading-none font-bold whitespace-nowrap text-gray-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 @2xl:hidden"
>
{tallyOpen ? "内訳を閉じる" : "内訳を見る"}
</button>
<span className={`${montserrat.className} hidden items-baseline gap-1 text-gray-900 @2xl:flex`}>
<span ref={wideTotalRef} className="inline-block text-[1.6rem] leading-none font-semibold tabular-nums">
{slaps.length}
</span>
<span className="text-[10px] font-semibold text-gray-400">/ {limit}</span>
</span>
</div>
<ul id="tag-slap-board-tally" className={`${tallyOpen ? "block" : "hidden"} border-t border-gray-200 px-4 py-1 @2xl:block @2xl:border-t-0`}>
{items.map((item, i) => {
const n = counts.get(item.id) ?? 0;
const prev = items[i - 1];
return (
<li
key={item.id}
className={`py-2 ${prev && prev.group !== item.group ? "mt-1 border-t border-gray-200 pt-3" : ""}`}
>
<span className="flex items-baseline justify-between gap-2">
<span
className={`text-[12px] leading-none font-bold tracking-tight ${n > 0 ? "text-gray-900" : "text-gray-300"}`}
>
{item.label}
</span>
<span
className={`${montserrat.className} text-[12px] leading-none font-semibold tabular-nums ${n > 0 ? "text-amber-700" : "text-gray-300"}`}
>
{n}
</span>
</span>
<span aria-hidden="true" className="mt-2 block h-px bg-gray-100">
{/* 伸縮は width ではなく scaleX(レイアウトを起こさない) */}
<span
className="block h-px origin-left bg-amber-600 transition-transform duration-300 ease-out motion-reduce:transition-none"
style={{ transform: `scaleX(${(n / peak).toFixed(3)})` }}
/>
</span>
</li>
);
})}
</ul>
</div>
</div>
<p role="status" aria-live="polite" className="sr-only">
{notice ? `${notice}。合計${slaps.length}枚` : warn ? "先に付箋を1枚選んでください" : ""}
</p>
<div className="mt-4 flex flex-col gap-3 @md:flex-row @md:items-center @md:justify-between">
<div className="flex shrink-0 items-center gap-2">
<button
type="button"
disabled={slaps.length === 0}
onClick={() => {
setSlaps((prev) => prev.slice(0, -1));
setNotice("1枚はがしました");
setPreset(null);
}}
className="border border-gray-300 px-3.5 py-2.5 text-[12px] leading-none font-bold tracking-tight whitespace-nowrap text-gray-700 transition-colors duration-200 hover:border-gray-900 hover:text-gray-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 disabled:border-gray-200 disabled:text-gray-300 motion-reduce:transition-none"
>
1枚はがす
</button>
<button
type="button"
disabled={slaps.length === 0}
onClick={() => {
setSlaps([]);
setNotice("すべてはがしました");
setPreset(null);
}}
className="border border-gray-300 px-3.5 py-2.5 text-[12px] leading-none font-bold tracking-tight whitespace-nowrap text-gray-700 transition-colors duration-200 hover:border-gray-900 hover:text-gray-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 disabled:border-gray-200 disabled:text-gray-300 motion-reduce:transition-none"
>
全部はがす
</button>
</div>
<p className="text-[12px] leading-[1.8] text-gray-500">
上限は{limit}枚で、超えた分は古いものから外れます。{copy.privacy && "送信も保存もされません。"}
</p>
</div>
{guide && (
<div className="mt-8 border-t border-gray-200 pt-6">
<h3 className="text-[15px] leading-[1.5] font-bold tracking-tight text-gray-900">状態の見本</h3>
<p className="mt-1 text-[12.5px] leading-[1.8] text-gray-500">
押すと上の板がその状態になります。組み込む前に、各状態の見た目と案内文を確かめられます。
</p>
<div className="mt-3 flex flex-wrap gap-2">
{PRESETS.map((p) => (
<button
key={p.key}
type="button"
aria-pressed={preset === p.key}
onClick={() => showPreset(p.key)}
className={`border px-3 py-2 text-[12px] leading-none font-bold tracking-tight transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600 motion-reduce:transition-none ${
preset === p.key
? "border-amber-600 bg-amber-600 text-white"
: "border-gray-300 bg-white text-gray-700 hover:border-gray-900"
}`}
>
{p.label}
</button>
))}
</div>
<h3 className="mt-8 text-[15px] leading-[1.5] font-bold tracking-tight text-gray-900">組み込み方</h3>
<p className="mt-1 text-[12.5px] leading-[1.8] text-gray-500">
props を省けば、この見本と同じ9枚・24枚・720ms で動きます。件数は onChange で受け取り、フォームの本文などへ入れます。
</p>
<pre className="mt-3 overflow-x-auto border border-gray-200 bg-gray-50 p-3 text-[11.5px] leading-[1.7] text-gray-800">
<code>{USAGE}</code>
</pre>
<dl className="mt-4 border-t border-gray-200 text-[12px] leading-[1.7]">
{PROPS.map((p) => (
<div key={p.name} className="grid gap-x-4 gap-y-0.5 border-b border-gray-200 py-2.5 @md:grid-cols-[9rem_11rem_1fr]">
<dt className="font-mono font-bold text-gray-900">{p.name}</dt>
<dd className="font-mono text-[11px] text-amber-800">{p.type}</dd>
<dd className="text-gray-600">{p.note}</dd>
</div>
))}
</dl>
<h3 className="mt-8 text-[15px] leading-[1.5] font-bold tracking-tight text-gray-900">使っている機能の対応状況</h3>
<ul className="mt-2 text-[12.5px] leading-[1.9] text-gray-600">
<li>clip-path(半平面で紙を切る): Baseline 広く利用可能・2020年1月から主要ブラウザで利用可</li>
<li>translate / rotate プロパティ(位置と傾きを transform と分ける): Baseline 広く利用可能・2022年8月から</li>
<li>Element.animate()(出現・着地・押した位置の輪): Baseline 広く利用可能・2020年3月から</li>
</ul>
<p className="mt-2 text-[11.5px] leading-[1.8] text-gray-400">
出典: MDN Web Docs の各ページ(
<a className="underline underline-offset-2 hover:text-gray-700" href="https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path">clip-path</a>・
<a className="underline underline-offset-2 hover:text-gray-700" href="https://developer.mozilla.org/en-US/docs/Web/CSS/translate">translate</a>・
<a className="underline underline-offset-2 hover:text-gray-700" href="https://developer.mozilla.org/en-US/docs/Web/CSS/rotate">rotate</a>・
<a className="underline underline-offset-2 hover:text-gray-700" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/animate">Element.animate()</a>
)の Baseline 表示。2026-11-17 確認。
</p>
</div>
)}
</section>
);
}
Add to your project via shadcn CLI
npx shadcn@latest add https://designs.first-ch.com/r/tag-slap-board.json