BLK-111Blocks

Chromeの自動入力でフリガナ欄が弾かれる12通り|見出し×入力ルールの再現表(カタカナ変換コード付き)

フリガナ欄の見出し4種(フリガナ/ふりがな/よみがな/カナ)と入力ルール3種(全角カタカナのみ/ひらがなのみ/どちらでも)の12通りを「通る/弾かれる」で塗り分けた再現表です。マスを押すと、架空の「山田 花子」の読みが Chrome の自動入力で入り、送信して通るか赤いエラーになるかまでを再現します。判定は Chrome for Developers の記事の規則だけで、見出しにカタカナが1字でもあればカタカナ、なければひらがなで入ります。弾かれるマスでは「見出しを変える」「確定後にカタカナ(ひらがな)へ変換する」の2案を適用して再送信でき、変換は外部ライブラリなしの数行の React コードで示します。制作担当へそのまま送れる確認メモのコピー、12通りの表の画像保存(1200×630)、フォームの HTML を貼って autocomplete・name・label から読みの欄を判定する欄(端末内で解析・保存なし)付き。実際の補完結果ではなく、Chrome 以外のブラウザは対象外です。

プレビュー

BLK-111

自動入力で弾かれるのはどのマス?フリガナ欄12通りの再現表

見出しの書き方と入力ルールの組み合わせで、Chrome の自動入力がそのまま送信できるかが決まります。 自社のフォームに近いマスを押すと、架空の「山田 花子」で入力から送信までを再現します。

記事の規則による再現で、実際の補完結果ではありません。根拠: Chrome for Developers「Chrome の自動入力で日本語のふりがな名のサポートを改善」(2026年4月15日)。Chrome 以外のブラウザは対象外です。

見出し × 入力ルール

12通りのうち、弾かれるのは 4 通り

見出し4種と入力ルール3種の組み合わせごとに、自動入力のあと送信できるかを再現した表です(矢印キーで移動できます)
見出し \ ルール全角カタカナのみひらがなのみどちらでも
フリガナカタカナで入る
ふりがなひらがなで入る
よみがなひらがなで入る
カナカタカナで入る
  • 1 文字種は見出しで決まります。カタカナが1字でもあればカタカナ、なければひらがな。
  • 2 弾かれるのは「カタカナのみ×カタカナの無い見出し」と「ひらがなのみ×カタカナのある見出し」の2つの向き。
矢印キーでマスを移動できます。選んだマスに枠が付きます

再現: 架空の申込フォーム

  1. 1 候補を選ぶ
  2. 2 自動入力
  3. 3 送信

入力ルール: 全角カタカナのみpattern="[ァ-ヶー  ]+"

氏名
ふりがな見出し(label)

全角カタカナで入力してください(やまだ はなこ は不可)

✕ 送信できません。お客様が打ち直すことになります

欄の識別: name="family-name-phonetic" / autocomplete="family-name"(記事の手がかり)。入る文字種は見出しで決まります。

直し方(どちらか一方で通ります)

案2のコード(外部ライブラリなし)

// ひらがな → 全角カタカナ(ぁ〜ゖ を 0x60 ずらす。ー・中黒はそのまま)
export const toKatakana = (s: string) =>
  s.replace(/[\u3041-\u3096]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 0x60));

// 変換中(isComposing)は触らず、確定・自動入力・貼り付けのあとに直す
<input
  name="family-name-phonetic"
  autoComplete="family-name"
  pattern="[ァ-ヶー  ]+"
  value={kana}
  onChange={(e) => {
    const v = e.target.value;
    setKana((e.nativeEvent as InputEvent).isComposing ? v : toKatakana(v));
  }}
  onCompositionEnd={(e) => setKana(toKatakana(e.currentTarget.value))}
/>

制作担当へ送る確認メモ

技術に詳しくなくても、そのまま貼って送れます

詳しい人向け: フォームのHTMLを貼って判定する

手がかりは記事の順に見ます: autocomplete(標準の値だけ・最優先)→ name 属性 → 見出し(label)。非標準の autocomplete は「補完されない見込み」、どれにも当たらない欄は「記事の範囲では識別できません」とします。 貼ったHTMLはこの端末の中で読むだけで、送信・保存・script の実行はしません。

フォームの離脱を減らしたい

自動入力で止まる欄・エラーの出し方・項目の削り方まで、お問い合わせフォームの改善を相談できます。

フォーム改善を相談する

X でシェア

説明の全文を読む

フリガナ欄の見出し4種(フリガナ/ふりがな/よみがな/カナ)と入力ルール3種(全角カタカナのみ/ひらがなのみ/どちらでも)の12通りを「通る/弾かれる」で塗り分けた再現表です。マスを押すと、架空の「山田 花子」の読みが Chrome の自動入力で入り、送信して通るか赤いエラーになるかまでを再現します。判定は Chrome for Developers の記事の規則だけで、見出しにカタカナが1字でもあればカタカナ、なければひらがなで入ります。弾かれるマスでは「見出しを変える」「確定後にカタカナ(ひらがな)へ変換する」の2案を適用して再送信でき、変換は外部ライブラリなしの数行の React コードで示します。制作担当へそのまま送れる確認メモのコピー、12通りの表の画像保存(1200×630)、フォームの HTML を貼って autocomplete・name・label から読みの欄を判定する欄(端末内で解析・保存なし)付き。実際の補完結果ではなく、Chrome 以外のブラウザは対象外です。

追加日:
2026-11-07
更新日:
2026-11-08
依存:
なし
tags
#form #furigana #autofill #chrome #validation #katakana #diagnostic #copy-memo #no-dependency #japanese #ui #no-image
"use client";

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

/**
 * フリガナ欄の自動入力 再現表(見出し4種 × 入力ルール3種 = 12通り)
 *
 * 差別化: 既存のフォーム系(contact-form-block・text-field・jp-address-autofill)は欄の並びや入力中の状態を見せる部品。
 * 本ブロックは「見出しの書き方 × 入力ルール」の12通りを1枚の表で塗り分け、押したマスの自動入力と送信の結果を再現し、
 * 直し方の適用・制作担当への確認メモ・貼ったHTMLの判定までを1操作でつなぐ診断表。英字の小見出し・見出しの「。」止め・
 * 末尾の矢印リンク・角丸・出現アニメは使わない。
 *
 * 判定に使うのは Chrome for Developers の記事(2026-04-15)に書かれた規則だけ:
 * - 文字種は欄の <label> で決まる。カタカナが1字でもあればカタカナ、なければひらがなで入る(name 属性は見ない)
 * - 欄の識別は autocomplete(最優先・標準値のみ。非標準値ではほかの手がかりへ戻らない)→ name → <label> の順
 * - ふりがな専用の autocomplete 値は無く、読みの欄にも name / family-name / given-name を使う
 * 実際の補完結果ではない。Chrome 以外のブラウザの挙動は扱わない。
 *
 * 汎用技法メモ:
 * 1. **かな変換は文字コードを 0x60 ずらすだけ**。ぁ(U+3041)〜ゖ(U+3096) と ァ(U+30A1)〜ヶ(U+30F6) は同じ並び。
 *    ヷ〜ヺ・ー・中黒は対応するひらがなが無いのでそのまま残す。外部ライブラリは要らない。
 * 2. **変換は「確定したあと」に掛ける**。IME の変換中(isComposing)の値を書き換えると候補が壊れるので、
 *    compositionend と、変換中でない input(自動入力・貼り付け)でだけ直す。送信時に直すのでは遅い
 *    (pattern の検査は submit イベントより先に走る)。
 * 3. **貼ったHTMLは DOMParser で読むだけ**。DOMParser の文書は script を実行せず画像も読み込まない。
 *    結果は文字列として React に描かせ、innerHTML へは戻さない。
 * 4. **表の移動は roving tabindex**。Tab で表に入るのは選択中の1マスだけで、矢印キーで隣のマスへ移り、そのまま再現する。
 *
 * 人物・フォームはすべて架空の見本。
 */

