TYP-05Typography

Vertical Japanese Text Checker | Fix Sideways Digits, Latin and Symbols with Tate-chu-yoko (writing-mode, text-combine-upright)

Sets pasted Japanese text vertically with writing-mode: vertical-rl, finds half-width digits, Latin words and symbols that fall sideways using seven rules, and shows the plain version (red numbers) next to a fixed version (amber) in two equal-height panels. Up to two digits and "!?" become tate-chu-yoko with text-combine-upright: all; three or more digits become kanji or full-width; Latin words can stand upright with text-orientation: upright or stay sideways; half-width brackets, hyphens and tildes become full-width; "..." becomes "……" and a single "—" becomes "――". Per-rule toggles re-set the fixed panel instantly, in a Mincho stack with font-feature-settings: "vpal". The horizontal scrollbar is hidden in favour of a thin progress line, and both panels scroll together. Copy the fixed HTML (with spans) and CSS, save the comparison as a 1200×630 image, and share texts up to 400 characters via the URL fragment. Runs entirely in the browser; no dependencies. The sample text is a fictional confectioner's history.

Preview

TYP-05

縦書きの崩れ診断

貼り付けた文章から、縦書きで横倒しになる半角の数字・英字・記号を探して直します(処理はブラウザ内で完結します)

崩れ9か所直した版で0

そのままvertical-rl だけ

宵月堂(よいづきどう)の由来

宵月堂は1925年、城下の坂の途中に小さな店を構えたのがはじまりです。初代は月見の晩に、灯籠の明かりで餡を炊いたと伝えられています。いまの店主は四代目。季節ごとに12種の上生菓子を並べ、朝の八時から仕込みを始めます。

看板の「月あかり」は、白餡に柚子を合わせた薄焼きの最中です。皮を一枚ずつ手で焼くため、一日に焼けるのは三百枚まで。売り切れた日は、のれんを早めに下ろします。

近ごろは遠方からのお客さまも増え、包み紙に英語でWagashiと添えるようになりました。「こんなに軽いの!?」と驚かれることもしばしばです。

夏は葛(くず)、冬は栗。季節が移るたびに品書きを書き換えます。お取り置きは前日の17時まで、電話か店頭で承ります。

甘さは控えめに—それが、創業から変わらない約束です。また来年の月見の晩に、お会いできますように...

直した版縦中横・全角・vpal

宵月堂(よいづきどう)の由来

宵月堂は一九二五年、城下の坂の途中に小さな店を構えたのがはじまりです。初代は月見の晩に、灯籠の明かりで餡を炊いたと伝えられています。いまの店主は四代目。季節ごとに12種の上生菓子を並べ、朝の八時から仕込みを始めます。

看板の「月あかり」は、白餡に柚子を合わせた薄焼きの最中です。皮を一枚ずつ手で焼くため、一日に焼けるのは三百枚まで。売り切れた日は、のれんを早めに下ろします。

近ごろは遠方からのお客さまも増え、包み紙に英語でWagashiと添えるようになりました。「こんなに軽いの!?」と驚かれることもしばしばです。

夏は葛(くず)、冬は栗。季節が移るたびに品書きを書き換えます。お取り置きは前日の17時まで、電話か店頭で承ります。

甘さは控えめに――それが、創業から変わらない約束です。また来年の月見の晩に、お会いできますように……

2枚は連動してスクロールします。ホイール・横スワイプ・矢印キーで読み進められ、下の線が今読んでいる位置を示します。

見つかった崩れ(押すと左右の版がその箇所までスクロール)

直す規則(切ると右の版が元に戻ります)

本文(400字まで)は URL の # に載り、サーバーには送られません

writing-mode

vertical-rl で右から左へ縦に組みます。和字は立ちますが、半角の数字・英字・記号は横向きの字として90度寝ます。左の版はこの状態です。直した版は明朝に font-feature-settings: "vpal" を足し、かなを縦の字幅で詰めています。

text-combine-upright

all を付けた span の中身を、1字分の幅に横書きで収めます(縦中横)。2桁までの数字と「!?」に使い、3桁以上は字が潰れるので漢数字か全角に置き換えます。古い Safari 向けに -webkit-text-combine: horizontal も書いています。

text-orientation

upright で英字を1字ずつ立てます。略語や短い語に向き、長い語は横倒しのほうが読みやすいので、規則3で選べるようにしました。

仕様: CSS Writing Modes Level 4(W3C)・日本語組版処理の要件(W3C)

見本の文章に登場する和菓子屋は架空のものです。ルビ・禁則は扱わず、ブラウザの組版に任せています。

Share on X

Read the full description

Sets pasted Japanese text vertically with writing-mode: vertical-rl, finds half-width digits, Latin words and symbols that fall sideways using seven rules, and shows the plain version (red numbers) next to a fixed version (amber) in two equal-height panels. Up to two digits and "!?" become tate-chu-yoko with text-combine-upright: all; three or more digits become kanji or full-width; Latin words can stand upright with text-orientation: upright or stay sideways; half-width brackets, hyphens and tildes become full-width; "..." becomes "……" and a single "—" becomes "――". Per-rule toggles re-set the fixed panel instantly, in a Mincho stack with font-feature-settings: "vpal". The horizontal scrollbar is hidden in favour of a thin progress line, and both panels scroll together. Copy the fixed HTML (with spans) and CSS, save the comparison as a 1200×630 image, and share texts up to 400 characters via the URL fragment. Runs entirely in the browser; no dependencies. The sample text is a fictional confectioner's history.

Added:
2026-11-05
Updated:
2026-11-07
Dependencies:
None
tags
#typography #japanese #vertical-text #writing-mode #text-combine-upright #text-orientation #tate-chu-yoko #font-feature-settings #vpal #checker #share-image #no-dependency #no-image
"use client";

