BLK-117Blocks

お店の「今年のまとめ」ストーリー|タップでめくる6枚を1080×1920の画像で保存

年末にSNSのストーリーで店の1年を振り返るための、9:16のまとめを作る部品です。見本は架空のパン屋の6枚で、『2026年のまとめ』『焼いたパン 38,400個』『いちばん人気 塩バターロール』『新しく出した商品 12品』『いちばん忙しかった日 12/24』『来年もよろしくお願いします』と進みます。右側をタップするか→キーで次へ、左側で戻り、長押しの間は止まります。上の細い線が1本ずつ埋まり、各1枚は5秒で自動で進みます(止める切替つき)。数字は数え上がって出ます。最初の画面は店名の入力1つとストーリー1つだけで、6枚の見出し・数字・単位・ひとことは畳んだ欄で変えられます。入れた内容はURLの#に入るので、同じURLで同じまとめが開けます。今の1枚は1080×1920のPNGで保存でき、画面と画像は同じ部品表から描くので見たままの1枚になります。入れた内容入りのReact(TSX)のコードもコピーできます。prefers-reduced-motionでは自動送り・数え上がり・フェードを止めます。新しい依存はありません。

プレビュー

BLK-117 年末のまとめ

1080×1920

お店の1年を、
6枚のストーリーに

右をタップで次へ、左で戻る、長押しで止まります。見本はパン屋の1年です。

1枚目: 2026年のまとめ

5秒ごとに自動で進みます

6枚の見出しと数字を変える

入れた枚がその場で表示されます。数字だけを入れると数え上がって出ます(例: 38400)。

  1. 01表紙

  2. 022枚目

  3. 033枚目

  4. 044枚目

  5. 055枚目

  6. 06結び

URL の # のあとに入れた内容が入ります。どこにも送られず、同じ URL を開くと同じまとめが出ます。

このストーリーの React コードをコピー

入れた6枚と店名が入った TSX の1ファイルです(依存なし・Tailwind CSS v4)。

"use client";

import { useEffect, useRef, useState } from "react";

// 今年のまとめストーリー(タップでめくる9:16・依存なし・React + Tailwind CSS v4)
// 右側のタップと→キーで次へ、左側と←キーで戻る。長押しの間は止まる。5秒で自動で進む。
const SHOP = "パン屋 むぎあかり";
const SLIDES: { title: string; value: string; unit: string; note: string }[] = [
  {
    "title": "2026年のまとめ",
    "value": "",
    "unit": "",
    "note": "1年分の数字を、6枚で振り返ります"
  },
  {
    "title": "焼いたパン",
    "value": "38400",
    "unit": "個",
    "note": "毎朝5時から、窯の前で"
  },
  {
    "title": "いちばん人気",
    "value": "塩バターロール",
    "unit": "",
    "note": "3人に1人が買っていった定番"
  },
  {
    "title": "新しく出した商品",
    "value": "12",
    "unit": "品",
    "note": "いちばんの新顔は 柚子あんぱん"
  },
  {
    "title": "いちばん忙しかった日",
    "value": "12/24",
    "unit": "",
    "note": "シュトーレンが午前中に完売"
  },
  {
    "title": "来年もよろしくお願いします",
    "value": "",
    "unit": "",
    "note": "新年は 1/5(火)から焼きます"
  }
];
const SLIDE_MS = 5000;
const HOLD_MS = 220;

const toNum = (v: string) => {
  const t = v.trim().replace(/[,,]/g, "");
  return /^\d{1,9}$/.test(t) ? Number(t) : null;
};

export default function YearRecapStory() {
  const [i, setI] = useState(0);
  const [auto, setAuto] = useState(true);
  const [held, setHeld] = useState(false);
  const [shown, setShown] = useState<number | null>(null);
  const fill = useRef<HTMLDivElement>(null);
  const elapsed = useRef(0);
  const press = useRef<{ timer: number; long: boolean } | null>(null);
  const reduced = useRef(false);

  const go = (n: number) => {
    elapsed.current = 0;
    setI((n + SLIDES.length) % SLIDES.length);
  };
  // 最後の1枚で止まっていたら最初から再開する
  const toggle = () => {
    elapsed.current = 0;
    if (!auto && i === SLIDES.length - 1) go(0);
    setAuto((a) => !a);
  };

  useEffect(() => {
    reduced.current = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduced.current) setAuto(false);
  }, []);

  // 自動送り。止めている間と長押しの間は rAF を止め、経過時間はそのまま残す
  useEffect(() => {
    if (!auto || held) return;
    let last = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      elapsed.current += now - last;
      last = now;
      const p = Math.min(1, elapsed.current / SLIDE_MS);
      if (fill.current) fill.current.style.transform = "scaleX(" + p + ")";
      if (p < 1) raf = requestAnimationFrame(tick);
      else if (i < SLIDES.length - 1) go(i + 1);
      else setAuto(false);
    });
    return () => cancelAnimationFrame(raf);
  }, [i, auto, held]);

  // 数え上がり(動きを減らす設定では最初から終わりの値)
  useEffect(() => {
    const n = toNum(SLIDES[i].value);
    setShown(null);
    if (n === null || reduced.current) return;
    const t0 = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      const k = Math.min(1, (now - t0) / 900);
      setShown(Math.round(n * (1 - (1 - k) ** 3)));
      if (k < 1) raf = requestAnimationFrame(tick);
    });
    return () => cancelAnimationFrame(raf);
  }, [i]);

  const s = SLIDES[i];
  const n = toNum(s.value);
  const first = i === 0;
  const lastOne = i === SLIDES.length - 1;
  const m = first ? s.title.match(/^(\d{2,4})(.*)$/) : null;

  return (
    <div className="mx-auto w-full max-w-[360px]">
      <div
        role="group"
        aria-roledescription="ストーリー"
        aria-label={"今年のまとめ " + (i + 1) + " / " + SLIDES.length + "枚目(→で次・←で戻る・スペースで止める)"}
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === "ArrowRight") go(i + 1);
          else if (e.key === "ArrowLeft") go(i - 1);
          else if (e.key === " ") toggle();
          else return;
          e.preventDefault();
        }}
        onPointerDown={(e) => {
          e.currentTarget.setPointerCapture(e.pointerId);
          const p = { timer: 0, long: false };
          p.timer = window.setTimeout(() => {
            p.long = true;
            setHeld(true);
          }, HOLD_MS);
          press.current = p;
        }}
        onPointerUp={(e) => {
          const p = press.current;
          press.current = null;
          if (!p) return;
          clearTimeout(p.timer);
          if (p.long) return setHeld(false);
          const r = e.currentTarget.getBoundingClientRect();
          go((e.clientX - r.left) / r.width < 0.3 ? i - 1 : i + 1);
        }}
        onPointerCancel={() => {
          if (press.current) clearTimeout(press.current.timer);
          press.current = null;
          setHeld(false);
        }}
        onContextMenu={(e) => e.preventDefault()}
        className="relative aspect-[9/16] w-full cursor-pointer touch-manipulation overflow-hidden border border-stone-200 bg-white text-stone-900 outline-none select-none [-webkit-touch-callout:none] [container-type:inline-size] focus-visible:ring-2 focus-visible:ring-[#d97706] focus-visible:ring-offset-2"
      >
        <div className="absolute inset-x-[3.7cqi] top-[3.7cqi] flex gap-[0.9cqi]">
          {SLIDES.map((_, k) => (
            <div key={k} className="h-[0.6cqi] min-h-[2px] flex-1 overflow-hidden bg-stone-200">
              <div
                ref={k === i ? fill : undefined}
                className="h-full origin-left bg-[#d97706]"
                style={{ transform: "scaleX(" + (k < i || (k === i && !auto) ? 1 : 0) + ")" }}
              />
            </div>
          ))}
        </div>
        <div className="absolute inset-x-[3.7cqi] top-[7.8cqi] flex items-center gap-[2.2cqi] border-b border-stone-200 pb-[3.5cqi]">
          <span aria-hidden="true" className="grid size-[6.7cqi] place-items-center bg-stone-900 text-[3.3cqi] font-bold text-white">{SHOP.slice(0, 1)}</span>
          <span className="truncate text-[3.2cqi] font-bold">{SHOP}</span>
          <span className="ml-auto font-[Montserrat,sans-serif] text-[2.8cqi] font-semibold text-stone-600">{held ? "止めています" : i + 1 + " / " + SLIDES.length}</span>
        </div>
        <div key={i} className="absolute inset-x-[8.9cqi] top-1/2 -translate-y-1/2 motion-safe:animate-[recap-in_.24s_ease-out]">
          <div className="h-[0.75cqi] w-[11cqi] bg-[#d97706]" />
          {first ? (
            <p className="mt-[6cqi] text-[11.8cqi] leading-[1.25] font-bold">
              {m ? <span className="block font-[Montserrat,sans-serif] text-[34cqi] leading-none text-[#d97706]">{m[1]}</span> : null}
              {m ? m[2] : s.title}
            </p>
          ) : (
            <p className={lastOne ? "mt-[6cqi] text-[11.5cqi] leading-[1.3] font-bold" : "mt-[5cqi] text-[5.9cqi] leading-[1.35] font-bold text-stone-700"}>{s.title}</p>
          )}
          {!first && !lastOne && (
            <p className="mt-[4.4cqi] flex items-end gap-[1.8cqi] leading-none font-bold">
              <span className={n === null ? "text-[13cqi] leading-[1.22]" : "font-[Montserrat,sans-serif] text-[24cqi]"}>
                {n === null ? s.value : (shown ?? n).toLocaleString("ja-JP")}
              </span>
              {s.unit && <span className="pb-[2cqi] text-[9.6cqi] text-[#b45309]">{s.unit}</span>}
            </p>
          )}
          {s.note && <p className="mt-[5.9cqi] text-[4.1cqi] leading-[1.6] text-stone-600">{s.note}</p>}
          {(first || lastOne) && <p className="mt-[8cqi] text-[4.6cqi] font-bold text-stone-700">{SHOP}</p>}
        </div>
      </div>
      <div className="mt-3 flex gap-2">
        <button type="button" onClick={() => go(i - 1)} className="min-h-11 flex-1 border border-stone-300 bg-white text-[14px] font-bold focus-visible:outline-2 focus-visible:outline-[#d97706]">前の1枚</button>
        <button type="button" onClick={toggle} className="min-h-11 flex-1 border border-stone-300 bg-white text-[14px] font-bold focus-visible:outline-2 focus-visible:outline-[#d97706]">{auto ? "止める" : "再開する"}</button>
        <button type="button" onClick={() => go(i + 1)} className="min-h-11 flex-1 border border-stone-900 bg-stone-900 text-[14px] font-bold text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]">次の1枚</button>
      </div>
      <style>{"@keyframes recap-in{from{opacity:0;transform:translateY(12px)}}"}</style>
    </div>
  );
}
X でシェア