/* ───────── 規則(記事に書かれていることだけ) ───────── */

export const ARTICLE_URL = "https://developer.chrome.com/blog/japanese-phonetic-name-autofill";
export const ARTICLE_TITLE = "Chrome の自動入力で日本語のふりがな名のサポートを改善";
export const ARTICLE_DATE = "2026年4月15日";

export const HEADINGS = ["フリガナ", "ふりがな", "よみがな", "カナ"] as const;
export type RuleId = "kata" | "hira" | "any";
export const RULES: { id: RuleId; label: string; short: string; hint: string; pattern: string }[] = [
  { id: "kata", label: "全角カタカナのみ", short: "カタカナのみ", hint: "全角カタカナで入力してください", pattern: "[ァ-ヶー  ]+" },
  { id: "hira", label: "ひらがなのみ", short: "ひらがなのみ", hint: "ひらがなで入力してください", pattern: "[ぁ-ゖー  ]+" },
  { id: "any", label: "どちらでも", short: "どちらでも", hint: "ひらがな・カタカナどちらでも", pattern: "[ぁ-ゖァ-ヶー  ]+" },
];

export const PERSON = { family: "山田", given: "花子", familyHira: "やまだ", givenHira: "はなこ" } as const;

/** カタカナ(全角の文字・半角カナ)を1字でも含むか。長音符「ー」と中黒「・」は記事に記載がないので数えない */
export const hasKatakana = (s: string) => /[ァ-ヺヽヾヲ-ッア-ン]/.test(s);
export type Script = "kata" | "hira";
export const scriptOf = (label: string): Script => (hasKatakana(label) ? "kata" : "hira");

export const toKatakana = (s: string) =>
  s.replace(/[ぁ-ゖ]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 0x60));
export const toHiragana = (s: string) =>
  s.replace(/[ァ-ヶ]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0x60));
export const inScript = (s: string, sc: Script) => (sc === "kata" ? toKatakana(s) : toHiragana(s));

export const passes = (value: string, rule: RuleId) =>
  new RegExp(`^(?:${RULES.find((r) => r.id === rule)!.pattern})$`, "u").test(value);

/** 弾かれる向き。null は通る */
export type Direction = "needKata" | "needHira" | null;
export function verdict(heading: string, rule: RuleId): Direction {
  const sc = scriptOf(heading);
  if (rule === "kata" && sc === "hira") return "needKata";
  if (rule === "hira" && sc === "kata") return "needHira";
  return null;
}

/** 案1で見出しを差し替えるときの行き先 */
export const fixedHeading = (dir: Direction) => (dir === "needKata" ? "フリガナ" : dir === "needHira" ? "ふりがな" : null);

export type Fix = "label" | "convert" | null;

/** そのマス(と直し方)で、送信までに起きること */
export function simulate(heading: string, rule: RuleId, fix: Fix) {
  const dir = verdict(heading, rule);
  const label = fix === "label" && dir ? fixedHeading(dir)! : heading;
  const filled = scriptOf(label);
  const raw = { family: inScript(PERSON.familyHira, filled), given: inScript(PERSON.givenHira, filled) };
  const target: Script | null = fix === "convert" && dir ? (dir === "needKata" ? "kata" : "hira") : null;
  const sent = target ? { family: inScript(raw.family, target), given: inScript(raw.given, target) } : raw;
  const ok = passes(sent.family, rule) && passes(sent.given, rule);
  return { dir, label, filled, raw, sent, converted: target !== null, ok };
}

const SCRIPT_JA = { kata: "カタカナ", hira: "ひらがな" } as const;

/** 制作担当へそのまま送れる確認メモ */
export function memoText(heading: string, rule: RuleId) {
  const r = RULES.find((x) => x.id === rule)!;
  const dir = verdict(heading, rule);
  const sim = simulate(heading, rule, null);
  const sample = `${sim.raw.family} ${sim.raw.given}`;
  const lines = [
    "【フォームのフリガナ欄 確認メモ】",
    `今の組み合わせ: 見出し「${heading}」/入力ルール「${r.label}」`,
  ];
  if (!dir) {
    lines.push(
      `起きること: Chrome の自動入力は見出しの文字から${SCRIPT_JA[sim.filled]}(${sample})を入れます。入力ルールに合うので、そのまま送信できます。`,
      "直し方: 不要です(このままで送信できます)。",
      rule === "any"
        ? "注意: 入力ルールを片方の文字だけに絞るときは、見出しの文字種と合わせてください。"
        : `注意: 見出しを「${sim.filled === "kata" ? "ふりがな" : "フリガナ"}」のように${sim.filled === "kata" ? "カタカナを含まない" : "カタカナを含む"}書き方へ変えると、送信でエラーになります。`,
    );
  } else {
    const want = dir === "needKata" ? "kata" : "hira";
    lines.push(
      `起きること: Chrome の自動入力は見出しに${dir === "needKata" ? "カタカナが無いため、ひらがな" : "カタカナがあるため、カタカナ"}(${sample})を入れます。送信すると「${r.hint}」のエラーになり、お客様が手で打ち直す必要があります。`,
      "直し方(どちらか一方で通ります):",
      `  案1: 見出しを「${fixedHeading(dir)}」に変える(${dir === "needKata" ? "カタカナを1字でも含めると、自動入力がカタカナで入ります" : "カタカナを含めなければ、自動入力がひらがなで入ります"})`,
      `  案2: 確定した${SCRIPT_JA[sim.filled]}を、検査の前に${SCRIPT_JA[want]}へ変換する(変換中の文字には触らない)`,
    );
  }
  lines.push(
    `根拠: Chrome for Developers「${ARTICLE_TITLE}」(${ARTICLE_DATE}) ${ARTICLE_URL}`,
    "※ 記事の規則による再現で、実際の補完結果ではありません。Chrome 以外のブラウザは対象外です。",
  );
  return lines.join("\n");
}