import {
  useCallback,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from "react";

/**
 * 縦書きの崩れ診断(貼った文章の、縦書きで寝る半角数字・英字・記号を見つけて、直した版と左右で比べる)
 *
 * 差別化: 既存の縦書き(ヒーローや代表メッセージの縦組み見出し・おみくじの札)は、縦組みを見た目の飾りに使う見本。本ブロックは
 * 縦組みの「崩れ」を検査する道具で、素の vertical-rl と直した版を同じ高さの2枚で並べ、崩れを番号で対応させる。直前の約物詰め
 * (横組みの見出し)とは組み方向も扱う字も違う。英字の小見出し・見出しの「。」止め・末尾の矢印リンク・角丸・出現アニメは使わない。
 *
 * 汎用技法メモ:
 * 1. 縦組みは writing-mode: vertical-rl だけで組むと、半角の数字・英字・記号が90度寝る(UTR #50 で回転と決まる字)。
 *    2桁までの数字と「!?」は text-combine-upright: all(Safari 旧版は -webkit-text-combine: horizontal も)で1字分に収める。
 * 2. 3桁以上の数字は縦中横にすると潰れて読めない。漢数字(年の前は「一九二五」、量は「三百」)か全角に置き換える。
 * 3. 英単語は text-orientation: upright で1字ずつ立てるか、横倒しのまま読ませるかを書き手が選ぶ(短い略語は立て、長い語は寝かせる)。
 * 4. 縦組みの横スクロールは scrollLeft が 0 から負の向きに進む(Chrome・Safari・Firefox とも)。進み具合は |scrollLeft| ÷
 *    (scrollWidth − clientWidth)。縦のホイールは、端に着くまでだけ横送りに替えて、端ではページのスクロールへ返す。
 * 5. canvas には縦書きが無いので、1字ずつ置く。半角は90度回し、括弧・長音・ダッシュも回し、句読点は右上へずらす。
 */

const AMBER = "#d97706";
const RED = "#dc2626";
const PAGE_URL = "https://designs.first-ch.com/d/tategaki-scroll-reading";
export const SHARE_LIMIT = 400;
const MAX_LEN = 3000;
const MINCHO =
  '"Yu Mincho", YuMincho, "Hiragino Mincho ProN", "Hiragino Mincho Pro", "Noto Serif JP", "Noto Serif CJK JP", serif';
const focusRing =
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]";

export const SAMPLE = `宵月堂(よいづきどう)の由来

宵月堂は1925年、城下の坂の途中に小さな店を構えたのがはじまりです。初代は月見の晩に、灯籠の明かりで餡を炊いたと伝えられています。いまの店主は四代目。季節ごとに12種の上生菓子を並べ、朝の八時から仕込みを始めます。

看板の「月あかり」は、白餡に柚子を合わせた薄焼きの最中です。皮を一枚ずつ手で焼くため、一日に焼けるのは三百枚まで。売り切れた日は、のれんを早めに下ろします。

近ごろは遠方からのお客さまも増え、包み紙に英語でWagashiと添えるようになりました。「こんなに軽いの!?」と驚かれることもしばしばです。

夏は葛(くず)、冬は栗。季節が移るたびに品書きを書き換えます。お取り置きは前日の17時まで、電話か店頭で承ります。

甘さは控えめに—それが、創業から変わらない約束です。また来年の月見の晩に、お会いできますように...`;

export type RuleId = 1 | 2 | 3 | 4 | 5 | 6 | 7;
export const RULE_IDS: RuleId[] = [1, 2, 3, 4, 5, 6, 7];
export const RULES: Record<RuleId, { name: string; fix: string }> = {
  1: { name: "2桁までの半角数字", fix: "縦中横(text-combine-upright: all)" },
  2: { name: "3桁以上の数字", fix: "漢数字か全角に置き換え" },
  3: { name: "半角の英単語", fix: "立てる(text-orientation: upright)か横倒しのまま" },
  4: { name: "「!?」「!!」と半角の「!」「?」", fix: "2字は縦中横・1字は全角" },
  5: { name: "半角のカッコ・ハイフン・チルダ・%", fix: "全角に置き換え" },
  6: { name: "「...」", fix: "「……」(2字分)に置き換え" },
  7: { name: "1字だけの「—」", fix: "「――」(2字分)に置き換え" },
};

export type Issue = {
  id: number;
  rule: RuleId;
  raw: string;
  /** 規則2の置き換え候補 */
  kanji?: string;
  full?: string;
};
export type Seg = { text: string; issue?: Issue };
export type NumMode = "kanji" | "full";
export type LatinMode = "upright" | "sideways";
export type Options = {
  on: Record<RuleId, boolean>;
  num: NumMode;
  latin: LatinMode;
};
export type Fixed =
  | { kind: "text"; text: string }
  | { kind: "tcy"; text: string }
  | { kind: "up"; text: string };

export const DEFAULT_OPTIONS: Options = {
  on: { 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true },
  num: "kanji",
  latin: "upright",
};

const KD = "〇一二三四五六七八九";
const toFull = (s: string) =>
  s.replace(/[!-~]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 0xfee0));

/** 位取りの漢数字(300→三百・1200→千二百・20000→二万)。1兆未満の整数だけ */
export function kanjiNumber(n: number): string {
  if (n === 0) return "〇";
  const small = ["", "十", "百", "千"];
  const big = ["", "万", "億"];
  let out = "";
  let rest = n;
  for (let g = 0; rest > 0 && g < big.length; g++) {
    const part = rest % 10000;
    rest = Math.floor(rest / 10000);
    if (part === 0) continue;
    let s = "";
    String(part)
      .padStart(4, "0")
      .split("")
      .forEach((d, i) => {
        const v = Number(d);
        const unit = small[3 - i];
        if (v === 0) return;
        s += (v === 1 && unit ? "" : KD[v]) + unit;
      });
    out = s + big[g] + out;
  }
  return out;
}

/** 3桁以上の数字の漢数字。年・小数・先頭0は1字ずつ(一九二五)、量は位取り(三百) */
export function toKanji(raw: string, next = "") {
  const plain = raw.replace(/,/g, "");
  if (
    next === "年" ||
    plain.includes(".") ||
    plain.startsWith("0") ||
    plain.length > 12
  )
    return plain.replace(/[0-9]/g, (d) => KD[Number(d)]).replace(/\./g, "・");
  return kanjiNumber(Number(plain));
}

const SWAP: Record<string, string> = {
  "(": "(",
  ")": ")",
  "[": "[",
  "]": "]",
  "-": "-",
  "~": "〜",
  "%": "%",
};