説明の全文を読む

年末にSNSのストーリーで店の1年を振り返るための、9:16のまとめを作る部品です。見本は架空のパン屋の6枚で、『2026年のまとめ』『焼いたパン 38,400個』『いちばん人気 塩バターロール』『新しく出した商品 12品』『いちばん忙しかった日 12/24』『来年もよろしくお願いします』と進みます。右側をタップするか→キーで次へ、左側で戻り、長押しの間は止まります。上の細い線が1本ずつ埋まり、各1枚は5秒で自動で進みます(止める切替つき)。数字は数え上がって出ます。最初の画面は店名の入力1つとストーリー1つだけで、6枚の見出し・数字・単位・ひとことは畳んだ欄で変えられます。入れた内容はURLの#に入るので、同じURLで同じまとめが開けます。今の1枚は1080×1920のPNGで保存でき、画面と画像は同じ部品表から描くので見たままの1枚になります。入れた内容入りのReact(TSX)のコードもコピーできます。prefers-reduced-motionでは自動送り・数え上がり・フェードを止めます。新しい依存はありません。

追加日:
2026-11-16
更新日:
2026-11-17
依存:
なし
tags
#block #stories #story-viewer #year-in-review #tap-to-advance #progress-bar #long-press #count-up #9-16 #share-image #canvas #url-hash #code-export #small-business #keyboard #a11y #reduced-motion #hairline #no-dependency
"use client";

import {
  useCallback,
  useEffect,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent,
  type PointerEvent,
} from "react";

/**
 * お店の「今年のまとめ」ストーリー(タップでめくる9:16の6枚・1080×1920で保存)(BLK-117)
 *
 * 差別化: 近い既存(three-object-gallery-hero・hero-kenburns-slideshow・coachmark-product-tour)は、眺める・案内される側の部品。
 * 本ブロックは店主が自分の数字を入れて「縦長の6枚を作って持ち帰る」制作道具で、画面の1枚と保存する画像が同じ部品表から描かれる。
 * 英字の小見出し・見出しの「。」止め・末尾の矢印リンク・角丸・スクロール連動の出現アニメは置かず、hairline 罫線と余白で組んでいる。
 *
 * 汎用技法メモ:
 * 1. **画面と画像を同じ「部品表」から描く**。1枚を 1080×1920 の座標の文字・四角の一覧(ops)にし、画面は cqi で縮めた
 *    絶対配置の span、保存は canvas の fillText で描く。改行と文字の大きさは canvas の measureText で決めて両方に渡すので、
 *    画面で見たままの1枚が画像になる。文字の縦位置は CSS の行の箱と同じ式((行の高さ − (ascent + descent)) / 2 + ascent)で合わせる。
 * 2. **進む線は rAF で transform: scaleX だけを書き換える**。経過時間は ref に持ち、長押し・自動送りの停止・画面外・タブを隠したときは
 *    rAF を止めるだけで、その位置から続きが進む。タップは押してから離すまでが 220ms 未満のときだけ「めくる」と数える。
 * 3. **入れた内容は URL の # に入れる**(JSON → UTF-8 → base64url)。サーバーに何も送らず、同じ URL で同じまとめが開ける。
 * 4. prefers-reduced-motion: reduce では自動送り・数え上がり・めくるときのフェードを止め、操作した分だけ切り替える。
 */

// --- 色と寸法 ----------------------------------------------------------------------------

const AMBER = "#d97706";
const AMBER_DEEP = "#b45309";
const INK = "#1c1917";
const SUB = "#44403c";
const MUTED = "#57534e";
const RULE = "#e7e5e4";
const FAINT = "#a8a29e";

/** 画像の大きさ。画面の1枚も同じ座標で組み、cqi で縮めて見せる */
export const W = 1080;
export const H = 1920;
/** 1枚を見せる時間 */
export const SLIDE_MS = 5000;
/** これより長く押したら「止める」、短ければ「めくる」 */
export const HOLD_MS = 220;
/** 左からこの割合までをタップすると戻る */
export const BACK_ZONE = 0.3;
const COUNT_MS = 900;
const PAD = 96;
const TEXT_W = W - PAD * 2;

// --- データ -------------------------------------------------------------------------------

export type Slide = { title: string; value: string; unit: string; note: string };
export type Recap = { shop: string; slides: Slide[]; credit: boolean };

export const MAX = { shop: 16, title: 20, value: 14, unit: 6, note: 32 } as const;
export const SLIDE_COUNT = 6;

export const DEFAULT_RECAP: Recap = {
  shop: "パン屋 むぎあかり",
  credit: true,
  slides: [
    { title: "2026年のまとめ", value: "", unit: "", note: "1年分の数字を、6枚で振り返ります" },
    { title: "焼いたパン", value: "38400", unit: "個", note: "毎朝5時から、窯の前で" },
    { title: "いちばん人気", value: "塩バターロール", unit: "", note: "3人に1人が買っていった定番" },
    { title: "新しく出した商品", value: "12", unit: "品", note: "いちばんの新顔は 柚子あんぱん" },
    { title: "いちばん忙しかった日", value: "12/24", unit: "", note: "シュトーレンが午前中に完売" },
    { title: "来年もよろしくお願いします", value: "", unit: "", note: "新年は 1/5(火)から焼きます" },
  ],
};

/** 「38,400」「38400」などを数に。数でなければ null */
export function toNum(v: string): number | null {
  const t = v.trim().replace(/[,,]/g, "");
  if (!/^\d{1,9}$/.test(t)) return null;
  return Number(t);
}

export const fmt = (n: number) => n.toLocaleString("ja-JP");