/** 案2のコード(外部ライブラリなし・React) */
export function convertCode(dir: Direction) {
  const kata = dir !== "needHira";
  const fn = kata ? "toKatakana" : "toHiragana";
  return [
    kata
      ? `// ひらがな → 全角カタカナ(ぁ〜ゖ を 0x60 ずらす。ー・中黒はそのまま)
export const toKatakana = (s: string) =>
  s.replace(/[\\u3041-\\u3096]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 0x60));`
      : `// 全角カタカナ → ひらがな(ァ〜ヶ を 0x60 ずらす。ヷ〜ヺ・ー はそのまま)
export const toHiragana = (s: string) =>
  s.replace(/[\\u30a1-\\u30f6]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0x60));`,
    "",
    `// 変換中(isComposing)は触らず、確定・自動入力・貼り付けのあとに直す
<input
  name="family-name-phonetic"
  autoComplete="family-name"
  pattern="${kata ? "[ァ-ヶー  ]+" : "[ぁ-ゖー  ]+"}"
  value={kana}
  onChange={(e) => {
    const v = e.target.value;
    setKana((e.nativeEvent as InputEvent).isComposing ? v : ${fn}(v));
  }}
  onCompositionEnd={(e) => setKana(${fn}(e.currentTarget.value))}
/>`,
  ].join("\n");
}

/* ───────── 貼ったHTMLの判定 ───────── */

// HTML の autocomplete の欄名(autofill field name)
const AC_FIELDS = new Set(
  (
    "name honorific-prefix given-name additional-name family-name honorific-suffix nickname username new-password " +
    "current-password one-time-code organization-title organization street-address address-line1 address-line2 address-line3 " +
    "address-level4 address-level3 address-level2 address-level1 country country-name postal-code cc-name cc-given-name " +
    "cc-additional-name cc-family-name cc-number cc-exp cc-exp-month cc-exp-year cc-csc cc-type transaction-currency " +
    "transaction-amount language bday bday-day bday-month bday-year sex url photo tel tel-country-code tel-national " +
    "tel-area-code tel-local tel-local-prefix tel-local-suffix tel-extension email impp"
  ).split(" "),
);
const AC_CONTACT = new Set(["home", "work", "mobile", "fax", "pager"]);
const AC_CONTACT_OK = /^(tel|email|impp)/;

/** autocomplete の値を読む。標準でなければ null */
export function parseAutocomplete(v: string): { field: string } | null {
  const t = v.trim().toLowerCase().split(/\s+/).filter(Boolean);
  if (t[t.length - 1] === "webauthn") t.pop();
  const field = t.pop();
  if (!field || !AC_FIELDS.has(field)) return null;
  if (t[0]?.startsWith("section-")) t.shift();
  if (t[0] === "shipping" || t[0] === "billing") t.shift();
  if (t[0] && AC_CONTACT.has(t[0]) && AC_CONTACT_OK.test(field)) t.shift();
  return t.length ? null : { field };
}

type Kind = "full" | "family" | "given";
const KIND_JA: Record<Kind, string> = { full: "氏名", family: "姓", given: "名" };
// 記事の表にある文字列(長いものから見る)
const NAME_CUES: [Kind, string[]][] = [
  ["full", ["full-name-phonetic", "セイメイ", "せいめい"]],
  ["family", ["family-name-phonetic", "セイ", "せい"]],
  ["given", ["given-name-phonetic", "メイ", "名ふりがな"]],
];
const LABEL_CUES: [Kind, string[]][] = [
  ["full", ["セイメイ", "せいめい"]],
  ["family", ["セイ", "せい", "姓ふりがな"]],
  ["given", ["メイ", "めい", "名ふりがな"]],
];
const findCue = (s: string, cues: [Kind, string[]][]) => {
  for (const [kind, list] of cues) for (const c of list) if (s.includes(c)) return { kind, cue: c };
  return null;
};

export type FieldInput = { tag: string; name: string; id: string; autocomplete: string | null; label: string; pattern: string | null };
export type FieldResult = {
  field: string;
  kind: "phonetic" | "regular" | "other" | "nonstandard" | "unknown";
  title: string;
  basis: string;
  script: Script | null;
  check: string;
  bad: boolean;
};

export function classifyField(f: FieldInput): FieldResult {
  const field = f.name || f.id || `${f.tag}(name なし)`;
  const ac = f.autocomplete?.trim() ?? "";
  const acHint = ac && !/^(on|off)$/i.test(ac);
  const nameCue = findCue(f.name, NAME_CUES);
  const labelCue = findCue(f.label, LABEL_CUES);
  const phon = nameCue
    ? { kind: nameCue.kind, basis: `name 属性に「${nameCue.cue}」` }
    : labelCue
      ? { kind: labelCue.kind, basis: `見出し(label)に「${labelCue.cue}」` }
      : null;
  const base = { field, script: null, check: "", bad: false } as const;

  if (acHint) {
    const p = parseAutocomplete(ac);
    if (!p)
      return { ...base, kind: "nonstandard", title: "補完されない見込み", basis: `autocomplete="${ac}" は標準の値ではありません。記事では、非標準の値はほかの手がかりへ戻らないとしています`, bad: true };
    const nameKind: Kind | null = p.field === "name" ? "full" : p.field === "family-name" ? "family" : p.field === "given-name" ? "given" : null;
    if (!nameKind) return { ...base, kind: "other", title: `名前以外(${p.field})`, basis: `autocomplete="${ac}" が最優先` };
    if (!phon) return { ...base, kind: "regular", title: `通常の名前(${KIND_JA[nameKind]})`, basis: `autocomplete="${ac}"。name と見出しに読みの手がかりなし` };
    return withScript(f, { ...base, kind: "phonetic", title: `読み(${KIND_JA[nameKind]})`, basis: `autocomplete="${ac}" + ${phon.basis}`, script: null, check: "", bad: false });
  }
  if (!phon)
    return { ...base, kind: "unknown", title: "記事の範囲では識別できません", basis: ac ? `autocomplete="${ac}" は手がかりになりません。name 属性と見出しにも、記事で挙げられた語は含まれていません` : "autocomplete の指定はありません。name 属性と見出しにも、記事で挙げられた語は含まれていません" };
  return withScript(f, { ...base, kind: "phonetic", title: `読み(${KIND_JA[phon.kind]})`, basis: phon.basis, script: null, check: "", bad: false });
}