const RE =
  /(\.{3,})|([!?]{2}|[!?])|([0-9]{1,3}(?:,[0-9]{3})+|[0-9]+(?:\.[0-9]+)?)|([A-Za-z]+(?:[-' ][A-Za-z]+)*)|([—―]+)|([()[\]\-~%])/g;

/** 文章を、崩れる箇所(番号付き)とそれ以外に切り分ける */
export function diagnose(text: string): Seg[] {
  const src = Array.from(text.replace(/\r\n?/g, "\n")).slice(0, MAX_LEN).join("");
  const out: Seg[] = [];
  let last = 0;
  let id = 0;
  const plain = (s: string) => {
    if (!s) return;
    const prev = out[out.length - 1];
    if (prev && !prev.issue) prev.text += s;
    else out.push({ text: s });
  };
  for (const m of src.matchAll(RE)) {
    const raw = m[0];
    const at = m.index ?? 0;
    let rule: RuleId | null = null;
    if (m[1]) rule = 6;
    else if (m[2]) rule = 4;
    else if (m[3]) {
      const digits = raw.replace(/[.,]/g, "").length;
      rule = digits <= 2 || (raw.includes(".") && raw.length <= 3) ? 1 : 2;
    } else if (m[4]) rule = 3;
    else if (m[5]) rule = raw.length === 1 ? 7 : null;
    else if (m[6]) rule = 5;
    plain(src.slice(last, at));
    last = at + raw.length;
    if (!rule) {
      plain(raw);
      continue;
    }
    const issue: Issue = { id: ++id, rule, raw };
    if (rule === 2) {
      issue.kanji = toKanji(raw, src[at + raw.length]);
      issue.full = toFull(raw);
    }
    out.push({ text: raw, issue });
  }
  plain(src.slice(last));
  return out;
}

/** 直した版の1か所。規則を切っていれば元のまま */
export function fixIssue(issue: Issue, o: Options): Fixed {
  const raw = issue.raw;
  if (!o.on[issue.rule]) return { kind: "text", text: raw };
  switch (issue.rule) {
    case 1:
      return { kind: "tcy", text: raw };
    case 2:
      return {
        kind: "text",
        text: (o.num === "kanji" ? issue.kanji : issue.full) ?? raw,
      };
    case 3:
      return o.latin === "upright"
        ? { kind: "up", text: raw }
        : { kind: "text", text: raw };
    case 4:
      return raw.length === 2
        ? { kind: "tcy", text: raw }
        : { kind: "text", text: toFull(raw) };
    case 5:
      return { kind: "text", text: SWAP[raw] ?? raw };
    case 6:
      return { kind: "text", text: "……" };
    case 7:
      return { kind: "text", text: "――" };
  }
}

/** 残っている崩れ(規則を切った箇所)の数 */
export const remaining = (segs: Seg[], o: Options) =>
  segs.filter((s) => s.issue && !o.on[s.issue.rule]).length;

const esc = (s: string) =>
  s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");

/** 直した本文の HTML(改行ごとに p、空行は飛ばす) */
export function buildHtml(segs: Seg[], o: Options) {
  const body = segs
    .map((s) => {
      if (!s.issue) return esc(s.text);
      const f = fixIssue(s.issue, o);
      if (f.kind === "tcy") return `<span class="tcy">${esc(f.text)}</span>`;
      if (f.kind === "up") return `<span class="upright">${esc(f.text)}</span>`;
      return esc(f.text);
    })
    .join("");
  const ps = body
    .split("\n")
    .filter((l) => l.trim() !== "")
    .map((l) => `  <p>${l}</p>`)
    .join("\n");
  return `<div class="tategaki">\n${ps}\n</div>`;
}

export const CSS = `.tategaki {
  writing-mode: vertical-rl;
  font-family: ${MINCHO};
  font-feature-settings: "vpal";
  line-height: 1.9;
  block-size: 30em;
  overflow-x: auto;
  scrollbar-width: none;
}
.tategaki::-webkit-scrollbar { display: none; }
.tategaki p { margin: 0; margin-block-end: 0.9em; }
/* 2桁までの数字・「!?」を1字分に収める */
.tategaki .tcy {
  text-combine-upright: all;
  -webkit-text-combine: horizontal;
  font-feature-settings: normal;
}
/* 英単語を1字ずつ立てる */
.tategaki .upright { text-orientation: upright; }`;

/** 共有リンクの #(本文が400字以内のときだけ本文を載せる) */
export function encodeState(text: string, o: Options) {
  const p = new URLSearchParams();
  p.set("t", text);
  const off = RULE_IDS.filter((r) => !o.on[r]);
  if (off.length) p.set("off", off.join(""));
  if (o.num !== "kanji") p.set("n", "full");
  if (o.latin !== "upright") p.set("e", "side");
  return p.toString();
}

export function decodeState(hash: string): { text: string; o: Options } | null {
  const p = new URLSearchParams(hash.replace(/^#/, ""));
  const t = p.get("t");
  if (!t) return null;
  const text = Array.from(t).slice(0, SHARE_LIMIT).join("");
  const off = new Set((p.get("off") ?? "").split("").map(Number));
  const on = { ...DEFAULT_OPTIONS.on };
  for (const r of RULE_IDS) on[r] = !off.has(r);
  return {
    text,
    o: {
      on,
      num: p.get("n") === "full" ? "full" : "kanji",
      latin: p.get("e") === "side" ? "sideways" : "upright",
    },
  };
}

/* ---------- 比較画像(1200×630) ---------- */

type Cell = {
  text: string;
  mode: "up" | "side" | "tcy";
  mark?: number;
};

const ROTATE = /[ー-―—〜~…‥「」『』()[]【】〔〕〈〉《》=]/;
const PUNCT = /[、。,.]/;
const SMALL = /[ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ]/;

/** 1字ずつのセル列。null は改行、"gap" は段落の空き */
function toCells(segs: Seg[], o: Options | null): (Cell | null | "gap")[] {
  const cells: (Cell | null | "gap")[] = [];
  const pushText = (t: string, mark?: number, upright = false) => {
    let first = true;
    for (const ch of Array.from(t)) {
      if (ch === "\n") {
        const prev = cells[cells.length - 1];
        cells.push(prev === null ? "gap" : null);
        continue;
      }
      const ascii = ch.charCodeAt(0) < 0x7f;
      cells.push({
        text: ch,
        mode: ascii && !upright ? "side" : "up",
        mark: first ? mark : mark === undefined ? undefined : -mark,
      });
      first = false;
    }
  };
  for (const s of segs) {
    if (!s.issue) {
      pushText(s.text);
      continue;
    }
    if (!o) {
      pushText(s.text, s.issue.id);
      continue;
    }
    const f = fixIssue(s.issue, o);
    if (f.kind === "tcy") cells.push({ text: f.text, mode: "tcy", mark: s.issue.id });
    else pushText(f.text, s.issue.id, f.kind === "up");
  }
  return cells;
}

function drawPanel(
  ctx: CanvasRenderingContext2D,
  cells: (Cell | null | "gap")[],
  box: { x: number; y: number; w: number; h: number },
  color: string,
) {
  const size = 16;
  const pitch = 27;
  let cx = box.x + box.w - pitch / 2;
  let y = box.y;
  const bottom = box.y + box.h;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  for (const c of cells) {
    if (c === null || c === "gap") {
      cx -= c === "gap" ? pitch * 0.4 : pitch;
      y = box.y;
      continue;
    }
    ctx.font = `500 ${size}px ${MINCHO}`;
    const adv =
      c.mode === "side" ? Math.max(ctx.measureText(c.text).width, size * 0.3) : size;
    if (y + adv > bottom) {
      cx -= pitch;
      y = box.y;
    }
    if (cx < box.x) return;
    if (c.mark !== undefined) {
      ctx.fillStyle = color === RED ? "#fee2e2" : "#fef3c7";
      ctx.fillRect(cx - size / 2 - 2, y, size + 4, adv);
    }
    ctx.fillStyle = c.mark !== undefined && color === RED ? RED : "#1c1917";
    ctx.save();
    ctx.translate(cx, y + adv / 2);
    if (c.mode === "side" || ROTATE.test(c.text)) ctx.rotate(Math.PI / 2);
    else if (PUNCT.test(c.text)) ctx.translate(size * 0.6, -size * 0.6);
    else if (SMALL.test(c.text)) ctx.translate(size * 0.1, -size * 0.1);
    if (c.mode === "tcy") {
      const w = ctx.measureText(c.text).width;
      if (w > size) ctx.scale(size / w, 1);
    }
    ctx.fillText(c.text, 0, 1);
    ctx.restore();
    if (c.mark !== undefined && c.mark > 0) {
      ctx.fillStyle = color;
      ctx.fillRect(cx + size / 2 + 2, y, 12, 12);
      ctx.fillStyle = "#fff";
      ctx.font = `700 9px Montserrat, sans-serif`;
      ctx.fillText(String(c.mark), cx + size / 2 + 8, y + 6.5);
    }
    y += adv;
  }
}

async function renderImage(segs: Seg[], o: Options, before: number, after: number) {
  const W = 1200;
  const H = 630;
  const cv = document.createElement("canvas");
  cv.width = W;
  cv.height = H;
  const ctx = cv.getContext("2d");
  if (!ctx) return null;
  const all = segs.map((s) => s.text).join("");
  await document.fonts?.load(`500 16px ${MINCHO}`, all).catch(() => undefined);
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, W, H);
  ctx.strokeStyle = "#e7e5e4";
  ctx.lineWidth = 1;
  ctx.fillStyle = "#1c1917";
  ctx.textAlign = "left";
  ctx.textBaseline = "alphabetic";
  ctx.font = `700 28px "Noto Sans JP", sans-serif`;
  ctx.fillText("縦書きの崩れ診断", 48, 62);
  ctx.textAlign = "right";
  ctx.font = `700 26px "Noto Sans JP", sans-serif`;
  const tail = ` か所 → `;
  const aw = ctx.measureText(String(after)).width;
  ctx.fillStyle = AMBER;
  ctx.fillText(String(after), W - 48, 62);
  ctx.fillStyle = "#57534e";
  ctx.fillText(tail, W - 48 - aw, 62);
  const tw = ctx.measureText(tail).width;
  ctx.fillStyle = RED;
  ctx.fillText(String(before), W - 48 - aw - tw, 62);
  const bw = ctx.measureText(String(before)).width;
  ctx.fillStyle = "#57534e";
  ctx.fillText("崩れ ", W - 48 - aw - tw - bw, 62);
  ctx.beginPath();
  ctx.moveTo(48, 88.5);
  ctx.lineTo(W - 48, 88.5);
  ctx.moveTo(600.5, 104);
  ctx.lineTo(600.5, 590);
  ctx.moveTo(48, 590.5);
  ctx.lineTo(W - 48, 590.5);
  ctx.stroke();
  ctx.textAlign = "left";
  ctx.font = `700 15px "Noto Sans JP", sans-serif`;
  ctx.fillStyle = RED;
  ctx.fillText("そのまま(writing-mode: vertical-rl だけ)", 48, 122);
  ctx.fillStyle = "#92400e";
  ctx.fillText("直した版(縦中横・全角・vpal)", 632, 122);
  drawPanel(ctx, toCells(segs, null), { x: 48, y: 140, w: 528, h: 436 }, RED);
  drawPanel(ctx, toCells(segs, o), { x: 632, y: 140, w: 520, h: 436 }, AMBER);
  ctx.textAlign = "left";
  ctx.textBaseline = "alphabetic";
  ctx.fillStyle = "#78716c";
  ctx.font = `500 14px Montserrat, "Noto Sans JP", sans-serif`;
  ctx.fillText("designs.first-ch.com/d/tategaki-scroll-reading", 48, 616);
  const blob = await new Promise<Blob | null>((r) => cv.toBlob(r, "image/png"));
  return blob;
}

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

type CopyTarget = "html" | "css" | "link";
type CopyResult = { target: CopyTarget; state: "ok" | "fail"; text: string };

function Panel({
  label,
  spec,
  tone,
  children,
  panelRef,
  barRef,
  className = "",
}: {
  label: string;
  spec: string;
  tone: "raw" | "fixed";
  children: ReactNode;
  panelRef: (el: HTMLDivElement | null) => void;
  barRef: (el: HTMLSpanElement | null) => void;
  className?: string;
}) {
  return (
    <figure className={`min-w-0 ${className}`}>
      <figcaption className="flex flex-wrap items-baseline gap-x-2 pb-2">
        <span
          className={`text-[13px] font-bold ${tone === "raw" ? "text-red-700" : "text-amber-800"}`}
        >
          {label}
        </span>
        <span className="font-mono text-[11px] text-stone-500">{spec}</span>
      </figcaption>
      <div
        ref={panelRef}
        tabIndex={0}
        role="region"
        aria-label={`${label}(横に送って読む)`}
        className={`tate-panel w-full h-[19rem] overflow-x-auto overflow-y-hidden border-y border-stone-200 py-3 text-[15px] leading-[2.15] text-stone-900 [scrollbar-width:none] [writing-mode:vertical-rl] @xl:h-[25rem] @xl:text-[17px] @4xl:h-[29rem] [&::-webkit-scrollbar]:hidden ${tone === "fixed" ? "bg-amber-50/30" : "bg-white"} ${focusRing}`}
        style={{
          fontFamily: MINCHO,
          fontFeatureSettings: tone === "fixed" ? '"vpal"' : "normal",
        }}
      >
        {children}
      </div>
      <div className="relative h-px bg-stone-200" aria-hidden="true">
        <span
          ref={barRef}
          className="absolute inset-y-[-1px] right-0 w-full origin-right bg-[#d97706]"
          style={{ transform: "scaleX(0)" }}
        />
      </div>
    </figure>
  );
}

function Badge({ n, tone }: { n: number; tone: "raw" | "fixed" }) {
  // 位置は本文の em で決める(外側は字の大きさを変えない)。中身は横書きにして数字を寝かせない
  return (
    <span
      aria-hidden="true"
      className="pointer-events-none absolute right-[-0.95em] top-0 [writing-mode:horizontal-tb]"
    >
      <span
        className={`grid h-[14px] w-[14px] place-items-center font-display text-[9px] font-bold leading-none text-white ${tone === "raw" ? "bg-red-600" : "bg-[#d97706]"}`}
      >
        {n}
      </span>
    </span>
  );
}

/** 本文を段落に分けて組む(空行の次の段落は1字分空ける) */
function Paragraphs({ nodes }: { nodes: ReactNode[][] }) {
  return (
    <>
      {nodes.map((line, i) =>
        line.length === 0 ? null : (
          <p
            key={i}
            className="m-0"
            style={{
              marginBlockStart: i > 0 && nodes[i - 1].length === 0 ? "0.9em" : 0,
            }}
          >
            {line}
          </p>
        ),
      )}
    </>
  );
}

/** 区切った部品を改行で行に分ける */
function splitLines(parts: { key: string; node: ReactNode; text?: string }[]) {
  const lines: ReactNode[][] = [[]];
  for (const p of parts) {
    if (p.text === undefined) {
      lines[lines.length - 1].push(p.node);
      continue;
    }
    p.text.split("\n").forEach((t, i) => {
      if (i > 0) lines.push([]);
      if (t) lines[lines.length - 1].push(<span key={`${p.key}-${i}`}>{t}</span>);
    });
  }
  return lines;
}

// 2枚の連動のロック。who は最後に動かした枠(-1 は一覧からの移動中)
export type SyncLock = { who: number; until: number } | null;
// 一覧から飛ぶ間は時刻で切らず、2枚のスクロールが止まったのを確かめてから外す
// (2枚は中身の長さが違うので、途中で割合の同期が入ると片方が目標からずれる)
export const jumpLock = (): SyncLock => ({ who: -1, until: Infinity });
export const syncAllowed = (l: SyncLock, who: number, now: number) =>
  !l || l.who === who || (l.who !== -1 && now >= l.until);

export default function TategakiScrollReading() {
  const uid = useId();
  const [text, setText] = useState(SAMPLE);
  const [o, setO] = useState<Options>(DEFAULT_OPTIONS);
  const [copyResult, setCopyResult] = useState<CopyResult | null>(null);
  const [saveMsg, setSaveMsg] = useState("");
  const [active, setActive] = useState<number | null>(null);
  const panels = useRef<(HTMLDivElement | null)[]>([null, null]);
  const bars = useRef<(HTMLSpanElement | null)[]>([null, null]);
  const lock = useRef<SyncLock>(null);
  const settle = useRef(0);
  const htmlRef = useRef<HTMLTextAreaElement>(null);
  const cssRef = useRef<HTMLTextAreaElement>(null);
  const linkRef = useRef<HTMLInputElement>(null);

  const segs = useMemo(() => diagnose(text), [text]);
  const issues = useMemo(
    () => segs.flatMap((s) => (s.issue ? [s.issue] : [])),
    [segs],
  );
  const total = issues.length;
  const left = remaining(segs, o);
  const counts = useMemo(() => {
    const c: Record<RuleId, number> = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0 };
    for (const i of issues) c[i.rule]++;
    return c;
  }, [issues]);
  const html = useMemo(() => buildHtml(segs, o), [segs, o]);
  const chars = Array.from(text).length;
  const shareable = chars <= SHARE_LIMIT && chars > 0;
  const shareUrl = `${PAGE_URL}#${encodeState(text, o)}`;
  const status = (t: CopyTarget, v: string) =>
    copyResult && copyResult.target === t && copyResult.text === v
      ? copyResult.state
      : null;
  const htmlCopied = status("html", html);
  const cssCopied = status("css", CSS);
  const linkCopied = status("link", shareUrl);

  // 共有リンクで開いたとき・戻る/進むで # が変わったときに、同じ診断を開く
  useEffect(() => {
    const apply = () => {
      const got = decodeState(window.location.hash);
      if (got) {
        setText(got.text);
        setO(got.o);
      }
    };
    const id = requestAnimationFrame(apply);
    window.addEventListener("hashchange", apply);
    return () => {
      cancelAnimationFrame(id);
      window.removeEventListener("hashchange", apply);
    };
  }, []);

  // 進捗線を描き直す(右端から読み始めて左へ進む)
  const paint = useCallback((i: number) => {
    const el = panels.current[i];
    const bar = bars.current[i];
    if (!el || !bar) return 0;
    const max = el.scrollWidth - el.clientWidth;
    const p = max > 0 ? Math.min(1, Math.abs(el.scrollLeft) / max) : 1;
    bar.style.transform = `scaleX(${p})`;
    return p;
  }, []);

  // 2枚を同じ割合で送る。縦のホイールは端に着くまでだけ横送りにする
  useEffect(() => {
    const els = panels.current;
    const offs: (() => void)[] = [];
    els.forEach((el, i) => {
      if (!el) return;
      const onScroll = () => {
        const p = paint(i);
        const now = performance.now();
        if (!syncAllowed(lock.current, i, now)) return;
        lock.current = { who: i, until: now + 120 };
        const other = els[1 - i];
        if (!other) return;
        const max = other.scrollWidth - other.clientWidth;
        other.scrollLeft = -p * max;
      };
      const onWheel = (e: WheelEvent) => {
        if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return;
        const max = el.scrollWidth - el.clientWidth;
        const pos = Math.abs(el.scrollLeft);
        if (max <= 0) return;
        if ((e.deltaY > 0 && pos >= max - 1) || (e.deltaY < 0 && pos <= 0)) return;
        e.preventDefault();
        el.scrollLeft -= e.deltaY;
      };
      el.addEventListener("scroll", onScroll, { passive: true });
      el.addEventListener("wheel", onWheel, { passive: false });
      offs.push(() => {
        el.removeEventListener("scroll", onScroll);
        el.removeEventListener("wheel", onWheel);
      });
    });
    const ro = new ResizeObserver(() => {
      paint(0);
      paint(1);
    });
    els.forEach((el) => el && ro.observe(el));
    const watching = settle;
    return () => {
      cancelAnimationFrame(watching.current);
      offs.forEach((f) => f());
      ro.disconnect();
    };
  }, [paint]);

  // 本文や設定が変わったら進捗線を測り直す
  useEffect(() => {
    paint(0);
    paint(1);
  }, [segs, o, paint]);

  // 一覧の番号を押したら、2枚ともその箇所を中央へ送る
  // 2枚とも位置が4コマ続けて動かなくなったら(動き出す前の150msは待ち、最長4秒で)連動のロックを外す
  // 押した時刻はイベントの timeStamp(performance.now と同じ基準)から取る
  const jump = (id: number, at: number) => {
    setActive(id);
    const smooth = !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    lock.current = jumpLock();
    cancelAnimationFrame(settle.current);
    let last = "";
    let still = 0;
    const watch = () => {
      const pos = panels.current.map((el) => el?.scrollLeft ?? 0).join(",");
      still = pos === last ? still + 1 : 0;
      last = pos;
      const t = performance.now() - at;
      if ((still >= 4 && t > 150) || t > 4000) {
        lock.current = null;
        return;
      }
      settle.current = requestAnimationFrame(watch);
    };
    panels.current.forEach((el) => {
      const m = el?.querySelector<HTMLElement>(`[data-mark="${id}"]`);
      if (!el || !m) return;
      const a = m.getBoundingClientRect();
      const b = el.getBoundingClientRect();
      el.scrollBy({
        left: a.left + a.width / 2 - (b.left + b.width / 2),
        behavior: smooth ? "smooth" : "auto",
      });
    });
    settle.current = requestAnimationFrame(watch);
  };

  const rawParts = segs.map((s, i) =>
    s.issue
      ? {
          key: `r${i}`,
          node: (
            <span
              key={`r${i}`}
              data-mark={s.issue.id}
              className={`relative text-red-700 ${active === s.issue.id ? "bg-red-200" : "bg-red-50"}`}
            >
              {s.text}
              <Badge n={s.issue.id} tone="raw" />
            </span>
          ),
        }
      : { key: `r${i}`, node: null, text: s.text },
  );
  const fixedParts = segs.map((s, i) => {
    if (!s.issue) return { key: `f${i}`, node: null, text: s.text };
    const f = fixIssue(s.issue, o);
    const fixedOn = o.on[s.issue.rule];
    return {
      key: `f${i}`,
      node: (
        <span
          key={`f${i}`}
          data-mark={s.issue.id}
          className={`relative ${fixedOn ? (active === s.issue.id ? "bg-amber-200" : "bg-amber-100") : "bg-red-50 text-red-700"}`}
        >
          {f.kind === "tcy" ? (
            <span className="[-webkit-text-combine:horizontal] [font-feature-settings:normal] [text-combine-upright:all]">
              {f.text}
            </span>
          ) : f.kind === "up" ? (
            <span className="[text-orientation:upright]">{f.text}</span>
          ) : (
            f.text
          )}
          <Badge n={s.issue.id} tone={fixedOn ? "fixed" : "raw"} />
        </span>
      ),
    };
  });

  const copy = async (target: CopyTarget, value: string) => {
    try {
      await navigator.clipboard.writeText(value);
      setCopyResult({ target, state: "ok", text: value });
    } catch {
      setCopyResult({ target, state: "fail", text: value });
      requestAnimationFrame(() => {
        const el =
          target === "html" ? htmlRef.current : target === "css" ? cssRef.current : linkRef.current;
        el?.focus();
        el?.select();
      });
    }
  };

  const save = async () => {
    setSaveMsg("画像を作っています…");
    const blob = await renderImage(segs, o, total, left);
    if (!blob) {
      setSaveMsg("画像を作れませんでした。このブラウザでは canvas が使えません");
      return;
    }
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "tategaki-check.png";
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 4000);
    setSaveMsg("左右の比較を 1200×630 の PNG で保存しました");
  };

  const setRule = (r: RuleId) =>
    setO((p) => ({ ...p, on: { ...p.on, [r]: !p.on[r] } }));

  const btn = `inline-flex min-h-10 items-center justify-center border px-3.5 text-[13.5px] font-bold transition-[transform,opacity] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100 ${focusRing}`;
  const radio = (checked: boolean) =>
    `flex min-h-9 flex-1 cursor-pointer items-center justify-center border px-2 text-[12.5px] has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[#d97706] ${checked ? "border-stone-900 bg-stone-900 text-white" : "border-stone-300 bg-white text-stone-700"}`;

  return (
    <section
      className="@container mx-auto w-full max-w-6xl border border-stone-200 bg-white text-stone-900"
      aria-labelledby={`${uid}-h`}
    >
      {/* 見出しと件数 */}
      <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-2 px-4 pb-3 pt-4 @xl:px-6">
        <div>
          <p className="font-display text-[11px] tracking-[0.18em] text-stone-500">TYP-05</p>
          <h2 id={`${uid}-h`} className="text-[1.1rem] font-bold @xl:text-[1.35rem]">
            縦書きの崩れ診断
          </h2>
          <p className="mt-0.5 text-[12.5px] text-stone-600">
            貼り付けた文章から、縦書きで横倒しになる半角の数字・英字・記号を探して直します(処理はブラウザ内で完結します)
          </p>
        </div>
        <p
          role="status"
          aria-live="polite"
          className="flex items-baseline gap-1.5 text-[14px] text-stone-600"
        >
          崩れ
          <span className="font-display text-[1.9rem] font-bold leading-none tabular-nums text-red-600">
            {total}
          </span>
          か所
          <span aria-hidden="true" className="px-0.5 text-stone-400">
            →
          </span>
          <span className="sr-only">直した版で</span>
          <span
            className={`font-display text-[1.9rem] font-bold leading-none tabular-nums ${left === 0 ? "text-[#d97706]" : "text-stone-900"}`}
          >
            {left}
          </span>
          {left > 0 && <span className="text-[12px]">(規則を切った分)</span>}
        </p>
      </div>

      {/* 狭い枠では 文章→比較→規則 の順に積み、広い枠では左列に文章と規則・右に比較を置く(置き場の幅で切り替える) */}
      <div className="grid border-t border-stone-200 @2xl:grid-cols-[15rem_minmax(0,1fr)] @4xl:grid-cols-[18rem_minmax(0,1fr)] @2xl:grid-rows-[auto_1fr]">
        {/* 入力 */}
        <div className="border-stone-200 px-4 pt-4 @xl:px-6 @2xl:col-start-1 @2xl:row-start-1 @2xl:border-r">
          <label htmlFor={`${uid}-t`} className="flex items-baseline justify-between text-[13px] font-bold">
            文章を貼る
            <span className="font-display text-[11px] font-normal tabular-nums text-stone-500">
              {chars} / {MAX_LEN}字
            </span>
          </label>
          <textarea
            id={`${uid}-t`}
            value={text}
            maxLength={MAX_LEN}
            onChange={(e) => {
              setText(e.target.value);
              setActive(null);
            }}
            rows={4}
            spellCheck={false}
            className={`tate-input mt-1.5 block w-full resize-y border border-stone-300 bg-white p-2.5 text-[16px] leading-relaxed @2xl:h-[13rem] ${focusRing}`}
          />
          <div className="mt-1.5 flex gap-3 text-[12.5px]">
            <button
              type="button"
              onClick={() => setText(SAMPLE)}
              className={`sample underline decoration-stone-300 underline-offset-4 hover:decoration-[#d97706] ${focusRing}`}
            >
              見本の文章に戻す
            </button>
            <button
              type="button"
              onClick={() => setText("")}
              className={`underline decoration-stone-300 underline-offset-4 hover:decoration-[#d97706] ${focusRing}`}
            >
              空にする
            </button>
          </div>

        </div>

        {/* 左右の比較 */}
        <div className="min-w-0 px-4 py-4 @xl:px-6 @2xl:col-start-2 @2xl:row-span-2 @2xl:row-start-1">
          <div className="grid grid-cols-2 gap-3 @xl:gap-5">
            <Panel
              label="そのまま"
              spec="vertical-rl だけ"
              tone="raw"
              panelRef={(el) => {
                panels.current[0] = el;
              }}
              barRef={(el) => {
                bars.current[0] = el;
              }}
            >
              <Paragraphs nodes={splitLines(rawParts)} />
            </Panel>
            <Panel
              label="直した版"
              spec="縦中横・全角・vpal"
              tone="fixed"
              panelRef={(el) => {
                panels.current[1] = el;
              }}
              barRef={(el) => {
                bars.current[1] = el;
              }}
            >
              <Paragraphs nodes={splitLines(fixedParts)} />
            </Panel>
          </div>
          <p className="mt-2 text-[11.5px] text-stone-500">
            2枚は連動してスクロールします。ホイール・横スワイプ・矢印キーで読み進められ、下の線が今読んでいる位置を示します。
          </p>

          {/* 見つかった崩れの一覧 */}
          <div className="mt-4 border-t border-stone-200 pt-3">
            <h3 className="text-[13px] font-bold">見つかった崩れ(押すと左右の版がその箇所までスクロール)</h3>
            {total === 0 ? (
              <p className="mt-2 text-[13px] text-stone-600">
                縦書きで横倒しになる字は見つかりませんでした。
              </p>
            ) : (
              <ol className="issue-list mt-2 flex flex-wrap gap-1.5">
                {issues.map((i) => {
                  const f = fixIssue(i, o);
                  const on = o.on[i.rule];
                  return (
                    <li key={i.id}>
                      <button
                        type="button"
                        onClick={(e) => jump(i.id, e.timeStamp)}
                        aria-pressed={active === i.id}
                        className={`flex min-h-9 items-center gap-1.5 border px-2 text-[12.5px] transition-[transform] active:scale-[0.97] motion-reduce:transition-none ${active === i.id ? "border-[#d97706] bg-amber-50" : "border-stone-200 bg-white hover:border-stone-400"} ${focusRing}`}
                      >
                        <span className="grid h-4 w-4 place-items-center bg-red-600 font-display text-[10px] font-bold text-white">
                          {i.id}
                        </span>
                        <span className="font-mono text-red-700">{i.raw}</span>
                        <span aria-hidden="true" className="text-stone-400">
                          ›
                        </span>
                        <span className={on ? "text-amber-800" : "text-stone-400 line-through"}>
                          {!on
                            ? "直さない"
                            : f.kind === "tcy"
                              ? `縦中横「${f.text}」`
                              : f.kind === "up"
                                ? `立てる「${f.text}」`
                                : i.rule === 3
                                  ? "横倒しのまま"
                                  : `「${f.text}」`}
                        </span>
                      </button>
                    </li>
                  );
                })}
              </ol>
            )}
          </div>
        </div>
        {/* 規則 */}
        <div className="border-t border-stone-200 px-4 py-4 @xl:px-6 @2xl:col-start-1 @2xl:row-start-2 @2xl:border-r @2xl:border-t-0">
          <fieldset>
            <legend className="text-[13px] font-bold">直す規則(切ると右の版が元に戻ります)</legend>
            <ul className="mt-1.5 divide-y divide-stone-200 border-y border-stone-200">
              {RULE_IDS.map((r) => (
                <li key={r} className={counts[r] === 0 ? "opacity-60" : ""}>
                  <label className="flex min-h-11 cursor-pointer items-center gap-2.5 py-1.5 has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[#d97706]">
                    <input
                      type="checkbox"
                      checked={o.on[r]}
                      onChange={() => setRule(r)}
                      className={`rule-${r} h-4 w-4 shrink-0 accent-[#d97706]`}
                    />
                    <span className="min-w-0 flex-1">
                      <span className="block text-[13px] font-bold leading-snug">
                        <span className="font-display tabular-nums text-stone-500">{r}</span>{" "}
                        {RULES[r].name}
                      </span>
                      <span className="block text-[11.5px] leading-snug text-stone-500">
                        {RULES[r].fix}
                      </span>
                    </span>
                    <span
                      className={`font-display text-[13px] font-bold tabular-nums ${counts[r] ? "text-red-600" : "text-stone-400"}`}
                    >
                      {counts[r]}
                    </span>
                  </label>
                  {r === 2 && (
                    <div role="radiogroup" aria-label="3桁以上の数字の直し方" className="flex gap-1.5 pb-2 pl-6">
                      {(
                        [
                          ["kanji", "漢数字"],
                          ["full", "全角"],
                        ] as const
                      ).map(([v, l]) => (
                        <label key={v} className={radio(o.num === v)}>
                          <input
                            type="radio"
                            name={`${uid}-num`}
                            className="sr-only"
                            checked={o.num === v}
                            onChange={() => setO((p) => ({ ...p, num: v }))}
                          />
                          {l}
                        </label>
                      ))}
                    </div>
                  )}
                  {r === 3 && (
                    <div role="radiogroup" aria-label="英単語の向き" className="flex gap-1.5 pb-2 pl-6">
                      {(
                        [
                          ["upright", "立てる"],
                          ["sideways", "横倒しのまま"],
                        ] as const
                      ).map(([v, l]) => (
                        <label key={v} className={radio(o.latin === v)}>
                          <input
                            type="radio"
                            name={`${uid}-latin`}
                            className={`latin-${v} sr-only`}
                            checked={o.latin === v}
                            onChange={() => setO((p) => ({ ...p, latin: v }))}
                          />
                          {l}
                        </label>
                      ))}
                    </div>
                  )}
                </li>
              ))}
            </ul>
          </fieldset>
        </div>
      </div>

      {/* 出力と共有 */}
      <div className="grid gap-4 border-t border-stone-200 px-4 py-4 @xl:px-6 @3xl:grid-cols-2">
        <div className="min-w-0">
          <label htmlFor={`${uid}-html`} className="text-[13px] font-bold">
            直した本文の HTML
          </label>
          <textarea
            id={`${uid}-html`}
            ref={htmlRef}
            readOnly
            value={html}
            rows={7}
            className={`mt-1.5 block w-full resize-y border border-stone-200 bg-stone-50 p-2.5 font-mono text-[12.5px] leading-relaxed ${focusRing}`}
          />
          <button
            type="button"
            onClick={() => copy("html", html)}
            className={`copy-html mt-2 ${btn} border-stone-900 bg-stone-900 text-white hover:bg-amber-800`}
          >
            HTML をコピー
          </button>
          <p aria-live="polite" className="mt-1 min-h-5 text-[12.5px] text-stone-600">
            {htmlCopied === "ok" && "コピーしました"}
            {htmlCopied === "fail" && "コピーできませんでした。欄の内容を選択したので、Ctrl+C(⌘C)でコピーしてください"}
          </p>
        </div>
        <div className="min-w-0">
          <label htmlFor={`${uid}-css`} className="text-[13px] font-bold">
            CSS
          </label>
          <textarea
            id={`${uid}-css`}
            ref={cssRef}
            readOnly
            value={CSS}
            rows={7}
            className={`mt-1.5 block w-full resize-y border border-stone-200 bg-stone-50 p-2.5 font-mono text-[12.5px] leading-relaxed ${focusRing}`}
          />
          <button
            type="button"
            onClick={() => copy("css", CSS)}
            className={`copy-css mt-2 ${btn} border-stone-900 bg-white text-stone-900 hover:border-[#d97706]`}
          >
            CSS をコピー
          </button>
          <p aria-live="polite" className="mt-1 min-h-5 text-[12.5px] text-stone-600">
            {cssCopied === "ok" && "コピーしました"}
            {cssCopied === "fail" && "コピーできませんでした。欄の内容を選択したので、Ctrl+C(⌘C)でコピーしてください"}
          </p>
        </div>
        <div className="flex flex-wrap items-start gap-x-6 gap-y-2 border-t border-stone-200 pt-4 @3xl:col-span-2">
          <div>
            <button
              type="button"
              onClick={save}
              disabled={chars === 0}
              className={`save-image ${btn} border-[#d97706] bg-[#d97706] text-white hover:bg-amber-700 disabled:opacity-40`}
            >
              左右の比較を画像で保存(1200×630)
            </button>
            <p aria-live="polite" className="mt-1 min-h-5 text-[12.5px] text-stone-600">
              {saveMsg}
            </p>
          </div>
          <div>
            <button
              type="button"
              onClick={() => copy("link", shareUrl)}
              disabled={!shareable}
              className={`copy-link ${btn} border-stone-900 bg-white text-stone-900 hover:border-[#d97706] disabled:opacity-40`}
            >
              この診断のリンクをコピー
            </button>
            <p aria-live="polite" className="mt-1 min-h-5 text-[12.5px] text-stone-600">
              {!shareable && chars > 0
                ? `本文が${SHARE_LIMIT}字を超えるため、リンクに載せられません(今${chars}字)`
                : linkCopied === "ok"
                  ? "リンクをコピーしました。開くと同じ本文と規則で診断します"
                  : linkCopied === "fail"
                    ? "コピーできませんでした。下の欄のリンクを選んでコピーしてください"
                    : `本文(${SHARE_LIMIT}字まで)は URL の # に載り、サーバーには送られません`}
            </p>
            {linkCopied === "fail" && (
              <input
                ref={linkRef}
                readOnly
                value={shareUrl}
                aria-label="この診断のリンク"
                className="mt-1 w-full max-w-md border border-stone-300 p-2 font-mono text-[12px]"
              />
            )}
          </div>
        </div>
      </div>

      {/* 解説 */}
      <div className="grid border-t border-stone-200 @3xl:grid-cols-3 @3xl:divide-x @3xl:divide-stone-200">
        <div className="px-4 py-4 @xl:px-6">
          <h3 className="font-mono text-[14px] font-bold">writing-mode</h3>
          <p className="mt-1.5 text-[13px] leading-relaxed text-stone-700">
            vertical-rl で右から左へ縦に組みます。和字は立ちますが、半角の数字・英字・記号は横向きの字として90度寝ます。左の版はこの状態です。直した版は明朝に font-feature-settings: &quot;vpal&quot; を足し、かなを縦の字幅で詰めています。
          </p>
        </div>
        <div className="border-t border-stone-200 px-4 py-4 @xl:px-6 @3xl:border-t-0">
          <h3 className="font-mono text-[14px] font-bold">text-combine-upright</h3>
          <p className="mt-1.5 text-[13px] leading-relaxed text-stone-700">
            all を付けた span の中身を、1字分の幅に横書きで収めます(縦中横)。2桁までの数字と「!?」に使い、3桁以上は字が潰れるので漢数字か全角に置き換えます。古い Safari 向けに -webkit-text-combine: horizontal も書いています。
          </p>
        </div>
        <div className="border-t border-stone-200 px-4 py-4 @xl:px-6 @3xl:border-t-0">
          <h3 className="font-mono text-[14px] font-bold">text-orientation</h3>
          <p className="mt-1.5 text-[13px] leading-relaxed text-stone-700">
            upright で英字を1字ずつ立てます。略語や短い語に向き、長い語は横倒しのほうが読みやすいので、規則3で選べるようにしました。
          </p>
          <p className="mt-2 text-[12px] text-stone-500">
            仕様:{" "}
            <a
              href="https://www.w3.org/TR/css-writing-modes-4/"
              target="_blank"
              rel="noopener noreferrer"
              className={`underline decoration-stone-300 underline-offset-4 hover:decoration-[#d97706] ${focusRing}`}
            >
              CSS Writing Modes Level 4(W3C)
            </a>
            ・
            <a
              href="https://www.w3.org/TR/jlreq/"
              target="_blank"
              rel="noopener noreferrer"
              className={`underline decoration-stone-300 underline-offset-4 hover:decoration-[#d97706] ${focusRing}`}
            >
              日本語組版処理の要件(W3C)
            </a>
          </p>
        </div>
      </div>
      <p className="border-t border-stone-200 px-4 py-2.5 text-[11.5px] text-stone-500 @xl:px-6">
        見本の文章に登場する和菓子屋は架空のものです。ルビ・禁則は扱わず、ブラウザの組版に任せています。
      </p>
    </section>
  );
}

Add to your project via shadcn CLI

npx shadcn@latest add https://designs.first-ch.com/r/tategaki-scroll-reading.json