export type Kind = "cover" | "number" | "word" | "closing";

export function kindOf(i: number, s: Slide): Kind {
  if (i === 0) return "cover";
  if (i === SLIDE_COUNT - 1) return "closing";
  return toNum(s.value) !== null ? "number" : "word";
}

// --- URL の # ------------------------------------------------------------------------------

export const HASH_KEY = "recap=";

const clean = (v: unknown, max: number) =>
  typeof v === "string" ? Array.from(v.replace(/[\u0000-\u001f\u007f]/g, " ")).slice(0, max).join("") : "";

export function encodeRecap(r: Recap): string {
  const json = JSON.stringify({ v: 1, s: r.shop, c: r.credit ? 1 : 0, d: r.slides.map((x) => [x.title, x.value, x.unit, x.note]) });
  const bytes = new TextEncoder().encode(json);
  let bin = "";
  for (const b of bytes) bin += String.fromCharCode(b);
  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

/** 壊れた値・別の版・枚数違いは null(既定の見本のまま開く) */
export function decodeRecap(hash: string): Recap | null {
  const at = hash.indexOf(HASH_KEY);
  if (at < 0) return null;
  try {
    const b64 = hash.slice(at + HASH_KEY.length).split("&")[0].replace(/-/g, "+").replace(/_/g, "/");
    const bin = atob(b64);
    const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
    const o = JSON.parse(new TextDecoder().decode(bytes));
    if (!o || o.v !== 1 || !Array.isArray(o.d) || o.d.length !== SLIDE_COUNT) return null;
    const slides = o.d.map((row: unknown) => {
      const a = Array.isArray(row) ? row : [];
      return { title: clean(a[0], MAX.title), value: clean(a[1], MAX.value), unit: clean(a[2], MAX.unit), note: clean(a[3], MAX.note) };
    });
    return { shop: clean(o.s, MAX.shop), credit: o.c !== 0, slides };
  } catch {
    return null;
  }
}

// --- 部品表(画面と画像で共有) ----------------------------------------------------------

export type Face = "display" | "sans";
export type TextOp = {
  t: "text";
  x: number;
  y: number;
  size: number;
  weight: number;
  face: Face;
  color: string;
  text: string;
  align?: "left" | "right" | "center";
  /** 画面で数え上がる数(終わりの値)。text はその表示 */
  count?: number;
  /** 本文(めくるときに入れ替わる側)か、枠(店名・罫線) */
  body?: boolean;
};
export type RectOp = { t: "rect"; x: number; y: number; w: number; h: number; color: string; body?: boolean };
export type Op = TextOp | RectOp;

/** 文字の幅を測る道具。画面では canvas、試験では文字数×大きさの近似を渡す */
export type Measure = (text: string, size: number, weight: number, face: Face) => number;

/** 日本語の行頭に来てはいけない文字 */
const NO_START = "、。,.,.・:;:;!?!?」』))】ーぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ々〜…";

/** 語の切れ目(Intl.Segmenter が無い環境は1文字ずつ) */
function segments(text: string): string[] {
  const Seg = (Intl as unknown as { Segmenter?: new (l: string, o: { granularity: "word" }) => { segment(t: string): Iterable<{ segment: string }> } }).Segmenter;
  if (!Seg) return Array.from(text);
  return Array.from(new Seg("ja", { granularity: "word" }).segment(text), (x) => x.segment);
}

/** 幅に収まるよう語の切れ目で折り返す。1語が入らないときだけ1文字ずつ(どちらも行頭禁則つき) */
export function wrap(text: string, size: number, weight: number, face: Face, maxW: number, m: Measure): string[] {
  const lines: string[] = [];
  let cur = "";
  const fits = (t: string) => m(t, size, weight, face) <= maxW;
  const pushChar = (ch: string) => {
    if (!cur || fits(cur + ch)) {
      cur += ch;
      return;
    }
    if (NO_START.includes(ch) && Array.from(cur).length > 1) {
      // 禁則: 前の行の最後の1文字を連れて行く
      const chars = Array.from(cur);
      const last = chars.pop() as string;
      lines.push(chars.join(""));
      cur = last + ch;
    } else {
      lines.push(cur);
      cur = ch;
    }
  };
  for (const seg of segments(text)) {
    if (fits(cur + seg)) cur += seg;
    else if (cur && fits(seg) && !NO_START.includes(Array.from(seg)[0])) {
      lines.push(cur);
      cur = seg;
    } else for (const ch of Array.from(seg)) pushChar(ch);
  }
  if (cur) lines.push(cur);
  return lines.length ? lines : [""];
}

/** 1行に収まる大きさ(max から縮め、min より小さくしない) */
export function fit(text: string, max: number, min: number, weight: number, face: Face, maxW: number, m: Measure) {
  const w = m(text, max, weight, face);
  if (w <= maxW) return max;
  return Math.max(min, Math.floor((max * maxW) / w));
}

/** 折り返して maxLines 行以内に収まる大きさ */
function fitLines(text: string, max: number, min: number, weight: number, face: Face, maxLines: number, m: Measure) {
  for (let size = max; size >= min; size -= 4) {
    const lines = wrap(text, size, weight, face, TEXT_W, m);
    if (lines.length <= maxLines) return { size, lines };
  }
  return { size: min, lines: wrap(text, min, weight, face, TEXT_W, m) };
}

const isLatin = (s: string) => /^[\x20-\x7e]+$/.test(s);
const pad2 = (n: number) => String(n).padStart(2, "0");

/** i 枚目の部品表(1080×1920 の座標) */
export function composeSlide(r: Recap, i: number, m: Measure): Op[] {
  const s = r.slides[i];
  const kind = kindOf(i, s);
  const ops: Op[] = [];
  const shop = r.shop.trim() || "お店の名前";

  // 枠: 店名・枚数・罫線・下の帯
  ops.push({ t: "rect", x: 40, y: 84, w: 72, h: 72, color: INK });
  ops.push({ t: "text", x: 76, y: 102, size: 36, weight: 700, face: "sans", color: "#ffffff", text: Array.from(shop)[0], align: "center" });
  ops.push({ t: "text", x: 136, y: 103, size: 34, weight: 700, face: "sans", color: INK, text: wrap(shop, 34, 700, "sans", 640, m)[0] });
  ops.push({ t: "text", x: 1040, y: 105, size: 30, weight: 600, face: "display", color: MUTED, text: `${i + 1} / ${SLIDE_COUNT}`, align: "right" });
  ops.push({ t: "rect", x: 40, y: 196, w: 1000, h: 2, color: RULE });
  ops.push({ t: "rect", x: 40, y: 1756, w: 1000, h: 2, color: RULE });
  const cover = r.slides[0].title.trim() || "今年のまとめ";
  ops.push({ t: "text", x: 40, y: 1790, size: 30, weight: 500, face: "sans", color: MUTED, text: wrap(cover, 30, 500, "sans", 760, m)[0] });
  ops.push({ t: "text", x: 1040, y: 1790, size: 30, weight: 700, face: "display", color: AMBER_DEEP, text: pad2(i + 1), align: "right" });
  if (r.credit) ops.push({ t: "text", x: 40, y: 1858, size: 22, weight: 500, face: "display", color: FAINT, text: "designs.first-ch.com" });

  // 本文: 上から積んで、縦の中央(200〜1750)にそろえる
  const col: { h: number; draw: (y: number) => Op[] }[] = [];
  const gap = (h: number) => col.push({ h, draw: () => [] });
  const bar = () => col.push({ h: 8, draw: (y) => [{ t: "rect", x: PAD, y, w: 120, h: 8, color: AMBER, body: true }] });
  const lines = (ls: string[], size: number, weight: number, face: Face, color: string, lead = 1.3) =>
    col.push({
      h: size + (ls.length - 1) * size * lead,
      draw: (y) => ls.map((text, k) => ({ t: "text", x: PAD, y: y + k * size * lead, size, weight, face, color, text, body: true }) as TextOp),
    });

  // 大きな通し番号(あしらい・右下へはみ出す)
  ops.push({ t: "text", x: 1110, y: 1250, size: 560, weight: 700, face: "display", color: "rgba(217,119,6,0.07)", text: pad2(i + 1), align: "right", body: true });

  if (kind === "cover") {
    const m4 = s.title.trim().match(/^(\d{2,4})([\s\S]*)$/);
    bar();
    gap(64);
    if (m4) {
      const ys = fit(m4[1], 400, 160, 700, "display", TEXT_W, m);
      lines([m4[1]], ys, 700, "display", AMBER);
      gap(24);
      const rest = fitLines(m4[2].trim() || " ", 128, 72, 700, "sans", 2, m);
      lines(rest.lines, rest.size, 700, "sans", INK, 1.25);
    } else {
      const t = fitLines(s.title.trim() || "今年のまとめ", 140, 72, 700, "sans", 3, m);
      lines(t.lines, t.size, 700, "sans", INK, 1.25);
    }
    gap(72);
    lines(wrap(shop, 48, 700, "sans", TEXT_W, m).slice(0, 2), 48, 700, "sans", SUB, 1.35);
    if (s.note.trim()) {
      gap(28);
      lines(wrap(s.note.trim(), 40, 500, "sans", TEXT_W, m), 40, 500, "sans", MUTED, 1.6);
    }
  } else if (kind === "closing") {
    bar();
    gap(64);
    const t = fitLines(s.title.trim() || "来年もよろしくお願いします", 132, 80, 700, "sans", 4, m);
    lines(t.lines, t.size, 700, "sans", INK, 1.3);
    const v = (s.value + s.unit).trim();
    if (v) {
      gap(48);
      const face: Face = isLatin(v) ? "display" : "sans";
      lines([v], fit(v, 72, 40, 700, face, TEXT_W, m), 700, face, AMBER_DEEP);
    }
    if (s.note.trim()) {
      gap(48);
      lines(wrap(s.note.trim(), 44, 500, "sans", TEXT_W, m), 44, 500, "sans", MUTED, 1.6);
    }
    gap(96);
    lines(wrap(shop, 52, 700, "sans", TEXT_W, m).slice(0, 2), 52, 700, "sans", INK, 1.35);
  } else {
    bar();
    gap(56);
    lines(wrap(s.title.trim() || "見出し", 64, 700, "sans", TEXT_W, m).slice(0, 2), 64, 700, "sans", SUB, 1.35);
    gap(48);
    if (kind === "number") {
      const n = toNum(s.value) as number;
      const unit = s.unit.trim();
      const uw = unit ? m(unit, 104, 700, "sans") + 20 : 0;
      const text = fmt(n);
      const size = fit(text, 300, 120, 700, "display", TEXT_W - uw, m);
      const tw = m(text, size, 700, "display");
      col.push({
        h: size,
        draw: (y) => {
          const out: Op[] = [{ t: "text", x: PAD + tw, y, size, weight: 700, face: "display", color: INK, text, align: "right", count: n, body: true }];
          if (unit) out.push({ t: "text", x: PAD + tw + 20, y: y + size - 104 * 1.02, size: 104, weight: 700, face: "sans", color: AMBER_DEEP, text: unit, body: true });
          return out;
        },
      });
    } else {
      const v = (s.value + s.unit).trim() || "ことば";
      if (isLatin(v)) lines([v], fit(v, 300, 120, 700, "display", TEXT_W, m), 700, "display", INK);
      else {
        const t = fitLines(v, 156, 88, 700, "sans", 2, m);
        lines(t.lines, t.size, 700, "sans", INK, 1.22);
      }
    }
    if (s.note.trim()) {
      gap(64);
      lines(wrap(s.note.trim(), 44, 500, "sans", TEXT_W, m), 44, 500, "sans", MUTED, 1.6);
    }
  }

  const total = col.reduce((a, c) => a + c.h, 0);
  let y = Math.round(200 + (1556 - total) / 2 - 40);
  for (const c of col) {
    ops.push(...c.draw(y));
    y += c.h;
  }
  return ops;
}

// --- 画像(canvas) -----------------------------------------------------------------------

type Fonts = { display: string; sans: string };
const fontOf = (size: number, weight: number, face: Face, f: Fonts) => `${weight} ${size}px ${f[face]}`;

/** 文字の縦位置: CSS で line-height = size の行の箱の top に置いたときと同じ基線 */
function baselineOf(ctx: CanvasRenderingContext2D, text: string, size: number) {
  const mt = ctx.measureText(text || "あ");
  const asc = mt.fontBoundingBoxAscent ?? size * 0.88;
  const desc = mt.fontBoundingBoxDescent ?? size * 0.24;
  return (size - (asc + desc)) / 2 + asc;
}

export function drawSlide(ctx: CanvasRenderingContext2D, r: Recap, i: number, ops: Op[], f: Fonts) {
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(0, 0, W, H);
  // 進む線(今の1枚までを埋める)
  const gapX = 10;
  const bw = (1000 - gapX * (SLIDE_COUNT - 1)) / SLIDE_COUNT;
  for (let k = 0; k < SLIDE_COUNT; k++) {
    ctx.fillStyle = k <= i ? AMBER : RULE;
    ctx.fillRect(40 + k * (bw + gapX), 40, bw, 6);
  }
  for (const op of ops) {
    if (op.t === "rect") {
      ctx.fillStyle = op.color;
      ctx.fillRect(op.x, op.y, op.w, op.h);
      continue;
    }
    ctx.font = fontOf(op.size, op.weight, op.face, f);
    ctx.fillStyle = op.color;
    ctx.textAlign = op.align ?? "left";
    ctx.textBaseline = "alphabetic";
    ctx.fillText(op.text, op.x, op.y + baselineOf(ctx, op.text, op.size));
  }
}

// --- 書き出すコード -----------------------------------------------------------------------

const PLAYER = String.raw`"use client";

import { useEffect, useRef, useState } from "react";

// 今年のまとめストーリー(タップでめくる9:16・依存なし・React + Tailwind CSS v4)
// 右側のタップと→キーで次へ、左側と←キーで戻る。長押しの間は止まる。5秒で自動で進む。
const SHOP = __SHOP__;
const SLIDES: { title: string; value: string; unit: string; note: string }[] = __SLIDES__;
const SLIDE_MS = 5000;
const HOLD_MS = 220;

const toNum = (v: string) => {
  const t = v.trim().replace(/[,,]/g, "");
  return /^\d{1,9}$/.test(t) ? Number(t) : null;
};

export default function YearRecapStory() {
  const [i, setI] = useState(0);
  const [auto, setAuto] = useState(true);
  const [held, setHeld] = useState(false);
  const [shown, setShown] = useState<number | null>(null);
  const fill = useRef<HTMLDivElement>(null);
  const elapsed = useRef(0);
  const press = useRef<{ timer: number; long: boolean } | null>(null);
  const reduced = useRef(false);

  const go = (n: number) => {
    elapsed.current = 0;
    setI((n + SLIDES.length) % SLIDES.length);
  };
  // 最後の1枚で止まっていたら最初から再開する
  const toggle = () => {
    elapsed.current = 0;
    if (!auto && i === SLIDES.length - 1) go(0);
    setAuto((a) => !a);
  };

  useEffect(() => {
    reduced.current = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduced.current) setAuto(false);
  }, []);

  // 自動送り。止めている間と長押しの間は rAF を止め、経過時間はそのまま残す
  useEffect(() => {
    if (!auto || held) return;
    let last = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      elapsed.current += now - last;
      last = now;
      const p = Math.min(1, elapsed.current / SLIDE_MS);
      if (fill.current) fill.current.style.transform = "scaleX(" + p + ")";
      if (p < 1) raf = requestAnimationFrame(tick);
      else if (i < SLIDES.length - 1) go(i + 1);
      else setAuto(false);
    });
    return () => cancelAnimationFrame(raf);
  }, [i, auto, held]);

  // 数え上がり(動きを減らす設定では最初から終わりの値)
  useEffect(() => {
    const n = toNum(SLIDES[i].value);
    setShown(null);
    if (n === null || reduced.current) return;
    const t0 = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      const k = Math.min(1, (now - t0) / 900);
      setShown(Math.round(n * (1 - (1 - k) ** 3)));
      if (k < 1) raf = requestAnimationFrame(tick);
    });
    return () => cancelAnimationFrame(raf);
  }, [i]);

  const s = SLIDES[i];
  const n = toNum(s.value);
  const first = i === 0;
  const lastOne = i === SLIDES.length - 1;
  const m = first ? s.title.match(/^(\d{2,4})(.*)$/) : null;

  return (
    <div className="mx-auto w-full max-w-[360px]">
      <div
        role="group"
        aria-roledescription="ストーリー"
        aria-label={"今年のまとめ " + (i + 1) + " / " + SLIDES.length + "枚目(→で次・←で戻る・スペースで止める)"}
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === "ArrowRight") go(i + 1);
          else if (e.key === "ArrowLeft") go(i - 1);
          else if (e.key === " ") toggle();
          else return;
          e.preventDefault();
        }}
        onPointerDown={(e) => {
          e.currentTarget.setPointerCapture(e.pointerId);
          const p = { timer: 0, long: false };
          p.timer = window.setTimeout(() => {
            p.long = true;
            setHeld(true);
          }, HOLD_MS);
          press.current = p;
        }}
        onPointerUp={(e) => {
          const p = press.current;
          press.current = null;
          if (!p) return;
          clearTimeout(p.timer);
          if (p.long) return setHeld(false);
          const r = e.currentTarget.getBoundingClientRect();
          go((e.clientX - r.left) / r.width < 0.3 ? i - 1 : i + 1);
        }}
        onPointerCancel={() => {
          if (press.current) clearTimeout(press.current.timer);
          press.current = null;
          setHeld(false);
        }}
        onContextMenu={(e) => e.preventDefault()}
        className="relative aspect-[9/16] w-full cursor-pointer touch-manipulation overflow-hidden border border-stone-200 bg-white text-stone-900 outline-none select-none [-webkit-touch-callout:none] [container-type:inline-size] focus-visible:ring-2 focus-visible:ring-[#d97706] focus-visible:ring-offset-2"
      >
        <div className="absolute inset-x-[3.7cqi] top-[3.7cqi] flex gap-[0.9cqi]">
          {SLIDES.map((_, k) => (
            <div key={k} className="h-[0.6cqi] min-h-[2px] flex-1 overflow-hidden bg-stone-200">
              <div
                ref={k === i ? fill : undefined}
                className="h-full origin-left bg-[#d97706]"
                style={{ transform: "scaleX(" + (k < i || (k === i && !auto) ? 1 : 0) + ")" }}
              />
            </div>
          ))}
        </div>
        <div className="absolute inset-x-[3.7cqi] top-[7.8cqi] flex items-center gap-[2.2cqi] border-b border-stone-200 pb-[3.5cqi]">
          <span aria-hidden="true" className="grid size-[6.7cqi] place-items-center bg-stone-900 text-[3.3cqi] font-bold text-white">{SHOP.slice(0, 1)}</span>
          <span className="truncate text-[3.2cqi] font-bold">{SHOP}</span>
          <span className="ml-auto font-[Montserrat,sans-serif] text-[2.8cqi] font-semibold text-stone-600">{held ? "止めています" : i + 1 + " / " + SLIDES.length}</span>
        </div>
        <div key={i} className="absolute inset-x-[8.9cqi] top-1/2 -translate-y-1/2 motion-safe:animate-[recap-in_.24s_ease-out]">
          <div className="h-[0.75cqi] w-[11cqi] bg-[#d97706]" />
          {first ? (
            <p className="mt-[6cqi] text-[11.8cqi] leading-[1.25] font-bold">
              {m ? <span className="block font-[Montserrat,sans-serif] text-[34cqi] leading-none text-[#d97706]">{m[1]}</span> : null}
              {m ? m[2] : s.title}
            </p>
          ) : (
            <p className={lastOne ? "mt-[6cqi] text-[11.5cqi] leading-[1.3] font-bold" : "mt-[5cqi] text-[5.9cqi] leading-[1.35] font-bold text-stone-700"}>{s.title}</p>
          )}
          {!first && !lastOne && (
            <p className="mt-[4.4cqi] flex items-end gap-[1.8cqi] leading-none font-bold">
              <span className={n === null ? "text-[13cqi] leading-[1.22]" : "font-[Montserrat,sans-serif] text-[24cqi]"}>
                {n === null ? s.value : (shown ?? n).toLocaleString("ja-JP")}
              </span>
              {s.unit && <span className="pb-[2cqi] text-[9.6cqi] text-[#b45309]">{s.unit}</span>}
            </p>
          )}
          {s.note && <p className="mt-[5.9cqi] text-[4.1cqi] leading-[1.6] text-stone-600">{s.note}</p>}
          {(first || lastOne) && <p className="mt-[8cqi] text-[4.6cqi] font-bold text-stone-700">{SHOP}</p>}
        </div>
      </div>
      <div className="mt-3 flex gap-2">
        <button type="button" onClick={() => go(i - 1)} className="min-h-11 flex-1 border border-stone-300 bg-white text-[14px] font-bold focus-visible:outline-2 focus-visible:outline-[#d97706]">前の1枚</button>
        <button type="button" onClick={toggle} className="min-h-11 flex-1 border border-stone-300 bg-white text-[14px] font-bold focus-visible:outline-2 focus-visible:outline-[#d97706]">{auto ? "止める" : "再開する"}</button>
        <button type="button" onClick={() => go(i + 1)} className="min-h-11 flex-1 border border-stone-900 bg-stone-900 text-[14px] font-bold text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]">次の1枚</button>
      </div>
      <style>{"@keyframes recap-in{from{opacity:0;transform:translateY(12px)}}"}</style>
    </div>
  );
}
`;

/** 入れた内容を入れた React(TSX)の1ファイル */
export function reactCode(r: Recap): string {
  const slides = JSON.stringify(
    r.slides.map((s) => ({ title: s.title, value: s.value, unit: s.unit, note: s.note })),
    null,
    2,
  );
  const shop = JSON.stringify(r.shop.trim() || "お店の名前");
  // 1回の走査で両方を置き換える(先に入れた店名の中を、あとの置換が書き換えないように)
  return PLAYER.replace(/__SHOP__|__SLIDES__/g, (k) => (k === "__SHOP__" ? shop : slides));
}

// --- 画面 ---------------------------------------------------------------------------------

const u = (n: number) => `${(n / 10.8).toFixed(4)}cqi`;
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-[#d97706] focus-visible:ring-offset-2";
const btn = "inline-flex min-h-11 items-center justify-center gap-2 border px-4 text-[14px] font-bold transition-colors duration-150 motion-reduce:transition-none";

const RELATED = [
  { href: "/d/fukubukuro-scratch-reveal", title: "福袋のスクラッチ", note: "こすると中身5品と価格が出る" },
  { href: "/d/business-day-calendar", title: "年末年始の営業日カレンダー", note: "休みを塗って、お知らせ文まで作る" },
  { href: "/d/omikuji-shake-card", title: "縦書きおみくじ", note: "筒を振って引き、紙を画像で保存" },
];

const FIELD_LABEL = ["表紙", "2枚目", "3枚目", "4枚目", "5枚目", "結び"];

/** 計測用の canvas(画面と保存で共有)。書体が届いたら tick を進めて測り直す */
function useMeasure(fonts: Fonts | null, tick: number) {
  return useMemo<Measure>(() => {
    void tick;
    if (!fonts || typeof document === "undefined") return (t, size) => Array.from(t).length * size * 0.9;
    const ctx = document.createElement("canvas").getContext("2d");
    if (!ctx) return (t, size) => Array.from(t).length * size * 0.9;
    const cache = new Map<string, number>();
    return (text, size, weight, face) => {
      const k = `${weight}|${face}|${size}|${text}`;
      let w = cache.get(k);
      if (w === undefined) {
        ctx.font = fontOf(size, weight, face, fonts);
        w = ctx.measureText(text).width;
        cache.set(k, w);
      }
      return w;
    };
  }, [fonts, tick]);
}

export type YearRecapStoriesProps = { headingTag?: "h1" | "h2" | "p" };

export default function YearRecapStories({ headingTag = "h2" }: YearRecapStoriesProps) {
  const Heading = headingTag;
  const uid = useId();
  const [recap, setRecap] = useState<Recap>(DEFAULT_RECAP);
  const [idx, setIdx] = useState(0);
  /** めくった回数(数え上がりとフェードを1枚ごとにやり直す鍵) */
  const [turn, setTurn] = useState(0);
  const [auto, setAuto] = useState(true);
  const [held, setHeld] = useState(false);
  const [inView, setInView] = useState(true);
  const [reduced, setReduced] = useState(false);
  const [fonts, setFonts] = useState<Fonts | null>(null);
  const [fontTick, setFontTick] = useState(0);
  const [countK, setCountK] = useState(1);
  const [saved, setSaved] = useState<{ url: string; name: string; n: number } | null>(null);
  const [busy, setBusy] = useState(false);
  const [copied, setCopied] = useState<"" | "url" | "code">("");
  const [edited, setEdited] = useState(false);

  const frameRef = useRef<HTMLDivElement>(null);
  const fillRef = useRef<HTMLDivElement>(null);
  const displayRef = useRef<HTMLSpanElement>(null);
  const sansRef = useRef<HTMLSpanElement>(null);
  const elapsed = useRef(0);
  const press = useRef<{ timer: number; long: boolean } | null>(null);
  const idxRef = useRef(0);

  const measure = useMeasure(fonts, fontTick);

  const ops = useMemo(() => (fonts ? composeSlide(recap, idx, measure) : []), [fonts, recap, idx, measure]);

  const go = useCallback((n: number) => {
    const next = ((n % SLIDE_COUNT) + SLIDE_COUNT) % SLIDE_COUNT;
    elapsed.current = 0;
    idxRef.current = next;
    setIdx(next);
    setTurn((t) => t + 1);
  }, []);

  // 最初に1回: 動きを減らす設定・書体・URL の # を読む
  useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const apply = () => {
      setReduced(mq.matches);
      if (mq.matches) setAuto(false);
    };
    apply();
    mq.addEventListener("change", apply);
    const fromHash = decodeRecap(window.location.hash);
    if (fromHash) setRecap(fromHash);
    const f = {
      display: displayRef.current ? getComputedStyle(displayRef.current).fontFamily : "sans-serif",
      sans: sansRef.current ? getComputedStyle(sansRef.current).fontFamily : "sans-serif",
    };
    setFonts(f);
    let alive = true;
    const text = JSON.stringify(fromHash ?? DEFAULT_RECAP) + "0123456789/ お店の名前今年のまとめ見出しことば来年もよろしくお願いします";
    Promise.all([
      document.fonts?.load(`700 100px ${f.display}`, text),
      document.fonts?.load(`600 100px ${f.display}`, text),
      document.fonts?.load(`700 100px ${f.sans}`, text),
      document.fonts?.load(`500 100px ${f.sans}`, text),
    ])
      .catch(() => undefined)
      .then(() => alive && setFontTick((t) => t + 1));
    return () => {
      alive = false;
      mq.removeEventListener("change", apply);
    };
  }, []);

  // 画面の外・タブを隠したときは止める
  useEffect(() => {
    const el = frameRef.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting && document.visibilityState === "visible"), { threshold: 0.3 });
    io.observe(el);
    const vis = () => {
      const r = el.getBoundingClientRect();
      setInView(document.visibilityState === "visible" && r.bottom > 0 && r.top < window.innerHeight);
    };
    document.addEventListener("visibilitychange", vis);
    return () => {
      io.disconnect();
      document.removeEventListener("visibilitychange", vis);
    };
  }, []);

  // 自動送り: 経過時間を ref に足し、今の線の scaleX だけを書く
  useEffect(() => {
    if (!auto || held || !inView) return;
    let last = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      elapsed.current += now - last;
      last = now;
      const p = Math.min(1, elapsed.current / SLIDE_MS);
      if (fillRef.current) fillRef.current.style.transform = `scaleX(${p})`;
      if (p < 1) raf = requestAnimationFrame(tick);
      else if (idxRef.current < SLIDE_COUNT - 1) go(idxRef.current + 1);
      else setAuto(false);
    });
    return () => cancelAnimationFrame(raf);
  }, [auto, held, inView, idx, go]);

  // 数え上がり(めくったときだけ。入力中の書き換えでは数え直さない)
  // 描画前に0へ戻す(useEffect だと最終値が1フレーム見えてから0に落ちる)
  useLayoutEffect(() => {
    if (reduced || toNum(recap.slides[idxRef.current]?.value ?? "") === null) return;
    setCountK(0);
    const t0 = performance.now();
    let raf = requestAnimationFrame(function tick(now) {
      const k = Math.min(1, (now - t0) / COUNT_MS);
      setCountK(1 - (1 - k) ** 3);
      if (k < 1) raf = requestAnimationFrame(tick);
    });
    return () => {
      cancelAnimationFrame(raf);
      setCountK(1);
    };
    // recap は入れずに、めくったときだけ数え直す
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [turn, reduced]);

  // 編集したら URL の # を書き換える(同じ URL で同じまとめが開ける)
  useEffect(() => {
    if (!edited) return;
    const t = window.setTimeout(() => {
      history.replaceState(null, "", `#${HASH_KEY}${encodeRecap(recap)}`);
    }, 250);
    return () => clearTimeout(t);
  }, [recap, edited]);

  useEffect(() => () => {
    if (saved) URL.revokeObjectURL(saved.url);
  }, [saved]);

  const toggleAuto = () => {
    elapsed.current = 0;
    if (!auto && idx === SLIDE_COUNT - 1) go(0);
    setAuto((a) => !a);
  };

  const edit = (i: number, patch: Partial<Slide>) => {
    setEdited(true);
    setRecap((r) => ({ ...r, slides: r.slides.map((s, k) => (k === i ? { ...s, ...patch } : s)) }));
    if (i !== idxRef.current) go(i);
    setAuto(false);
  };
  const setShop = (shop: string) => {
    setEdited(true);
    setRecap((r) => ({ ...r, shop }));
  };

  // --- タップ・長押し・キー ---
  const onDown = (e: PointerEvent<HTMLDivElement>) => {
    if (e.pointerType === "mouse" && e.button !== 0) return;
    e.currentTarget.setPointerCapture(e.pointerId);
    const p = { timer: 0, long: false };
    p.timer = window.setTimeout(() => {
      p.long = true;
      setHeld(true);
    }, HOLD_MS);
    press.current = p;
  };
  const onUp = (e: PointerEvent<HTMLDivElement>) => {
    const p = press.current;
    press.current = null;
    if (!p) return;
    clearTimeout(p.timer);
    if (p.long) {
      setHeld(false);
      return;
    }
    const r = e.currentTarget.getBoundingClientRect();
    go((e.clientX - r.left) / r.width < BACK_ZONE ? idxRef.current - 1 : idxRef.current + 1);
  };
  const onCancel = () => {
    if (press.current) clearTimeout(press.current.timer);
    press.current = null;
    setHeld(false);
  };
  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key === "ArrowRight") go(idx + 1);
    else if (e.key === "ArrowLeft") go(idx - 1);
    else if (e.key === "Home") go(0);
    else if (e.key === "End") go(SLIDE_COUNT - 1);
    else if (e.key === " " || e.key === "k") toggleAuto();
    else return;
    e.preventDefault();
  };

  // --- 保存・共有 ---
  const saveImage = async () => {
    if (!fonts) return;
    setBusy(true);
    try {
      const cv = document.createElement("canvas");
      cv.width = W;
      cv.height = H;
      const ctx = cv.getContext("2d");
      if (!ctx) return;
      drawSlide(ctx, recap, idx, composeSlide(recap, idx, measure), fonts);
      const blob = await new Promise<Blob | null>((res) => cv.toBlob(res, "image/png"));
      if (!blob) return;
      const name = `recap-${pad2(idx + 1)}.png`;
      const url = URL.createObjectURL(blob);
      setSaved({ url, name, n: idx + 1 });
      const a = document.createElement("a");
      a.href = url;
      a.download = name;
      a.click();
    } finally {
      setBusy(false);
    }
  };

  const copy = async (what: "url" | "code") => {
    const text =
      what === "url"
        ? `${location.origin}${location.pathname}#${HASH_KEY}${encodeRecap(recap)}`
        : reactCode(recap);
    if (what === "url") history.replaceState(null, "", `#${HASH_KEY}${encodeRecap(recap)}`);
    try {
      await navigator.clipboard.writeText(text);
      setCopied(what);
      window.setTimeout(() => setCopied(""), 1600);
    } catch {
      setCopied("");
    }
  };

  const s = recap.slides[idx];
  const playing = auto && !held;
  const status = held ? "長押しの間は止まっています" : auto ? "5秒ごとに自動で進みます" : "自動送りは止めています";

  const bodyOps = ops.filter((o) => o.body);
  const frameOps = ops.filter((o) => !o.body);
  const renderOp = (o: Op, k: number) => {
    if (o.t === "rect") {
      return <span key={k} aria-hidden="true" className="absolute block" style={{ left: u(o.x), top: u(o.y), width: u(o.w), height: u(o.h), background: o.color }} />;
    }
    const text = o.count !== undefined && countK < 1 ? fmt(Math.round(o.count * countK)) : o.text;
    const style: CSSProperties = {
      top: u(o.y),
      fontSize: u(o.size),
      lineHeight: u(o.size),
      fontWeight: o.weight,
      color: o.color,
    };
    if (o.align === "right") style.right = u(W - o.x);
    else if (o.align === "center") {
      style.left = u(o.x);
      style.transform = "translateX(-50%)";
    } else style.left = u(o.x);
    return (
      <span key={k} className={`absolute block whitespace-pre ${o.face === "display" ? "font-display" : "font-sans"}`} style={style}>
        {text}
      </span>
    );
  };

  return (
    <section className="@container w-full max-w-5xl border border-stone-200 bg-white text-stone-900">
      {/* 書体名を取るための見えない見本 */}
      <span ref={displayRef} aria-hidden="true" className="pointer-events-none absolute font-display opacity-0" />
      <span ref={sansRef} aria-hidden="true" className="pointer-events-none absolute font-sans opacity-0" />
      <style>{`@keyframes yrs-in{from{opacity:0;transform:translateY(${u(18)})}}.yrs-in{animation:yrs-in .24s ease-out both}@media (prefers-reduced-motion:reduce){.yrs-in{animation:none}}`}</style>

      <div className="grid grid-cols-[minmax(0,1fr)] gap-y-6 px-5 py-7 @[44rem]:grid-cols-[minmax(0,300px)_minmax(0,1fr)] @[44rem]:gap-x-10 @[44rem]:px-8 @[44rem]:py-9 @[60rem]:grid-cols-[minmax(0,360px)_minmax(0,1fr)] @[60rem]:gap-x-12 @[60rem]:px-10 @[60rem]:py-10">
        {/* 題と、最初に見せる入力1つ */}
        <div className="@[44rem]:col-start-2 @[44rem]:row-start-1">
          <div className="flex items-baseline justify-between gap-4 border-b border-stone-200 pb-3">
            <p className="font-display text-[11px] font-semibold tracking-wide text-stone-500">
              BLK-117 <span aria-hidden="true" className="text-stone-300">/</span> 年末のまとめ
            </p>
            <p className="font-display text-[11px] text-stone-400 tabular-nums">1080×1920</p>
          </div>
          <Heading className="mt-5 text-[clamp(1.5rem,5.2cqi,2.2rem)] leading-[1.4] font-bold tracking-tight">
            お店の1年を、
            <br />
            6枚のストーリーに
          </Heading>
          <p className="mt-3 text-[15px] leading-[1.8] text-stone-600">
            右をタップで次へ、左で戻る、長押しで止まります。見本はパン屋の1年です。
          </p>
          <label htmlFor={`${uid}-shop`} className="mt-5 block text-[13px] font-bold text-stone-700">
            お店の名前
          </label>
          <input
            id={`${uid}-shop`}
            value={recap.shop}
            maxLength={MAX.shop}
            onChange={(e) => setShop(e.target.value)}
            className={`shop-name mt-1.5 min-h-12 w-full border border-stone-300 bg-white px-3 text-[16px] ${focusRing}`}
            autoComplete="organization"
          />
        </div>

        {/* ストーリー本体 */}
        <div className="@[44rem]:col-start-1 @[44rem]:row-span-3 @[44rem]:row-start-1">
          <div className="mx-auto w-full max-w-[400px] @[44rem]:max-w-none">
            <div
              ref={frameRef}
              role="group"
              aria-roledescription="ストーリー"
              aria-label={`今年のまとめ ${idx + 1} / ${SLIDE_COUNT}枚目。→キーで次、←キーで戻る、スペースで自動送りの切替`}
              tabIndex={0}
              onPointerDown={onDown}
              onPointerUp={onUp}
              onPointerCancel={onCancel}
              onLostPointerCapture={() => {
                if (press.current) onCancel();
              }}
              onContextMenu={(e) => e.preventDefault()}
              onKeyDown={onKey}
              className={`story-frame relative aspect-[9/16] w-full cursor-pointer touch-manipulation overflow-hidden border border-stone-200 bg-white select-none [-webkit-touch-callout:none] [container-type:inline-size] ${focusRing}`}
            >
              {/* 進む線 */}
              <div aria-hidden="true" className="absolute flex" style={{ left: u(40), right: u(40), top: u(40), gap: u(10) }}>
                {recap.slides.map((_, k) => (
                  <div key={k} className="min-h-[2px] flex-1 overflow-hidden bg-stone-200" style={{ height: u(6) }}>
                    <div
                      ref={k === idx ? fillRef : undefined}
                      className="h-full origin-left bg-[#d97706]"
                      style={{ transform: `scaleX(${k < idx || (k === idx && !auto) ? 1 : 0})` }}
                    />
                  </div>
                ))}
              </div>
              {frameOps.map(renderOp)}
              <div key={turn} className="yrs-in absolute inset-0">
                {bodyOps.map(renderOp)}
              </div>
              {/* 止めている印(長押し中) */}
              <span
                aria-hidden="true"
                className={`absolute right-[3.7cqi] top-[19.5cqi] flex items-center gap-[1cqi] bg-stone-900 px-[2cqi] py-[1cqi] text-[2.6cqi] font-bold text-white transition-opacity duration-150 motion-reduce:transition-none ${held ? "opacity-100" : "opacity-0"}`}
              >
                <svg viewBox="0 0 10 10" className="size-[2.2cqi]" fill="currentColor">
                  <path d="M1.5 1h2.5v8H1.5zM6 1h2.5v8H6z" />
                </svg>
                止めています
              </span>
            </div>

            <p aria-live={playing ? "off" : "polite"} className="sr-only">
              {`${idx + 1}枚目: ${s.title} ${s.value}${s.unit}`}
            </p>

            {/* 操作 */}
            <div className="mt-3 grid grid-cols-[1fr_1.25fr_1fr] gap-2">
              <button type="button" onClick={() => go(idx - 1)} className={`story-prev border-stone-300 bg-white text-stone-800 hover:border-stone-900 ${btn} ${focusRing}`}>
                前の1枚
              </button>
              <button
                type="button"
               
                onClick={toggleAuto}
                className={`story-auto border-stone-300 bg-white text-stone-800 hover:border-stone-900 ${btn} ${focusRing}`}
              >
                <svg viewBox="0 0 10 10" aria-hidden="true" className="size-2.5 text-[#b45309]" fill="currentColor">
                  {auto ? <path d="M1.5 1h2.5v8H1.5zM6 1h2.5v8H6z" /> : <path d="M2 1l7 4-7 4z" />}
                </svg>
                {auto ? "止める" : "再開する"}
              </button>
              <button type="button" onClick={() => go(idx + 1)} className={`story-next border-stone-900 bg-stone-900 text-white hover:bg-stone-700 ${btn} ${focusRing}`}>
                次の1枚
              </button>
            </div>
            <p className="mt-2 text-center text-[12px] text-stone-500">{status}</p>
          </div>
        </div>

        {/* 保存・変える・持ち帰る */}
        <div className="@[44rem]:col-start-2 @[44rem]:row-start-2">
          <button
            type="button"
            onClick={saveImage}
            disabled={busy || !fonts}
            className={`save-image w-full border-[#b45309] bg-[#b45309] text-white hover:bg-[#92400e] disabled:opacity-60 ${btn} ${focusRing}`}
          >
            <svg viewBox="0 0 16 16" aria-hidden="true" className="size-4" fill="none" stroke="currentColor" strokeWidth={1.6}>
              <path d="M8 2v8M4.5 6.5L8 10l3.5-3.5M2.5 13.5h11" />
            </svg>
            {busy ? "画像を作っています…" : `この${idx + 1}枚目を画像で保存(1080×1920)`}
          </button>
          {saved && (
            <figure className="saved-image mt-4 grid grid-cols-[96px_minmax(0,1fr)] items-center gap-4 border-y border-stone-200 py-3">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={saved.url} width={W} height={H} alt={`保存した${saved.n}枚目の画像(縦1920×横1080)`} className="h-auto w-full border border-stone-200" />
              <figcaption className="text-[13px] leading-[1.7] text-stone-600">
                ストーリーにそのまま載る 9:16 の画像です。保存されないときは、画像を長押しして保存してください。
                <a href={saved.url} download={saved.name} className={`mt-2 border-stone-900 bg-white text-stone-900 hover:bg-stone-100 ${btn} ${focusRing}`}>
                  もう一度保存
                </a>
              </figcaption>
            </figure>
          )}

          <div className="mt-5 border-t border-stone-200">
            <details className="group border-b border-stone-200">
              <summary className={`edit-open flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 py-3 text-[15px] font-bold [&::-webkit-details-marker]:hidden ${focusRing}`}>
                6枚の見出しと数字を変える
                <span aria-hidden="true" className="text-stone-500 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none">
                  ▸
                </span>
              </summary>
              <div className="pb-5">
                <p className="text-[13px] leading-[1.7] text-stone-600">
                  入れた枚がその場で表示されます。数字だけを入れると数え上がって出ます(例: 38400)。
                </p>
                <ol className="mt-3 divide-y divide-stone-200 border-y border-stone-200">
                  {recap.slides.map((sl, i) => (
                    <li key={i} className={`py-3 ${i === idx ? "bg-amber-50/60" : ""}`}>
                      <p className="flex items-baseline gap-2 text-[13px] font-bold text-stone-700">
                        <span className="font-display text-[#b45309] tabular-nums">{pad2(i + 1)}</span>
                        {FIELD_LABEL[i]}
                      </p>
                      <div className="mt-1.5 grid grid-cols-[minmax(0,1fr)] gap-1.5 @[30rem]:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_4.5rem]">
                        <label className="sr-only" htmlFor={`${uid}-t${i}`}>{`${i + 1}枚目の見出し`}</label>
                        <input
                          id={`${uid}-t${i}`}
                          value={sl.title}
                          maxLength={MAX.title}
                          placeholder="見出し"
                          onFocus={() => i !== idxRef.current && go(i)}
                          onChange={(e) => edit(i, { title: e.target.value })}
                          className={`slide-title min-h-11 border border-stone-300 bg-white px-2.5 text-[15px] ${focusRing}`}
                        />
                        {i > 0 && (
                          <>
                            <label className="sr-only" htmlFor={`${uid}-v${i}`}>{`${i + 1}枚目の数字・ことば`}</label>
                            <input
                              id={`${uid}-v${i}`}
                              value={sl.value}
                              maxLength={MAX.value}
                              placeholder="数字・ことば"
                              inputMode={toNum(sl.value) !== null ? "numeric" : undefined}
                              onFocus={() => i !== idxRef.current && go(i)}
                              onChange={(e) => edit(i, { value: e.target.value })}
                              className={`slide-value min-h-11 border border-stone-300 bg-white px-2.5 text-[15px] ${focusRing}`}
                            />
                            <label className="sr-only" htmlFor={`${uid}-u${i}`}>{`${i + 1}枚目の単位`}</label>
                            <input
                              id={`${uid}-u${i}`}
                              value={sl.unit}
                              maxLength={MAX.unit}
                              placeholder="単位"
                              onFocus={() => i !== idxRef.current && go(i)}
                              onChange={(e) => edit(i, { unit: e.target.value })}
                              className={`min-h-11 border border-stone-300 bg-white px-2.5 text-[15px] ${focusRing}`}
                            />
                          </>
                        )}
                        <label className="sr-only" htmlFor={`${uid}-n${i}`}>{`${i + 1}枚目のひとこと`}</label>
                        <input
                          id={`${uid}-n${i}`}
                          value={sl.note}
                          maxLength={MAX.note}
                          placeholder="ひとこと(なくても可)"
                          onFocus={() => i !== idxRef.current && go(i)}
                          onChange={(e) => edit(i, { note: e.target.value })}
                          className={`min-h-11 border border-stone-300 bg-white px-2.5 text-[14px] text-stone-700 @[30rem]:col-span-3 ${focusRing}`}
                        />
                      </div>
                    </li>
                  ))}
                </ol>
                <label className="mt-3 flex min-h-11 items-center gap-2.5 text-[14px] text-stone-700">
                  <input
                    type="checkbox"
                    checked={recap.credit}
                    onChange={(e) => {
                      setEdited(true);
                      setRecap((r) => ({ ...r, credit: e.target.checked }));
                    }}
                    className={`size-4 accent-[#b45309] ${focusRing}`}
                  />
                  画像の左下に作成元の小さな表記を入れる
                </label>
                <div className="mt-3 flex flex-wrap gap-2">
                  <button type="button" onClick={() => copy("url")} className={`copy-url border-stone-900 bg-white text-stone-900 hover:bg-stone-100 ${btn} ${focusRing}`}>
                    {copied === "url" ? "URLをコピーしました ✓" : "このまとめのURLをコピー"}
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setEdited(false);
                      setRecap(DEFAULT_RECAP);
                      history.replaceState(null, "", location.pathname + location.search);
                      go(0);
                    }}
                    className={`border-stone-300 bg-white text-stone-700 hover:border-stone-900 ${btn} ${focusRing}`}
                  >
                    見本に戻す
                  </button>
                </div>
                <p className="mt-2 text-[12px] leading-[1.7] text-stone-500">
                  URL の # のあとに入れた内容が入ります。どこにも送られず、同じ URL を開くと同じまとめが出ます。
                </p>
              </div>
            </details>

            <details className="group border-b border-stone-200">
              <summary className={`code-open flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 py-3 text-[15px] font-bold [&::-webkit-details-marker]:hidden ${focusRing}`}>
                このストーリーの React コードをコピー
                <span aria-hidden="true" className="text-stone-500 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none">
                  ▸
                </span>
              </summary>
              <div className="pb-5">
                <p className="text-[13px] leading-[1.7] text-stone-600">入れた6枚と店名が入った TSX の1ファイルです(依存なし・Tailwind CSS v4)。</p>
                <pre tabIndex={0} className={`mt-3 max-h-72 overflow-auto bg-stone-950 p-4 text-[12px] leading-[1.7] text-stone-100 ${focusRing}`}>
                  <code>{reactCode(recap)}</code>
                </pre>
                <button type="button" onClick={() => copy("code")} className={`copy-code mt-3 border-stone-900 bg-white text-stone-900 hover:bg-stone-100 ${btn} ${focusRing}`}>
                  {copied === "code" ? "コピーしました ✓" : "React のコードをコピー"}
                </button>
              </div>
            </details>
          </div>
        </div>

        {/* 年末年始の、ほかの部品 */}
        <nav aria-label="年末年始のほかの部品" className="@[44rem]:col-start-2 @[44rem]:row-start-3 @[44rem]:self-end">
          <p className="text-[13px] font-bold text-stone-600">年末年始の告知に合わせて</p>
          <ul className="mt-2 divide-y divide-stone-200 border-y border-stone-200 text-[14px]">
            {RELATED.map((r) => (
              <li key={r.href}>
                <a
                  href={r.href}
                  className={`flex min-h-11 flex-col justify-center gap-0.5 py-2 hover:text-[#b45309] @[30rem]:flex-row @[30rem]:items-center @[30rem]:justify-between @[30rem]:gap-3 ${focusRing}`}
                >
                  <span className="font-bold">{r.title}</span>
                  <span className="text-[13px] text-stone-500 @[30rem]:text-right">{r.note}</span>
                </a>
              </li>
            ))}
          </ul>
          <p className="mt-3 text-[12px] text-stone-500">店名と数字は架空の見本です。</p>
        </nav>
      </div>
    </section>
  );
}

shadcn CLI でプロジェクトに追加

npx shadcn@latest add https://designs.first-ch.com/r/year-recap-stories.json