function withScript(f: FieldInput, r: FieldResult): FieldResult {
  const script = scriptOf(f.label);
  const sample = script === "kata" ? "ヤマダ" : "やまだ";
  let check = "pattern なし(サーバー側の検査はここでは見えません)";
  let bad = false;
  if (f.pattern) {
    try {
      // pattern 属性は v フラグで読む(使えない環境は u で)
      let re: RegExp;
      try {
        re = new RegExp(`^(?:${f.pattern})$`, "v");
      } catch {
        re = new RegExp(`^(?:${f.pattern})$`, "u");
      }
      const ok = re.test(sample);
      check = ok ? `通る(${sample} が pattern に合う)` : `弾かれる見込み(${sample} が pattern に合わない)`;
      bad = !ok;
    } catch {
      check = "pattern を読めませんでした";
    }
  }
  return { ...r, script, check, bad };
}

const labelOf = (doc: Document, el: Element) => {
  const parts: string[] = [];
  const id = el.getAttribute("id");
  if (id) doc.querySelectorAll("label").forEach((l) => l.getAttribute("for") === id && parts.push(l.textContent ?? ""));
  const wrap = el.closest("label");
  if (wrap) parts.push(wrap.textContent ?? "");
  return parts.join(" ").replace(/\s+/g, " ").trim();
};

export const MAX_HTML = 100_000;

/** 貼ったHTMLを端末の中で読む(DOMParser は script を実行せず、画像も読み込まない) */
export function judgeHtml(html: string): FieldResult[] {
  if (!html.trim() || typeof DOMParser === "undefined") return [];
  const doc = new DOMParser().parseFromString(html.slice(0, MAX_HTML), "text/html");
  const skip = /^(hidden|submit|button|reset|checkbox|radio|file|image|range|color|date|datetime-local|month|week|time|number|password)$/i;
  return Array.from(doc.querySelectorAll("input, textarea"))
    .filter((el) => !(el.tagName === "INPUT" && skip.test(el.getAttribute("type") ?? "")))
    .slice(0, 40)
    .map((el) =>
      classifyField({
        tag: el.tagName.toLowerCase(),
        name: el.getAttribute("name") ?? "",
        id: el.getAttribute("id") ?? "",
        autocomplete: el.getAttribute("autocomplete"),
        label: labelOf(doc, el),
        pattern: el.getAttribute("pattern"),
      }),
    );
}

export const SAMPLE_HTML = `<form>
  <label for="sei">姓</label>
  <input id="sei" name="family-name" autocomplete="family-name">
  <label for="kana-sei">ふりがな(セイ)</label>
  <input id="kana-sei" name="family-name-phonetic" autocomplete="family-name" pattern="[ァ-ヶー]+">
  <label for="kana-mei">よみがな(名)</label>
  <input id="kana-mei" name="kana_mei" autocomplete="furigana-given">
  <label for="mail">メールアドレス</label>
  <input id="mail" name="email" autocomplete="email">
  <label>カナ <input name="kana_full"></label>
</form>`;

/* ───────── 共有画像(1200×630) ───────── */

const xml = (t: string) => t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

export function shareSvg(sel: { h: number; r: number }) {
  const x0 = 300, y0 = 168, cw = 268, ch = 92;
  let cells = "";
  HEADINGS.forEach((h, i) => {
    const y = y0 + i * ch;
    cells += `<text x="${x0 - 24}" y="${y + 40}" text-anchor="end" font-size="30" font-weight="700" fill="#1c1917">${h}</text>`;
    cells += `<text x="${x0 - 24}" y="${y + 70}" text-anchor="end" font-size="17" fill="#78716c">${SCRIPT_JA[scriptOf(h)]}で入る</text>`;
    RULES.forEach((r, j) => {
      const x = x0 + j * cw;
      const dir = verdict(h, r.id);
      const s = simulate(h, r.id, null);
      cells += `<rect x="${x}" y="${y}" width="${cw}" height="${ch}" fill="${dir ? "url(#hatch)" : "#ffffff"}" stroke="#d6d3d1"/>`;
      cells += `<text x="${x + 22}" y="${y + 44}" font-size="30" font-weight="700" fill="${dir ? "#b91c1c" : "#047857"}">${dir ? "✕ 弾かれる" : "○ 通る"}</text>`;
      cells += `<text x="${x + 22}" y="${y + 72}" font-size="17" fill="#57534e">${xml(s.raw.family)} が入る</text>`;
      if (i === sel.h && j === sel.r) cells += `<rect x="${x + 3}" y="${y + 3}" width="${cw - 6}" height="${ch - 6}" fill="none" stroke="#d97706" stroke-width="5"/>`;
    });
  });
  RULES.forEach((r, j) => {
    cells += `<text x="${x0 + j * cw + 22}" y="${y0 - 20}" font-size="21" font-weight="700" fill="#44403c">${r.label}</text>`;
  });
  return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" font-family="'Noto Sans JP','Hiragino Sans','Yu Gothic',sans-serif">
<defs><pattern id="hatch" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="10" height="10" fill="#fef2f2"/><rect width="3" height="10" fill="#fecaca"/></pattern></defs>
<rect width="1200" height="630" fill="#ffffff"/>
<rect x="0" y="0" width="1200" height="8" fill="#d97706"/>
<text x="56" y="70" font-size="36" font-weight="700" fill="#1c1917">Chrome の自動入力で弾かれるフリガナ欄は12通り中4通り</text>
<text x="56" y="110" font-size="20" fill="#57534e">見出しにカタカナが1字でもあればカタカナ、なければひらがなで入る(架空の人物「山田 花子」で再現)</text>
${cells}
<text x="56" y="600" font-size="16" fill="#78716c">記事の規則による再現で、実際の補完結果ではありません ・ 根拠: Chrome for Developers(${ARTICLE_DATE})</text>
<text x="1144" y="600" text-anchor="end" font-size="16" font-weight="700" fill="#b45309">designs.first-ch.com</text>
</svg>`;
}

/* ───────── 画面 ───────── */

const focusRing =
  "outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]";
const CONTACT_URL = "https://first-ch.com/?utm_source=designs&utm_medium=referral&utm_campaign=furigana-name-fields#contact";

// 0 待機・1 候補を出す・2 自動入力・3 変換(案2のみ)・4 送信
type Stage = 0 | 1 | 2 | 3 | 4;
const STEP_LABELS = ["候補を選ぶ", "自動入力", "送信"];

export default function FuriganaNameFields({
  headingTag: Heading = "h2",
}: {
  headingTag?: "h1" | "h2" | "p";
}) {
  const uid = useId();
  const [sel, setSel] = useState({ h: 1, r: 0 });
  const [fix, setFix] = useState<Fix>(null);
  const [stage, setStage] = useState<Stage>(4);
  const [run, setRun] = useState(0);
  const [msg, setMsg] = useState("");
  const [copied, setCopied] = useState<"" | "memo" | "code" | "memo-ng" | "code-ng">("");
  const [png, setPng] = useState<string | null>(null);
  const [html, setHtml] = useState("");
  const cellRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const memoRef = useRef<HTMLTextAreaElement>(null);
  const codeRef = useRef<HTMLPreElement>(null);

  const heading = HEADINGS[sel.h];
  const rule = RULES[sel.r];
  const sim = simulate(heading, rule.id, fix);
  const dir = sim.dir;
  const memo = memoText(heading, rule.id);
  const code = convertCode(dir);
  const judged = useMemo(() => judgeHtml(html), [html]);
  const afterCell = fix === "label" && dir ? { h: HEADINGS.indexOf(fixedHeading(dir) as (typeof HEADINGS)[number]), r: sel.r } : null;
  const total = HEADINGS.length * RULES.length;
  const rejectedCount = HEADINGS.reduce((n, h) => n + RULES.filter((r) => verdict(h, r.id)).length, 0);

  // 押したら即座に候補を出し、あとは時間で進める(動きを減らす設定では結果だけ)
  useEffect(() => {
    if (run === 0) return;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const conv = sim.converted;
    const plan: [number, Stage][] = reduced
      ? [[0, 4]]
      : conv
        ? [[320, 2], [720, 3], [1120, 4]]
        : [[320, 2], [760, 4]];
    const ts = plan.map(([ms, st]) => window.setTimeout(() => setStage(st), ms));
    return () => ts.forEach(window.clearTimeout);
    // run が変わったときだけ流す
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [run]);

  // 書き出した画像の URL は差し替え・破棄で解放する
  useEffect(() => {
    if (!png) return;
    return () => URL.revokeObjectURL(png);
  }, [png]);

  const play = (next: { h: number; r: number }, nextFix: Fix) => {
    const s = simulate(HEADINGS[next.h], RULES[next.r].id, nextFix);
    setSel(next);
    setFix(nextFix);
    setStage(1);
    setRun((n) => n + 1);
    setCopied("");
    setMsg(
      `見出し「${s.label}」×${RULES[next.r].label}: ${s.ok ? "通る" : "弾かれる"}` +
        (nextFix === "label" ? "(案1を適用)" : nextFix === "convert" ? "(案2を適用)" : ""),
    );
  };

  const onCellKey = (e: KeyboardEvent<HTMLButtonElement>, h: number, r: number) => {
    const mv: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
    let next: { h: number; r: number } | null = null;
    if (mv[e.key]) next = { h: Math.min(3, Math.max(0, h + mv[e.key][0])), r: Math.min(2, Math.max(0, r + mv[e.key][1])) };
    if (e.key === "Home") next = { h, r: 0 };
    if (e.key === "End") next = { h, r: 2 };
    if (!next) return;
    e.preventDefault();
    if (next.h === h && next.r === r) return;
    play(next, null);
    cellRefs.current[next.h * 3 + next.r]?.focus();
  };

  const copy = async (what: "memo" | "code") => {
    try {
      await navigator.clipboard.writeText(what === "memo" ? memo : code);
      setCopied(what);
    } catch {
      if (what === "memo") memoRef.current?.select();
      else if (codeRef.current) window.getSelection()?.selectAllChildren(codeRef.current);
      setCopied(what === "memo" ? "memo-ng" : "code-ng");
    }
  };

  const savePng = () => {
    const img = new Image();
    const src = URL.createObjectURL(new Blob([shareSvg(sel)], { type: "image/svg+xml" }));
    img.onload = () => {
      const c = document.createElement("canvas");
      c.width = 1200;
      c.height = 630;
      const ctx = c.getContext("2d");
      URL.revokeObjectURL(src);
      if (!ctx) return;
      ctx.drawImage(img, 0, 0);
      c.toBlob((blob) => {
        if (!blob) return;
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "furigana-autofill-12.png";
        a.click();
        setPng(url);
        setMsg("12通りの表を画像(1200×630)で保存しました");
      }, "image/png");
    };
    img.onerror = () => {
      URL.revokeObjectURL(src);
      setMsg("画像を作れませんでした");
    };
    img.src = src;
  };

  const shown = stage >= 2;
  const values = stage >= 3 && sim.converted ? sim.sent : sim.raw;
  const submitted = stage === 4;
  const invalid = submitted && !sim.ok;
  const stepIdx = stage <= 1 ? 0 : stage < 4 ? 1 : 2;
  const readLabel = sim.label;

  return (
    <section aria-labelledby={`${uid}-h`} className="fn-root @container mx-auto w-full max-w-6xl border border-stone-200 bg-white text-stone-900">
      {/* 見出し */}
      <div className="px-4 pb-3 pt-4 sm:px-6">
        <p className="font-display text-[11px] font-semibold tracking-[0.18em] text-stone-500">BLK-111</p>
        <Heading id={`${uid}-h`} className="mt-1 text-[1.1rem] font-bold leading-[1.5] [word-break:keep-all] sm:text-[1.35rem]">
          自動入力で弾かれるのはどのマス?
          <wbr />
          フリガナ欄12通りの再現表
        </Heading>
        <p className="mt-1.5 max-w-[46em] text-[13.5px] leading-[1.8] text-stone-600">
          見出しの書き方と入力ルールの組み合わせで、Chrome の自動入力がそのまま送信できるかが決まります。
          自社のフォームに近いマスを押すと、架空の「山田 花子」で入力から送信までを再現します。
        </p>
      </div>
      {/* 常に出す注意 */}
      <p className="flex flex-wrap items-baseline gap-x-2 border-y border-amber-200 bg-amber-50 px-4 py-2 text-[12.5px] leading-[1.7] text-amber-950 sm:px-6">
        <strong className="font-bold">記事の規則による再現で、実際の補完結果ではありません。</strong>
        <span>
          根拠:{" "}
          <a href={ARTICLE_URL} target="_blank" rel="noopener noreferrer" className={`underline decoration-amber-400 underline-offset-4 hover:decoration-amber-700 ${focusRing}`}>
            Chrome for Developers「{ARTICLE_TITLE}」({ARTICLE_DATE})
          </a>
          。Chrome 以外のブラウザは対象外です。
        </span>
      </p>

      <div className="grid @min-[720px]:grid-cols-[minmax(0,1.08fr)_minmax(0,1fr)]">
        {/* 左: 12マスの表 */}
        <div className="min-w-0 px-4 pb-5 pt-4 sm:px-6 @min-[720px]:border-r @min-[720px]:border-stone-200">
          <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
            <h3 className="text-[14px] font-bold">見出し × 入力ルール</h3>
            <p className="text-[12.5px] text-stone-600">
              {total}通りのうち、弾かれるのは <strong className="font-display text-[15px] font-bold tabular-nums text-red-700">{rejectedCount}</strong> 通り
            </p>
          </div>
          <table className="mt-2 w-full table-fixed border-collapse text-left">
            <caption className="sr-only">見出し4種と入力ルール3種の組み合わせごとに、自動入力のあと送信できるかを再現した表です(矢印キーで移動できます)</caption>
            <colgroup>
              <col className="w-[27%] sm:w-[25%]" />
              <col />
              <col />
              <col />
            </colgroup>
            <thead>
              <tr>
                <th scope="col" className="pb-1.5 pr-2 align-bottom text-[11px] font-normal leading-tight text-stone-500">
                  見出し \ ルール
                </th>
                {RULES.map((r) => (
                  <th key={r.id} scope="col" className="px-1 pb-1.5 align-bottom text-[11.5px] font-bold leading-tight text-stone-700 sm:px-2 sm:text-[12.5px]">
                    {r.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {HEADINGS.map((h, i) => (
                <tr key={h}>
                  <th scope="row" className="border-t border-stone-200 py-2 pr-2 align-middle">
                    <span className="block text-[14px] font-bold leading-tight sm:text-[15px]">{h}</span>
                    <span className="mt-0.5 block whitespace-nowrap text-[10px] leading-tight text-stone-500 sm:text-[11px]">{SCRIPT_JA[scriptOf(h)]}で入る</span>
                  </th>
                  {RULES.map((r, j) => {
                    const d = verdict(h, r.id);
                    const on = sel.h === i && sel.r === j;
                    const after = afterCell?.h === i && afterCell.r === j;
                    const s = simulate(h, r.id, null);
                    return (
                      <td key={r.id} className="border-l border-t border-stone-200 p-0">
                        <button
                          type="button"
                          ref={(el) => {
                            cellRefs.current[i * 3 + j] = el;
                          }}
                          data-cell={`${i}-${j}`}
                          tabIndex={on ? 0 : -1}
                          aria-pressed={on}
                          aria-label={`見出し「${h}」×${r.label}: ${d ? "弾かれる" : "通る"}(${s.raw.family}が入る)`}
                          onClick={() => play({ h: i, r: j }, null)}
                          onKeyDown={(e) => onCellKey(e, i, j)}
                          className={`fn-cell relative block min-h-[3.9rem] w-full px-1.5 py-2 text-left transition-colors duration-100 sm:min-h-[4.25rem] sm:px-2.5 ${
                            d
                              ? "bg-[repeating-linear-gradient(135deg,#fef2f2_0_6px,#fee2e2_6px_8px)] hover:bg-[repeating-linear-gradient(135deg,#fee2e2_0_6px,#fecaca_6px_8px)]"
                              : "bg-white hover:bg-stone-50"
                          } ${focusRing}`}
                        >
                          <span className={`block whitespace-nowrap text-[12.5px] font-bold leading-tight sm:text-[14px] ${d ? "text-red-700" : "text-emerald-700"}`}>
                            <span aria-hidden="true">{d ? "✕ " : "○ "}</span>
                            {d ? "弾かれる" : "通る"}
                          </span>
                          <span className="mt-1 block text-[10.5px] leading-tight text-stone-600 sm:text-[11.5px]">{s.raw.family}</span>
                          {on && <span aria-hidden="true" className="pointer-events-none absolute inset-0 border-[3px] border-[#d97706]" />}
                          {after && !on && <span aria-hidden="true" className="pointer-events-none absolute inset-0 border-2 border-dashed border-[#d97706]" />}
                        </button>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
          <ul className="mt-3 space-y-1 text-[12.5px] leading-[1.75] text-stone-700">
            <li>
              <span className="font-display font-bold text-[#b45309]">1</span> 文字種は<strong>見出し</strong>で決まります。カタカナが1字でもあればカタカナ、なければひらがな。
            </li>
            <li>
              <span className="font-display font-bold text-[#b45309]">2</span> 弾かれるのは「カタカナのみ×カタカナの無い見出し」と「ひらがなのみ×カタカナのある見出し」の2つの向き。
            </li>
          </ul>
          <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-stone-200 pt-3">
            <button
              type="button"
              onClick={savePng}
              className={`save-png inline-flex min-h-11 items-center border border-stone-900 bg-stone-900 px-4 text-[13px] font-bold text-white transition-colors hover:bg-amber-800 ${focusRing}`}
            >
              表を画像で保存(1200×630)
            </button>
            <span className="text-[11.5px] text-stone-500">矢印キーでマスを移動できます。選んだマスに枠が付きます</span>
          </div>
          {png && (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={png} alt="12通りを通る・弾かれるで塗り分けた表の画像" width={1200} height={630} className="share-thumb mt-3 h-auto w-full max-w-[26rem] border border-stone-200" />
          )}
        </div>

        {/* 右: フォームの再現 */}
        <div className="min-w-0 border-t border-stone-200 px-4 pb-5 pt-4 sm:px-6 @min-[720px]:border-t-0">
          <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
            <h3 className="text-[14px] font-bold">再現: 架空の申込フォーム</h3>
            <ol className="flex gap-3 text-[11.5px]" aria-label="再現の進行状況">
              {STEP_LABELS.map((l, k) => (
                <li key={l} className={k === stepIdx ? "font-bold text-[#b45309]" : k < stepIdx ? "text-stone-700" : "text-stone-400"}>
                  <span className="font-display tabular-nums">{k + 1}</span> {l}
                </li>
              ))}
            </ol>
          </div>

          <form
            noValidate
            onSubmit={(e) => {
              e.preventDefault();
              play(sel, fix);
            }}
            className="fn-form relative mt-3 border border-stone-200 bg-stone-50 px-3 pb-4 pt-3 sm:px-4"
            aria-describedby={`${uid}-res`}
          >
            <p className="text-[11px] text-stone-500">
              入力ルール: <strong className="font-bold text-stone-700">{rule.label}</strong>
              <span className="ml-2 inline-block whitespace-nowrap font-mono text-[10.5px] text-stone-400">pattern=&quot;{rule.pattern}&quot;</span>
            </p>
            <div className="mt-2 grid grid-cols-[5.6rem_minmax(0,1fr)_minmax(0,1fr)] items-center gap-x-2 gap-y-2 sm:grid-cols-[7rem_minmax(0,1fr)_minmax(0,1fr)]">
              <span className="text-[12.5px] font-bold">氏名</span>
              <div className="relative">
                <input
                  readOnly
                  aria-label="姓"
                  value={shown ? PERSON.family : ""}
                  className={`h-10 w-full border px-2 text-[16px] ${stage === 1 ? "border-[#1a73e8] outline outline-1 outline-[#1a73e8]" : "border-stone-300"} ${shown ? "bg-[#e8f0fe]" : "bg-white"}`}
                />
                {stage === 1 && (
                  <div className="fn-suggest absolute left-0 top-full z-10 mt-1 w-[15rem] max-w-[calc(100vw-3rem)] border border-stone-200 bg-white py-1 text-[12.5px] shadow-[0_6px_20px_rgba(0,0,0,0.18)]" aria-hidden="true">
                    <div className="bg-stone-100 px-3 py-1.5">
                      <span className="block font-bold">山田 花子</span>
                      <span className="block text-[11px] text-stone-500">ふりがな: やまだ はなこ(保存済み)</span>
                    </div>
                    <div className="px-3 py-1 text-[11px] text-stone-400">自動入力の候補(再現)</div>
                  </div>
                )}
              </div>
              <input readOnly aria-label="名" value={shown ? PERSON.given : ""} className={`h-10 w-full border border-stone-300 px-2 text-[16px] ${shown ? "bg-[#e8f0fe]" : "bg-white"}`} />

              <span className="text-[12.5px] font-bold leading-tight">
                <span className={fix === "label" && dir ? "bg-amber-100 px-0.5 text-amber-950" : ""}>{readLabel}</span>
                <span className="block text-[10.5px] font-normal text-stone-500">見出し(label)</span>
              </span>
              {(["family", "given"] as const).map((k) => (
                <input
                  key={k}
                  readOnly
                  aria-label={`${readLabel}(${k === "family" ? "姓" : "名"})`}
                  aria-invalid={invalid || undefined}
                  name={`${k}-name-phonetic`}
                  value={shown ? values[k] : ""}
                  className={`fn-kana h-10 w-full border px-2 text-[16px] transition-colors duration-150 ${
                    invalid ? "border-red-600 bg-red-50 text-red-900" : stage === 3 ? "border-[#d97706] bg-amber-50" : shown ? "border-stone-300 bg-[#e8f0fe]" : "border-stone-300 bg-white"
                  }`}
                />
              ))}
            </div>
            <p className={`mt-1.5 min-h-[1.4em] pl-[5.6rem] text-[12px] sm:pl-[7rem] ${invalid ? "font-bold text-red-700" : "text-stone-500"}`}>
              {invalid ? `${rule.hint}(${values.family} ${values.given} は不可)` : stage === 3 ? `案2: ${SCRIPT_JA[sim.filled]}を${SCRIPT_JA[dir === "needKata" ? "kata" : "hira"]}へ変換しました` : rule.hint}
            </p>
            <div className="mt-2 flex flex-wrap items-center gap-3">
              <button type="submit" className={`fn-submit inline-flex min-h-11 items-center border border-stone-900 bg-white px-5 text-[13.5px] font-bold transition-colors hover:bg-stone-900 hover:text-white ${focusRing}`}>
                送信する(再現)
              </button>
              <p id={`${uid}-res`} role="status" className="fn-result min-h-[1.5em] text-[13.5px] font-bold">
                {submitted ? (
                  sim.ok ? (
                    <span className="text-emerald-700">✓ 送信できました{fix ? `(案${fix === "label" ? 1 : 2}で直して通過)` : ""}</span>
                  ) : (
                    <span className="text-red-700">✕ 送信できません。お客様が打ち直すことになります</span>
                  )
                ) : (
                  <span className="font-normal text-stone-500">{stage === 1 ? "保存済みの候補を選んでいます…" : "自動入力しました。送信します…"}</span>
                )}
              </p>
            </div>
            <p className="mt-2 text-[11px] leading-[1.6] text-stone-500">
              欄の識別: name=&quot;family-name-phonetic&quot; / autocomplete=&quot;family-name&quot;(記事の手がかり)。入る文字種は見出しで決まります。
            </p>
          </form>

          {/* 直し方 */}
          <div className="mt-4">
            <h3 className="text-[14px] font-bold">{dir ? "直し方(どちらか一方で通ります)" : "このマスは直す必要がありません"}</h3>
            {dir ? (
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                {(["label", "convert"] as const).map((f, k) => (
                  <button
                    key={f}
                    type="button"
                    aria-pressed={fix === f}
                    onClick={() => play(sel, fix === f ? null : f)}
                    className={`fix-${f} block min-h-11 border px-3 py-2.5 text-left transition-colors duration-100 ${
                      fix === f ? "border-[#d97706] bg-amber-50" : "border-stone-300 bg-white hover:border-stone-500"
                    } ${focusRing}`}
                  >
                    <span className="block text-[13px] font-bold">
                      <span className="font-display text-[#b45309]">案{k + 1}</span>{" "}
                      {f === "label" ? `見出しを「${fixedHeading(dir)}」に変える` : `確定後に${dir === "needKata" ? "全角カタカナ" : "ひらがな"}へ変換する`}
                    </span>
                    <span className="mt-0.5 block text-[11.5px] leading-[1.6] text-stone-600">
                      {f === "label"
                        ? dir === "needKata"
                          ? "カタカナを1字でも含めると、自動入力がカタカナで入ります"
                          : "カタカナを含めなければ、自動入力がひらがなで入ります"
                        : "変換中の文字には触らず、確定・自動入力のあとに直します(下のコード)"}
                    </span>
                    <span className="mt-1 block text-[11px] font-bold text-stone-500">{fix === f ? "適用中。もう一度押すと元に戻します" : "押すと適用して再送信"}</span>
                  </button>
                ))}
              </div>
            ) : (
              <p className="mt-1.5 text-[12.5px] leading-[1.75] text-stone-600">
                {rule.id === "any"
                  ? "どちらの文字でも受け付けるので、見出しを変えても通ります。片方に絞るときは見出しの文字種と合わせてください。"
                  : `見出しを${sim.filled === "kata" ? "「ふりがな」「よみがな」のようなカタカナの無い書き方" : "「フリガナ」「カナ」のようなカタカナのある書き方"}に変えると弾かれます。`}
              </p>
            )}
            <div className="mt-3 border-t border-stone-200 pt-2">
              <div className="flex items-center justify-between gap-3">
                <p className="text-[12.5px] font-bold">案2のコード(外部ライブラリなし)</p>
                <button type="button" onClick={() => copy("code")} className={`copy-code inline-flex shrink-0 whitespace-nowrap min-h-11 items-center px-2 text-[12.5px] font-bold text-stone-700 underline decoration-stone-300 underline-offset-4 hover:decoration-[#d97706] ${focusRing}`}>
                  {copied === "code" ? "コピーしました" : copied === "code-ng" ? "選択しました。⌘C / Ctrl+C で" : "コードをコピー"}
                </button>
              </div>
              <pre ref={codeRef} className="mt-1 max-h-[15rem] overflow-auto border border-stone-200 bg-stone-50 p-3 font-mono text-[11.5px] leading-[1.6] text-stone-800">
                {code}
              </pre>
            </div>
          </div>
        </div>
      </div>

      {/* 確認メモ */}
      <div className="border-t border-stone-200 px-4 pb-5 pt-4 sm:px-6">
        <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
          <h3 className="text-[14px] font-bold">制作担当へ送る確認メモ</h3>
          <p className="text-[11.5px] text-stone-500">技術に詳しくなくても、そのまま貼って送れます</p>
        </div>
        <textarea
          ref={memoRef}
          readOnly
          value={memo}
          aria-label="確認メモ"
          rows={8}
          className="fn-memo mt-2 block h-[13rem] w-full resize-none border border-stone-300 bg-white p-3 text-[13px] leading-[1.75] text-stone-800 sm:h-[11.5rem]"
        />
        <div className="mt-2 flex flex-wrap items-center gap-3">
          <button
            type="button"
            onClick={() => copy("memo")}
            className={`copy-memo inline-flex min-h-11 items-center border border-[#d97706] bg-amber-50 px-4 text-[13px] font-bold text-amber-950 transition-colors hover:bg-amber-100 ${focusRing}`}
          >
            {copied === "memo" ? "コピーしました" : "確認メモをコピー"}
          </button>
          {copied === "memo-ng" && <span className="text-[12px] text-stone-600">コピーできませんでした。文字列を選択した状態にしたので、⌘C / Ctrl+C でコピーしてください</span>}
        </div>
      </div>

      {/* 詳しい人向け */}
      <details className="fn-details group border-t border-stone-200 px-4 py-3 sm:px-6">
        <summary className={`fn-summary flex min-h-11 cursor-pointer list-none items-center gap-2 text-[13.5px] font-bold [&::-webkit-details-marker]:hidden ${focusRing}`}>
          <span aria-hidden="true" className="inline-block w-3 text-[#b45309] transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none">
            ▸
          </span>
          詳しい人向け: フォームのHTMLを貼って判定する
        </summary>
        <div className="pb-2 pt-1">
          <p className="text-[12px] leading-[1.75] text-stone-600">
            手がかりは記事の順に見ます: autocomplete(標準の値だけ・最優先)→ name 属性 → 見出し(label)。非標準の autocomplete は「補完されない見込み」、どれにも当たらない欄は「記事の範囲では識別できません」とします。
            貼ったHTMLはこの端末の中で読むだけで、送信・保存・script の実行はしません。
          </p>
          <label htmlFor={`${uid}-html`} className="mt-2 block text-[12px] font-bold">
            フォームのHTML({MAX_HTML.toLocaleString()}文字まで)
          </label>
          <textarea
            id={`${uid}-html`}
            value={html}
            onChange={(e) => setHtml(e.target.value)}
            spellCheck={false}
            placeholder={'<label for="kana">フリガナ</label>\n<input id="kana" name="family-name-phonetic" autocomplete="family-name">'}
            className="fn-html mt-1 block h-36 w-full resize-y border border-stone-300 p-2 font-mono text-[16px] leading-[1.5] sm:text-[12.5px]"
          />
          <div className="mt-2 flex flex-wrap gap-3">
            <button type="button" onClick={() => setHtml(SAMPLE_HTML)} className={`fill-sample inline-flex min-h-11 items-center border border-stone-300 px-3 text-[12.5px] font-bold hover:border-stone-500 ${focusRing}`}>
              見本のHTMLを入れる
            </button>
            {html && (
              <button type="button" onClick={() => setHtml("")} className={`inline-flex min-h-11 items-center px-2 text-[12.5px] text-stone-600 underline decoration-stone-300 underline-offset-4 ${focusRing}`}>
                消す
              </button>
            )}
          </div>
          {html.trim() && (
            <div className="mt-3">
              {judged.length === 0 ? (
                <p className="text-[12.5px] text-stone-600">文字を入れる欄(input・textarea)が見つかりませんでした。</p>
              ) : (
                <ul className="fn-judge border-t border-stone-200 text-[12px] leading-[1.6]" aria-label="欄ごとの判定">
                  {judged.map((r, k) => (
                    <li key={k} className="grid gap-x-4 gap-y-0.5 border-b border-stone-200 py-2 @min-[640px]:grid-cols-[11rem_minmax(0,1fr)]">
                      <div>
                        <span className="block break-all font-mono text-[11.5px] text-stone-500">{r.field}</span>
                        <span className={`block text-[13px] font-bold ${r.bad ? "text-red-700" : r.kind === "phonetic" ? "text-emerald-800" : "text-stone-800"}`}>{r.title}</span>
                      </div>
                      <div className="text-stone-600">
                        <p><span className="text-stone-400">手がかり: </span>{r.basis}</p>
                        {r.script && (
                          <p>
                            <span className="text-stone-400">入力できる文字: </span>
                            <strong className="font-bold text-stone-800">{SCRIPT_JA[r.script]}</strong>
                            <span className="text-stone-400"> pattern: </span>
                            <span className={r.bad ? "font-bold text-red-700" : ""}>{r.check}</span>
                          </p>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          )}
        </div>
      </details>

      {/* 本体への導線と関連 */}
      <div className="grid border-t border-stone-200 sm:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]">
        <div className="px-4 py-4 sm:px-6">
          <p className="text-[13.5px] font-bold">フォームの離脱を減らしたい</p>
          <p className="mt-1 text-[12.5px] leading-[1.75] text-stone-600">自動入力で止まる欄・エラーの出し方・項目の削り方まで、お問い合わせフォームの改善を相談できます。</p>
          <a
            href={CONTACT_URL}
            className={`mt-2 inline-flex min-h-11 items-center border border-stone-900 bg-stone-900 px-4 text-[13px] font-bold text-white transition-colors hover:bg-amber-800 ${focusRing}`}
          >
            フォーム改善を相談する
          </a>
        </div>
        <nav aria-label="フォーム関連の制作事例" className="border-t border-stone-200 px-4 py-4 sm:border-l sm:border-t-0 sm:px-6">
          <p className="text-[13.5px] font-bold">フォーム関連の制作事例</p>
          <ul className="mt-1">
            {[
              { slug: "contact-form-block", code: "BLK-12", name: "お問い合わせフォームセクション", note: "入力と送信の基本形" },
              { slug: "jp-address-autofill", code: "BLK-106", name: "郵便番号から住所を自動入力するフォーム", note: "入力済みの番地を消さない" },
            ].map((l) => (
              <li key={l.slug} className="border-t border-stone-100 first:border-0">
                <a href={`/d/${l.slug}`} className={`group block py-2 ${focusRing}`}>
                  <span className="font-display text-[10.5px] font-semibold tracking-[0.14em] text-stone-400">{l.code}</span>
                  <span className="block text-[13.5px] font-bold underline decoration-stone-300 underline-offset-4 group-hover:decoration-[#d97706]">{l.name}</span>
                  <span className="block text-[11.5px] text-stone-500">{l.note}</span>
                </a>
              </li>
            ))}
          </ul>
        </nav>
      </div>
      <p className="sr-only" aria-live="polite">
        {msg}
      </p>
    </section>
  );
}

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

npx shadcn@latest add https://designs.first-ch.com/r/furigana-name-fields.json