TYP-06Typography

Fix a One-Character Orphan in a Heading Across 7 Phone Widths | Phrase Line Breaks with inline-block and nowrap

A tool for the one- or two-character orphan at the end of a Japanese heading: it lays out the same heading at seven common phone widths (360, 375, 390, 393, 412, 414 and 430 px) at one shared scale, with the fixed version next to each width. Each frame is laid out at its real width and then scaled down by the same factor. The text is set in the fonts installed in the browser you are using, so on a device with different default fonts (Windows, iPhone, Android) character widths and line breaks can differ. Frames whose last line holds only one or two characters get a label, an amber border and a box around the fallen characters. Tap between two characters (or use the arrow keys and Enter) to add a break, and the seven fixed frames re-flow instantly. The fix is plain HTML and CSS: each phrase is wrapped in a span with display:inline-block and white-space:nowrap inside a heading with lang="ja", ready to copy. Phrases wider than the content box are flagged as not fitting. Side padding, font size, weight and the device's default gothic or mincho font are adjustable; a 1200×630 PNG of all 14 frames can be saved, and the share link writes the text and settings after the # only when you press the button. No dependencies and no server processing. Sample headings are fictional.

Preview

TYP-06

見出しの1文字落ちをスマホ7台で比べて直す

直す前
0/7台
直した後
0/7台

このブラウザ・この設定での表示です。枠の幅は端末の画面幅(CSS px)、左右の余白 20px、縮尺 75%(7台とも同じ)

文字と文字の間を押すと、区切りが入りますキーボードは ← → で移動、Enter で入れる・外す

まとまり: はじめての方も|安心して|ご相談ください

直す前そのままの文

直した後まとまり 3つを nowrap で包む

  1. 430px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  2. 414px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  3. 412px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  4. 393px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  5. 390px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  6. 375px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

  7. 360px

    直す前

    はじめての方も安心してご相談ください

    直した後

    はじめての方も安心してご相談ください

20px
22px
太さ
フォント

見出しの位置に h2 を、style の中身を CSS に貼ります。まとまりが内幅より長いと、その幅でははみ出します(上の枠に「収まりません」と出ます)。

リンクを開いた人には原稿が見えます

1〜2文字が落ちるかどうかは、端末の幅・余白・文字サイズ・フォントで変わります。同じ見出しでも、制作者の画面では1行に収まり、発注者のスマホでは落ちることがあります。幅は代表的な7つだけを見ています。仕様は CSS Text Module Level 3(white-space)。
Share on X

Read the full description

A tool for the one- or two-character orphan at the end of a Japanese heading: it lays out the same heading at seven common phone widths (360, 375, 390, 393, 412, 414 and 430 px) at one shared scale, with the fixed version next to each width. Each frame is laid out at its real width and then scaled down by the same factor. The text is set in the fonts installed in the browser you are using, so on a device with different default fonts (Windows, iPhone, Android) character widths and line breaks can differ. Frames whose last line holds only one or two characters get a label, an amber border and a box around the fallen characters. Tap between two characters (or use the arrow keys and Enter) to add a break, and the seven fixed frames re-flow instantly. The fix is plain HTML and CSS: each phrase is wrapped in a span with display:inline-block and white-space:nowrap inside a heading with lang="ja", ready to copy. Phrases wider than the content box are flagged as not fitting. Side padding, font size, weight and the device's default gothic or mincho font are adjustable; a 1200×630 PNG of all 14 frames can be saved, and the share link writes the text and settings after the # only when you press the button. No dependencies and no server processing. Sample headings are fictional.

Added:
2026-11-09
Dependencies:
None
tags
#typography #japanese #heading #line-break #orphan #inline-block #white-space-nowrap #responsive #mobile #comparison #generator #canvas-export #keyboard #no-dependency #no-image
"use client";

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

/**
 * 見出しの1文字落ちを、よくある7つのスマホ幅で「直す前/直した後」に並べて比べる道具
 *
 * 差別化: 既存の見出しタイポ(scroll-reveal-editorial・text-swap-tabs・watermark-heading-section・section-heading・
 * typed-glitch-header・wind-blown-text・yakumono-spacing-compare・tategaki-scroll-reading)は1つの幅で見た目・動き・約物を扱う。
 * 本ブロックは同じ見出しを7つの幅で同じ縮尺に組んで、最終行に1〜2文字だけ落ちる幅を札で示し、文字の間を押して入れた区切りで
 * 直した後の7台をその場で組み直す比較表が主役。英字の小見出し・見出しの「。」止め・末尾の矢印リンク・角丸・出現アニメは使わない。
 *
 * 汎用技法メモ:
 * 1. 端末の幅ごとの折り返しは、枠を実寸(幅=端末の幅)で組んでから transform: scale で縮めて並べる。縮めても行の分かれ方は
 *    実寸のまま変わらない。測った矩形は getBoundingClientRect().width / offsetWidth で割り戻して実寸の座標にする。
 * 2. 行の判定は TreeWalker で文字ノードを走り、Range を1文字ずつ当てて getClientRects の top が前の字より半字以上下がったら次の行。
 * 3. 直し方は、まとまりごとに display:inline-block と white-space:nowrap の span で包むだけ。まとまりの途中では折り返さず、
 *    まとまりが内幅より長いときだけはみ出す(その幅には「収まりません」を出す)。lang="ja" を付けて和文の禁則で組ませる。
 */

const PAGE_URL = "https://designs.first-ch.com/d/phrase-break-heading";
const WIDTHS = [360, 375, 390, 393, 412, 414, 430] as const;
/** 表示は広い順(落ちやすい広めの幅が上に来る) */
const ORDER = WIDTHS.map((_, i) => WIDTHS.length - 1 - i);
const MAX_LEN = 40;
const focusRing =
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]";

type FontId = "sans" | "serif";
type Weight = 400 | 700;
type Settings = {
  text: string;
  breaks: number[];
  pad: number;
  size: number;
  weight: Weight;
  font: FontId;
};

const FONTS: Record<FontId, { label: string; stack: string }> = {
  sans: {
    label: "端末の標準ゴシック",
    stack:
      '"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Noto Sans JP", "Noto Sans CJK JP", "Yu Gothic", Meiryo, sans-serif',
  },
  serif: {
    label: "端末の明朝",
    stack:
      '"Hiragino Mincho ProN", "Yu Mincho", YuMincho, "Noto Serif JP", "Noto Serif CJK JP", serif',
  },
};

/** 例文(架空の見本)。区切りの位置はまとまりの切れ目 */
const EXAMPLES: { label: string; phrases: string[] }[] = [
  { label: "歯科の見出し", phrases: ["はじめての方も", "安心して", "ご相談ください"] },
  { label: "診療時間", phrases: ["土曜日も", "夕方6時まで", "診療しています"] },
  { label: "採用", phrases: ["未経験から", "始められる", "受付スタッフを", "募集しています"] },
];

const fromPhrases = (phrases: string[]) => {
  const breaks: number[] = [];
  let i = 0;
  for (const p of phrases.slice(0, -1)) {
    i += Array.from(p).length;
    breaks.push(i);
  }
  return { text: phrases.join(""), breaks };
};

const DEFAULTS: Settings = {
  ...fromPhrases(EXAMPLES[0].phrases),
  pad: 20,
  size: 22,
  weight: 700,
  font: "sans",
};
const PAD = { min: 8, max: 32 };
const SIZE = { min: 16, max: 40 };

/** 入力をそろえる(改行は詰め、40字まで) */
export function normalizeText(text: string) {
  return Array.from(text.replace(/[\r\n\t]+/g, "").trim()).slice(0, MAX_LEN).join("");
}

/** 区切りの位置(i 文字目の前)でまとまりに分ける */
export function phrasesOf(text: string, breaks: number[]) {
  const chars = Array.from(text);
  const cuts = [...new Set(breaks)].filter((b) => b > 0 && b < chars.length).sort((a, b) => a - b);
  const out: string[] = [];
  let prev = 0;
  for (const c of [...cuts, chars.length]) {
    out.push(chars.slice(prev, c).join(""));
    prev = c;
  }
  return out.filter((p) => p.length > 0);
}

/** 原稿を直したとき、変わっていない前後の区切りだけを残して位置をずらす */
export function remapBreaks(oldText: string, newText: string, breaks: number[]) {
  const a = Array.from(oldText);
  const b = Array.from(newText);
  let pre = 0;
  while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
  let suf = 0;
  while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
  const delta = b.length - a.length;
  const out: number[] = [];
  for (const x of breaks) {
    if (x <= pre) out.push(x);
    else if (x >= a.length - suf) out.push(x + delta);
  }
  return [...new Set(out)].filter((x) => x > 0 && x < b.length).sort((p, q) => p - q);
}

/** 最終行が1〜2文字だけなら、その文字(空白は数えない) */
export function orphanOf(lines: string[]) {
  if (lines.length < 2) return null;
  const last = Array.from(lines[lines.length - 1].replace(/\s/g, ""));
  return last.length > 0 && last.length <= 2 ? last.join("") : null;
}

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

/** 直した後の HTML と CSS(貼ればこのページの「直した後」と同じ組みになる) */
export function buildOutput({
  phrases,
  size,
  weight,
  font,
}: {
  phrases: string[];
  size: number;
  weight: Weight;
  font: FontId;
}) {
  const html = `<h2 class="pb-heading" lang="ja">${phrases
    .map((p) => `<span class="pb">${esc(p)}</span>`)
    .join("")}</h2>`;
  const css = [
    ".pb-heading {",
    `  font-family: ${FONTS[font].stack};`,
    `  font-size: ${size}px;`,
    `  font-weight: ${weight};`,
    "  line-height: 1.5;",
    "}",
    "/* まとまりの途中では折り返さない */",
    ".pb {",
    "  display: inline-block;",
    "  white-space: nowrap;",
    "}",
  ].join("\n");
  return `${html}\n\n<style>\n${css}\n</style>`;
}

/** 共有リンクの # 以降(押したときだけ作る) */
export function encodeShare(s: Settings) {
  const p = new URLSearchParams();
  p.set("t", s.text);
  p.set("b", s.breaks.join("."));
  p.set("p", String(s.pad));
  p.set("s", String(s.size));
  p.set("w", String(s.weight));
  p.set("f", s.font);
  return p.toString();
}

export function decodeShare(hash: string): Settings | null {
  const p = new URLSearchParams(hash.replace(/^#/, ""));
  const raw = p.get("t");
  if (!raw) return null;
  const text = normalizeText(raw);
  if (!text) return null;
  const len = Array.from(text).length;
  const num = (k: string, lo: number, hi: number, d: number) => {
    const v = Number(p.get(k));
    return Number.isFinite(v) && p.get(k) !== "" ? Math.min(hi, Math.max(lo, Math.round(v))) : d;
  };
  const breaks = [...new Set((p.get("b") ?? "").split(".").map(Number))]
    .filter((x) => Number.isInteger(x) && x > 0 && x < len)
    .sort((a, b) => a - b);
  return {
    text,
    breaks,
    pad: num("p", PAD.min, PAD.max, DEFAULTS.pad),
    size: num("s", SIZE.min, SIZE.max, DEFAULTS.size),
    weight: p.get("w") === "400" ? 400 : 700,
    font: p.get("f") === "serif" ? "serif" : "sans",
  };
}

/* ───────── 実測 ───────── */

type Box = { ch: string; x: number; y: number; w: number; h: number };
type Measure = {
  lines: string[];
  orphan: string | null;
  orphanBoxes: Box[];
  overflow: string | null;
  height: number;
};

/** 枠の中の見出しを1文字ずつ測り、行に分ける(座標は枠の実寸) */
function measure(frame: HTMLElement, heading: HTMLElement, fs: number, inner: number): Measure {
  const fr = frame.getBoundingClientRect();
  const k = fr.width / frame.offsetWidth || 1;
  const boxes: Box[] = [];
  const walker = document.createTreeWalker(heading, NodeFilter.SHOW_TEXT);
  const range = document.createRange();
  for (let n = walker.nextNode(); n; n = walker.nextNode()) {
    const t = n.textContent ?? "";
    let i = 0;
    for (const ch of Array.from(t)) {
      range.setStart(n, i);
      range.setEnd(n, i + ch.length);
      i += ch.length;
      const r = range.getClientRects()[0];
      if (!r) continue;
      boxes.push({ ch, x: (r.left - fr.left) / k, y: (r.top - fr.top) / k, w: r.width / k, h: r.height / k });
    }
  }
  const lineIdx: number[] = [];
  const lines: string[] = [];
  let top = -Infinity;
  for (const b of boxes) {
    if (b.y > top + fs * 0.5) {
      lines.push("");
      top = b.y;
    }
    lines[lines.length - 1] += b.ch;
    lineIdx.push(lines.length - 1);
  }
  const orphan = orphanOf(lines);
  const orphanBoxes = orphan ? boxes.filter((_, i) => lineIdx[i] === lines.length - 1 && /\S/.test(boxes[i].ch)) : [];
  let overflow: string | null = null;
  for (const el of Array.from(heading.querySelectorAll<HTMLElement>("[data-phrase]"))) {
    if (el.getBoundingClientRect().width / k > inner + 0.5) {
      overflow = el.textContent;
      break;
    }
  }
  return { lines, orphan, orphanBoxes, overflow, height: frame.offsetHeight };
}

const sameMeasure = (a: Measure[] | null, b: Measure[]) =>
  !!a &&
  a.length === b.length &&
  a.every(
    (m, i) =>
      m.lines.join("\n") === b[i].lines.join("\n") &&
      m.overflow === b[i].overflow &&
      m.height === b[i].height &&
      m.orphanBoxes.map((x) => `${x.x.toFixed(1)},${x.y.toFixed(1)}`).join() ===
        b[i].orphanBoxes.map((x) => `${x.x.toFixed(1)},${x.y.toFixed(1)}`).join(),
  );

const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

type Row = "before" | "after";
type CopyState = "ok" | "fail" | null;

export default function PhraseBreakHeading({
  headingTag: Heading = "h2",
}: {
  headingTag?: "h1" | "h2" | "p";
}) {
  const uid = useId();
  const [s, setS] = useState<Settings>(DEFAULTS);
  const [draft, setDraft] = useState(DEFAULTS.text);
  const [fit, setFit] = useState(true);
  const [scale, setScale] = useState(0.75);
  const [res, setRes] = useState<Record<Row, Measure[]> | null>(null);
  const [focusGap, setFocusGap] = useState(0);
  const [live, setLive] = useState("");
  const [copied, setCopied] = useState<{ state: CopyState; text: string } | null>(null);
  const [share, setShare] = useState<{ state: CopyState; url: string } | null>(null);
  const [saved, setSaved] = useState<"ok" | "fail" | null>(null);
  const [tick, setTick] = useState(0);

  const boardRef = useRef<HTMLDivElement>(null);
  const cellRef = useRef<HTMLDivElement>(null);
  const frameRefs = useRef<Record<Row, (HTMLDivElement | null)[]>>({ before: [], after: [] });
  const headRefs = useRef<Record<Row, (HTMLElement | null)[]>>({ before: [], after: [] });
  const gapRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const outRef = useRef<HTMLTextAreaElement>(null);
  const linkRef = useRef<HTMLInputElement>(null);
  const prevBreaks = useRef(s.breaks.join("."));
  const resRef = useRef<Record<Row, Measure[]> | null>(null);

  const chars = useMemo(() => Array.from(s.text), [s.text]);
  const phrases = useMemo(() => phrasesOf(s.text, s.breaks), [s.text, s.breaks]);
  const hasBreaks = phrases.length > 1;
  const output = useMemo(
    () => buildOutput({ phrases, size: s.size, weight: s.weight, font: s.font }),
    [phrases, s.size, s.weight, s.font],
  );
  const fontStack = FONTS[s.font].stack;
  const headStyle = {
    fontFamily: fontStack,
    fontSize: `${s.size}px`,
    fontWeight: s.weight,
    lineHeight: 1.5,
  } as const;
  const k = fit ? scale : 1;

  // 共有リンクで開いたら、原稿と設定を読んで比較を最初に見せる
  useEffect(() => {
    const apply = (scroll: boolean) => {
      const got = decodeShare(window.location.hash);
      if (!got) return;
      setS(got);
      setDraft(got.text);
      if (scroll)
        requestAnimationFrame(() =>
          boardRef.current?.scrollIntoView({ block: "start", behavior: reducedMotion() ? "auto" : "smooth" }),
        );
    };
    apply(true);
    const onHash = () => apply(true);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // 縮尺: 一番広い 430px の枠が、比較の1マスに収まる倍率(7台とも同じ倍率)
  useLayoutEffect(() => {
    const el = cellRef.current;
    if (!el) return;
    const calc = () => setScale(Math.max(0.3, Math.min(1, el.clientWidth / WIDTHS[WIDTHS.length - 1])));
    calc();
    const ro = new ResizeObserver(calc);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  // Web フォントの差し替えで幅が変わったら測り直す
  useEffect(() => {
    const f = document.fonts;
    if (!f) return;
    const bump = () => setTick((t) => t + 1);
    f.ready.then(bump);
    f.addEventListener("loadingdone", bump);
    return () => f.removeEventListener("loadingdone", bump);
  }, []);

  // 14台を実測(描画と同じフレームで札を出す)
  useLayoutEffect(() => {
    const inner = (w: number) => w - s.pad * 2;
    const next = {} as Record<Row, Measure[]>;
    for (const row of ["before", "after"] as Row[]) {
      next[row] = WIDTHS.map((w, i) => {
        const fr = frameRefs.current[row][i];
        const hd = headRefs.current[row][i];
        return fr && hd ? measure(fr, hd, s.size, inner(w)) : { lines: [], orphan: null, orphanBoxes: [], overflow: null, height: 0 };
      });
    }
    const prev = resRef.current;
    if (prev && sameMeasure(prev.before, next.before) && sameMeasure(prev.after, next.after)) return;
    resRef.current = next;
    setRes(next);
  }, [s, k, tick]);

  // 区切りが変わったら、直した後の7台を組み直す動き(動きを減らす設定では出さない)
  useEffect(() => {
    const key = s.breaks.join(".");
    if (key === prevBreaks.current) return;
    prevBreaks.current = key;
    if (reducedMotion()) return;
    for (const el of headRefs.current.after) {
      el?.animate(
        [
          { opacity: 0.35, transform: "translateY(3px)" },
          { opacity: 1, transform: "none" },
        ],
        { duration: 220, easing: "cubic-bezier(.2,.7,.2,1)" },
      );
    }
  }, [s.breaks]);

  const count = (row: Row) => (res ? res[row].filter((m) => m.orphan).length : 0);
  const afterBad = res ? res.after.filter((m) => m.orphan || m.overflow).length : 0;

  const toggleGap = useCallback(
    (i: number) => {
      const pos = i + 1;
      const on = s.breaks.includes(pos);
      const breaks = on ? s.breaks.filter((b) => b !== pos) : [...s.breaks, pos].sort((a, b) => a - b);
      setS((x) => ({ ...x, breaks }));
      setFocusGap(i);
      setLive(
        `「${chars[i]}」と「${chars[i + 1]}」の間の区切りを${on ? "外しました" : "入れました"}。まとまり ${phrasesOf(s.text, breaks).length}つ`,
      );
    },
    [s.breaks, s.text, chars],
  );

  const onGapKey = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {
    const last = chars.length - 2;
    let j = -1;
    if (e.key === "ArrowRight" || e.key === "ArrowDown") j = Math.min(last, i + 1);
    else if (e.key === "ArrowLeft" || e.key === "ArrowUp") j = Math.max(0, i - 1);
    else if (e.key === "Home") j = 0;
    else if (e.key === "End") j = last;
    if (j < 0) return;
    e.preventDefault();
    setFocusGap(j);
    gapRefs.current[j]?.focus();
  };

  const commitText = (raw: string) => {
    setDraft(raw);
    const text = normalizeText(raw);
    if (!text || text === s.text) return;
    setS((x) => ({ ...x, text, breaks: remapBreaks(x.text, text, x.breaks) }));
    setFocusGap(0);
  };

  const pickExample = (phrases: string[]) => {
    const v = fromPhrases(phrases);
    setS((x) => ({ ...x, ...v }));
    setDraft(v.text);
    setFocusGap(0);
    setLive(`例文「${v.text}」に替えました`);
  };

  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(output);
      setCopied({ state: "ok", text: output });
    } catch {
      outRef.current?.focus();
      outRef.current?.select();
      setCopied({ state: "fail", text: output });
    }
  };

  const makeShare = async () => {
    const url = `${PAGE_URL}#${encodeShare(s)}`;
    try {
      await navigator.clipboard.writeText(url);
      setShare({ state: "ok", url });
    } catch {
      setShare({ state: "fail", url });
      requestAnimationFrame(() => linkRef.current?.select());
    }
  };

  const saveImage = async () => {
    if (!res) return;
    try {
      await document.fonts?.ready;
      const url = drawComparison({ s, phrases, res, fontStack });
      const a = document.createElement("a");
      a.href = url;
      a.download = "phrase-break-compare.png";
      document.body.appendChild(a);
      a.click();
      a.remove();
      setSaved("ok");
    } catch {
      setSaved("fail");
    }
  };

  const copyState = copied && copied.text === output ? copied.state : null;
  const shareUrlNow = `${PAGE_URL}#${encodeShare(s)}`;
  const shareState = share && share.url === shareUrlNow ? share.state : null;
  const firstOrphan = res?.before.find((m) => m.orphan)?.orphan;

  const frameCell = (row: Row, w: number, i: number) => {
    const m = res?.[row][i];
    const plain = row === "before" || !hasBreaks;
    const idle = row === "after" && !hasBreaks;
    const bad = !idle && !!m?.orphan;
    const over = row === "after" && hasBreaks && !!m?.overflow;
    return (
      <div ref={row === "before" && i === ORDER[0] ? cellRef : undefined} className="min-w-0">
        <div className="mb-1 flex min-h-5 max-w-full items-baseline gap-2 text-[11.5px] leading-[1.35]" style={{ width: w * k }}>
          <span className="font-bold text-stone-500 @xl:hidden">{row === "before" ? "直す前" : "直した後"}</span>
          <span
            className={`badge ml-auto text-right font-bold ${
              over ? "text-red-700" : bad ? "text-amber-800" : "font-normal text-stone-400"
            }`}
          >
            {over ? (
              <>この幅では「{m?.overflow}」が収まりません</>
            ) : bad ? (
              <>
                この幅だけ「{m?.orphan}」が{Array.from(m?.orphan ?? "").length}文字
              </>
            ) : idle ? (
              "区切りなし"
            ) : m ? (
              `${m.lines.length}行`
            ) : null}
          </span>
        </div>
        <div className={`relative overflow-hidden ${idle ? "opacity-45" : ""}`} style={{ width: w * k, height: m?.height ? m.height * k : undefined }}>
          <div
            ref={(el) => {
              frameRefs.current[row][i] = el;
            }}
            className={`relative origin-top-left border bg-white ${
              over ? "border-red-500" : bad ? "border-[#d97706]" : "border-stone-300"
            }`}
            style={{ width: w, transform: k === 1 ? undefined : `scale(${k})` }}
          >
            <div aria-hidden className="mx-auto mt-1.5 h-[5px] w-14 bg-stone-200" />
            <div style={{ padding: `${Math.round(s.size * 0.5)}px ${s.pad}px ${Math.round(s.size * 0.6)}px` }}>
              <p
                ref={(el) => {
                  headRefs.current[row][i] = el;
                }}
                lang="ja"
                className="m-0 text-stone-900"
                style={headStyle}
              >
                {plain
                  ? s.text
                  : phrases.map((p, j) => (
                      <span key={j} data-phrase className="inline-block whitespace-nowrap">
                        {p}
                      </span>
                    ))}
              </p>
            </div>
            {bad && m?.orphanBoxes.map((b, j) => (
              <span
                key={j}
                aria-hidden
                className="pointer-events-none absolute border-2 border-[#d97706] bg-amber-200/30"
                style={{ left: b.x - 3, top: b.y - 2, width: b.w + 6, height: b.h + 4 }}
              />
            ))}
          </div>
        </div>
      </div>
    );
  };

  const cols = fit
    ? "@xl:grid-cols-[3.5rem_minmax(0,1fr)_minmax(0,1fr)]"
    : "w-max grid-cols-[430px] @xl:grid-cols-[3.5rem_430px_430px]";
  const rowNote = (row: Row) =>
    row === "before"
      ? "そのままの文"
      : hasBreaks
        ? `まとまり ${phrases.length}つを nowrap で包む`
        : "区切りなし。上の文字の間を押してください";

  return (
    <section
      className="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 sm:px-6">
        <div className="min-w-0">
          <p className="font-display text-[11px] font-semibold tracking-[0.18em] text-stone-500">TYP-06</p>
          <Heading
            id={`${uid}-h`}
            className="mt-1 text-[1.05rem] font-bold leading-[1.5] [word-break:keep-all] sm:text-[1.3rem]"
          >
            見出しの1文字落ちを
            <wbr />
            スマホ7台で比べて直す
          </Heading>
        </div>
        <dl className="flex gap-5 text-[12.5px]" aria-live="polite">
          <div className="flex items-baseline gap-1.5">
            <dt className="text-stone-500">直す前</dt>
            <dd className="font-display text-[1.25rem] font-bold tabular-nums text-amber-800">
              {count("before")}
              <span className="text-[12px] font-normal text-stone-500">/7台</span>
            </dd>
          </div>
          <div className="flex items-baseline gap-1.5">
            <dt className="text-stone-500">直した後</dt>
            <dd className="font-display text-[1.25rem] font-bold tabular-nums text-stone-900">
              {hasBreaks ? afterBad : "—"}
              <span className="text-[12px] font-normal text-stone-500">/7台</span>
            </dd>
          </div>
        </dl>
      </div>

      {/* 比較 */}
      <div ref={boardRef} className="@container flex scroll-mt-20 flex-col border-t border-stone-200">
        <div className="order-0 flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-4 pt-3 sm:px-6">
          <p className="text-[12.5px] text-stone-600">
            <strong className="font-bold text-stone-900">このブラウザ・この設定での表示です。</strong>
            枠の幅は端末の画面幅(CSS px)、左右の余白 {s.pad}px、縮尺{" "}
            <span className="font-display tabular-nums">{Math.round(k * 100)}%</span>(7台とも同じ)
          </p>
          <div role="group" aria-label="縮尺" className="grid grid-cols-2 border border-stone-300 text-[12.5px]">
            {[
              { v: true, label: "枠に合わせる" },
              { v: false, label: "実寸" },
            ].map((o) => (
              <button
                key={String(o.v)}
                type="button"
                aria-pressed={fit === o.v}
                onClick={() => setFit(o.v)}
                className={`zoom-${o.v ? "fit" : "full"} min-h-9 px-3 font-bold transition-colors motion-reduce:transition-none ${
                  fit === o.v ? "bg-stone-900 text-white" : "bg-white text-stone-700 hover:text-amber-800"
                } ${focusRing}`}
              >
                {o.label}
              </button>
            ))}
          </div>
        </div>
        <div className="editor order-1 mx-4 mt-3 border border-stone-200 bg-stone-50 px-3 py-3 sm:mx-6 sm:px-4 @xl:sticky @xl:bottom-0 @xl:z-10 @xl:order-3 @xl:mb-3 @xl:mt-0 @xl:py-2.5 @xl:shadow-[0_-10px_18px_-14px_rgba(28,25,23,0.35)]">
        <p id={`${uid}-gl`} className="text-[13.5px] font-bold">
          文字と文字の間を押すと、区切りが入ります
          <span className="ml-2 text-[12px] font-normal text-stone-500">
            キーボードは ← → で移動、Enter で入れる・外す
          </span>
        </p>
        <div
          role="toolbar"
          aria-labelledby={`${uid}-gl`}
          className="gaps mt-2 flex flex-wrap items-stretch"
          style={{ fontFamily: fontStack, fontWeight: s.weight }}
        >
          {chars.map((ch, i) => {
            const on = s.breaks.includes(i + 1);
            return (
              <span key={i} className="flex items-stretch">
                <span aria-hidden className="flex min-h-12 items-center text-[22px] leading-none sm:text-[26px]">
                  {ch}
                </span>
                {i < chars.length - 1 && (
                  <button
                    ref={(el) => {
                      gapRefs.current[i] = el;
                    }}
                    type="button"
                    tabIndex={i === Math.min(focusGap, chars.length - 2) ? 0 : -1}
                    aria-pressed={on}
                    aria-label={`「${ch}」と「${chars[i + 1]}」の間`}
                    onClick={() => toggleGap(i)}
                    onKeyDown={(e) => onGapKey(e, i)}
                    onFocus={() => setFocusGap(i)}
                    className={`gap-btn group relative flex w-6 justify-center ${focusRing}`}
                  >
                    <span
                      aria-hidden
                      className={`my-1.5 transition-[opacity,transform] duration-150 motion-reduce:transition-none ${
                        on
                          ? "w-[3px] bg-[#d97706]"
                          : "w-px scale-y-50 bg-stone-300 group-hover:scale-y-100 group-hover:bg-amber-500"
                      }`}
                    />
                  </button>
                )}
              </span>
            );
          })}
        </div>
        <p className="mt-3 text-[13px] leading-relaxed text-stone-600">
          {hasBreaks ? (
            <>
              まとまり:{" "}
              {phrases.map((p, j) => (
                <span key={j}>
                  {j > 0 && <span className="px-1 text-[#d97706]">|</span>}
                  {p}
                </span>
              ))}
            </>
          ) : (
            "区切りを入れたところでだけ改行します。意味のまとまり(〜も・〜して など)の後ろに入れるのが目安です"
          )}
        </p>
        <p aria-live="polite" className="sr-only">
          {live}
        </p>

        </div>
        <div className="compare order-2 overflow-x-auto px-4 pb-4 sm:px-6">
          <div className={`mt-4 grid gap-x-6 gap-y-1 text-[13.5px] ${cols}`}>
            <span aria-hidden className="hidden @xl:block" />
            {(["before", "after"] as Row[]).map((row) => (
              <p key={row} className="min-w-0 leading-snug">
                <span
                  className={`border-l-[3px] pl-2 font-bold ${row === "before" ? "border-stone-400" : "border-[#d97706]"}`}
                >
                  {row === "before" ? "直す前" : "直した後"}
                </span>
                <span className="ml-2 text-[12px] text-stone-500">{rowNote(row)}</span>
              </p>
            ))}
          </div>
          <ol className="mt-2">
            {ORDER.map((i) => WIDTHS[i]).map((w, n) => (
              <li key={w} className={`grid gap-x-6 gap-y-2 border-t border-stone-200 py-2.5 ${cols}`}>
                <p className="font-display text-[13px] font-semibold tabular-nums text-stone-700 @xl:pt-6">
                  {w}
                  <span className="text-[11px] text-stone-500">px</span>
                </p>
                {frameCell("before", w, ORDER[n])}
                {frameCell("after", w, ORDER[n])}
              </li>
            ))}
          </ol>
        </div>
      </div>

      {/* 原稿と設定 */}
      <div className="grid grid-cols-[minmax(0,1fr)] border-t border-stone-200 lg:grid-cols-[minmax(0,1fr)_20rem]">
        <div className="min-w-0 px-4 py-4 sm:px-6 lg:border-r lg:border-stone-200">
          <div>
            <label htmlFor={`${uid}-t`} className="text-[13.5px] font-bold">
              見出しを貼る
              <span className="ml-2 text-[12px] font-normal text-stone-500">{MAX_LEN}字まで・改行は詰めます</span>
            </label>
            <input
              id={`${uid}-t`}
              type="text"
              value={draft}
              maxLength={MAX_LEN + 10}
              onChange={(e) => commitText(e.target.value)}
              onBlur={() => setDraft(s.text)}
              className={`heading-input mt-2 block min-h-12 w-full border border-stone-300 bg-white px-3 text-[16px] ${focusRing}`}
            />
            <div className="mt-2 flex flex-wrap gap-2">
              {EXAMPLES.map((ex) => {
                const v = fromPhrases(ex.phrases);
                const active = v.text === s.text;
                return (
                  <button
                    key={ex.label}
                    type="button"
                    aria-pressed={active}
                    onClick={() => pickExample(ex.phrases)}
                    className={`min-h-9 border px-3 text-[13px] transition-colors motion-reduce:transition-none ${
                      active ? "border-[#d97706] font-bold text-amber-800" : "border-stone-300 text-stone-700 hover:border-stone-500"
                    } ${focusRing}`}
                  >
                    {ex.label}
                  </button>
                );
              })}
              <button
                type="button"
                onClick={() => {
                  setS((x) => ({ ...x, breaks: [] }));
                  setLive("区切りをすべて外しました");
                }}
                disabled={!hasBreaks}
                className={`clear-breaks min-h-9 border border-stone-300 px-3 text-[13px] text-stone-700 hover:border-stone-500 disabled:opacity-40 ${focusRing}`}
              >
                区切りをすべて外す
              </button>
            </div>
          </div>
        </div>

        {/* 設定 */}
        <div className="border-t border-stone-200 px-4 py-4 sm:px-6 lg:border-t-0">
          <Range
            id={`${uid}-p`}
            label="左右の余白"
            value={s.pad}
            min={PAD.min}
            max={PAD.max}
            onChange={(v) => setS((x) => ({ ...x, pad: v }))}
          />
          <Range
            id={`${uid}-s`}
            label="文字サイズ"
            value={s.size}
            min={SIZE.min}
            max={SIZE.max}
            onChange={(v) => setS((x) => ({ ...x, size: v }))}
          />
          <Choice
            name={`${uid}-w`}
            label="太さ"
            value={String(s.weight)}
            options={[
              { v: "400", label: "標準" },
              { v: "700", label: "太字" },
            ]}
            onChange={(v) => setS((x) => ({ ...x, weight: v === "400" ? 400 : 700 }))}
          />
          <Choice
            name={`${uid}-f`}
            label="フォント"
            value={s.font}
            options={[
              { v: "sans", label: FONTS.sans.label },
              { v: "serif", label: FONTS.serif.label },
            ]}
            onChange={(v) => setS((x) => ({ ...x, font: v === "serif" ? "serif" : "sans" }))}
          />
        </div>
      </div>

      {/* 出力 */}
      <div className="grid grid-cols-[minmax(0,1fr)] border-t border-stone-200 lg:grid-cols-[minmax(0,1fr)_20rem]">
        <div className="min-w-0 px-4 py-4 sm:px-6 lg:border-r lg:border-stone-200">
          <label htmlFor={`${uid}-o`} className="text-[13.5px] font-bold">
            直した後の HTML と CSS
          </label>
          <textarea
            id={`${uid}-o`}
            ref={outRef}
            readOnly
            value={output}
            rows={9}
            spellCheck={false}
            className={`output mt-2 block w-full resize-y border border-stone-300 bg-stone-50 p-3 font-mono text-[12.5px] leading-[1.7] text-stone-800 ${focusRing}`}
          />
          <p className="mt-2 text-[12.5px] leading-[1.75] text-stone-500">
            見出しの位置に h2 を、style の中身を CSS に貼ります。まとまりが内幅より長いと、その幅でははみ出します(上の枠に「収まりません」と出ます)。
          </p>
        </div>
        <div className="flex flex-col px-4 py-4 sm:px-6">
          <button
            type="button"
            onClick={copyCode}
            className={`copy-code min-h-12 bg-stone-900 px-5 text-[15px] font-bold text-white transition-colors hover:bg-amber-800 active:bg-amber-900 motion-reduce:transition-none ${focusRing}`}
          >
            {copyState === "ok" ? "コピーしました" : "HTML と CSS をコピー"}
          </button>
          <p aria-live="polite" className="mt-1.5 min-h-5 text-[13px] leading-relaxed text-stone-600">
            {copyState === "fail" && "自動でコピーできませんでした。コード欄を選択したので Ctrl+C(⌘C)でコピーしてください"}
          </p>
          <button
            type="button"
            onClick={saveImage}
            disabled={!res}
            className={`save-image mt-2 min-h-12 border border-stone-900 bg-white px-5 text-[15px] font-bold text-stone-900 transition-colors hover:border-[#d97706] hover:text-amber-800 motion-reduce:transition-none ${focusRing}`}
          >
            比較を画像で保存
          </button>
          <p aria-live="polite" className="mt-1.5 min-h-5 text-[13px] leading-relaxed text-stone-600">
            {saved === "ok" && "前後14台を並べた 1200×630 の PNG を保存しました"}
            {saved === "fail" && "画像を作れませんでした"}
          </p>
          <div className="mt-2 border-t border-stone-200 pt-3">
            <button
              type="button"
              onClick={makeShare}
              className={`copy-link min-h-12 w-full border border-stone-300 bg-white px-5 text-[14px] font-bold text-stone-900 transition-colors hover:border-[#d97706] hover:text-amber-800 motion-reduce:transition-none ${focusRing}`}
            >
              {shareState === "ok" ? "リンクをコピーしました" : "共有リンクを作る"}
            </button>
            <p className="mt-1.5 text-[12.5px] leading-relaxed text-amber-900">
              リンクを開いた人には原稿が見えます
            </p>
            {shareState === "fail" && (
              <>
                <label htmlFor={`${uid}-l`} className="sr-only">
                  共有リンク
                </label>
                <input
                  id={`${uid}-l`}
                  ref={linkRef}
                  readOnly
                  value={share?.url ?? ""}
                  onFocus={(e) => e.currentTarget.select()}
                  className={`share-fallback mt-2 block min-h-11 w-full border border-stone-300 bg-stone-50 px-3 font-mono text-[12.5px] text-stone-800 ${focusRing}`}
                />
              </>
            )}
            <p aria-live="polite" className="mt-1 min-h-5 text-[13px] leading-relaxed text-stone-600">
              {shareState === "ok" && "開くと、この原稿と設定の前後の比較から表示されます"}
              {shareState === "fail" && "自動でコピーできませんでした。上の欄を選択したので Ctrl+C(⌘C)でコピーしてください"}
            </p>
          </div>
        </div>
      </div>

      {/* 注記 */}
      <div className="border-t border-stone-200 px-4 py-3 text-[12.5px] leading-[1.8] text-stone-500 sm:px-6">
        {firstOrphan ? `「${firstOrphan}」` : "1〜2文字"}
        が落ちるかどうかは、端末の幅・余白・文字サイズ・フォントで変わります。同じ見出しでも、制作者の画面では1行に収まり、発注者のスマホでは落ちることがあります。幅は代表的な7つだけを見ています。仕様は{" "}
        <a
          href="https://www.w3.org/TR/css-text-3/#white-space-property"
          className={`underline decoration-stone-300 underline-offset-2 hover:text-amber-800 ${focusRing}`}
        >
          CSS Text Module Level 3(white-space)
        </a>
        。
      </div>
    </section>
  );
}

function Range({
  id,
  label,
  value,
  min,
  max,
  onChange,
}: {
  id: string;
  label: string;
  value: number;
  min: number;
  max: number;
  onChange: (v: number) => void;
}) {
  return (
    <div className="mb-3">
      <div className="flex items-baseline justify-between">
        <label htmlFor={id} className="text-[13.5px] font-bold">
          {label}
        </label>
        <span className="font-display text-[14px] font-semibold tabular-nums">{value}px</span>
      </div>
      <input
        id={id}
        type="range"
        min={min}
        max={max}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className={`h-11 w-full accent-[#d97706] ${focusRing}`}
      />
    </div>
  );
}

function Choice({
  name,
  label,
  value,
  options,
  onChange,
}: {
  name: string;
  label: string;
  value: string;
  options: { v: string; label: string }[];
  onChange: (v: string) => void;
}) {
  return (
    <fieldset className="mb-3">
      <legend className="mb-1.5 text-[13.5px] font-bold">{label}</legend>
      <div className="flex">
        {options.map((o, i) => (
          <label
            key={o.v}
            className={`flex min-h-11 flex-1 cursor-pointer items-center justify-center border px-2 text-center text-[13px] has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[#d97706] ${
              i > 0 ? "-ml-px" : ""
            } ${value === o.v ? "border-stone-900 bg-stone-900 font-bold text-white" : "border-stone-300 bg-white text-stone-700"}`}
          >
            <input
              type="radio"
              name={name}
              value={o.v}
              checked={value === o.v}
              onChange={() => onChange(o.v)}
              className="sr-only"
            />
            {o.label}
          </label>
        ))}
      </div>
    </fieldset>
  );
}

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

function drawComparison({
  s,
  phrases,
  res,
  fontStack,
}: {
  s: Settings;
  phrases: string[];
  res: Record<Row, Measure[]>;
  fontStack: string;
}) {
  const W = 1200;
  const H = 630;
  const cv = document.createElement("canvas");
  cv.width = W;
  cv.height = H;
  const ctx = cv.getContext("2d");
  if (!ctx) throw new Error("no canvas");
  const ui = '"Noto Sans JP", "Noto Sans CJK JP", "Hiragino Sans", sans-serif';
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(0, 0, W, H);
  ctx.textBaseline = "alphabetic";

  ctx.fillStyle = "#1c1917";
  ctx.font = `700 30px ${ui}`;
  ctx.fillText("見出しの1文字落ち スマホ7台で直す前と後", 48, 64);
  ctx.fillStyle = "#57534e";
  ctx.font = `400 15px ${ui}`;
  ctx.fillText(
    `文字サイズ ${s.size}px・${s.weight === 700 ? "太字" : "標準"}・左右の余白 ${s.pad}px・${FONTS[s.font].label}(このブラウザでの表示)`,
    48,
    94,
  );
  ctx.fillStyle = "#b45309";
  ctx.font = `700 15px ${ui}`;
  ctx.textAlign = "right";
  ctx.fillText("designs.first-ch.com", W - 48, 64);
  ctx.textAlign = "left";

  // 2列(直す前・直した後)に7台を縦に積む。縮尺は全台で同じ
  const top = 150;
  const bottom = H - 30;
  const colW = (W - 48 * 2 - 40) / 2;
  const labelW = 58;
  const badgeW = 150;
  const gap = 7;
  const lh = s.size * 1.5;
  const padY = s.size * 0.5;
  const rows = WIDTHS.map((_, i) => Math.max(res.before[i].lines.length, res.after[i].lines.length, 1));
  const totalH = rows.reduce((a, n) => a + n * lh + padY * 2, 0);
  const k = Math.min((bottom - top - gap * (WIDTHS.length - 1)) / totalH, (colW - labelW - badgeW) / WIDTHS[WIDTHS.length - 1]);

  (["before", "after"] as Row[]).forEach((row, c) => {
    const x0 = 48 + c * (colW + 40);
    const n = row === "before" ? res.before.filter((m) => m.orphan).length : res.after.filter((m) => m.orphan || m.overflow).length;
    ctx.fillStyle = row === "before" ? "#a8a29e" : "#d97706";
    ctx.fillRect(x0, top - 30, 4, 20);
    ctx.fillStyle = "#1c1917";
    ctx.font = `700 18px ${ui}`;
    ctx.fillText(row === "before" ? "直す前" : "直した後", x0 + 12, top - 13);
    const lab = row === "before" ? "直す前" : "直した後";
    const lw = ctx.measureText(lab).width;
    ctx.font = `400 14px ${ui}`;
    ctx.fillStyle = "#57534e";
    ctx.fillText(
      row === "before" ? `7台中 ${n}台で1〜2文字が落ちる` : phrases.length > 1 ? `7台中 ${n}台・${phrases.join("|")}` : "区切りなし",
      x0 + 12 + lw + 12,
      top - 13,
    );
    let y = top;
    ORDER.forEach((i) => {
      const w = WIDTHS[i];
      const m = res[row][i];
      const h = (rows[i] * lh + padY * 2) * k;
      const fw = w * k;
      ctx.fillStyle = "#78716c";
      ctx.font = `600 12px ${ui}`;
      ctx.fillText(`${w}px`, x0, y + Math.min(h, 22) / 2 + 9);
      const fx = x0 + labelW;
      const bad = !!m.orphan && (row === "before" || phrases.length > 1);
      const over = row === "after" && phrases.length > 1 && !!m.overflow;
      ctx.strokeStyle = over ? "#dc2626" : bad ? "#d97706" : "#d6d3d1";
      ctx.lineWidth = bad || over ? 2 : 1;
      ctx.strokeRect(fx + 0.5, y + 0.5, fw - 1, h - 1);
      ctx.save();
      ctx.beginPath();
      ctx.rect(fx, y, fw, h);
      ctx.clip();
      ctx.fillStyle = "#1c1917";
      ctx.font = `${s.weight} ${s.size * k}px ${fontStack}`;
      m.lines.forEach((line, li) => {
        const by = y + (padY + li * lh + lh * 0.5 + s.size * 0.36) * k;
        const isLast = li === m.lines.length - 1;
        if (bad && isLast) {
          const tw = ctx.measureText(line).width;
          ctx.fillStyle = "rgba(253,230,138,0.6)";
          ctx.fillRect(fx + s.pad * k - 3, y + (padY + li * lh) * k + 1, tw + 6, lh * k - 2);
          ctx.strokeStyle = "#d97706";
          ctx.lineWidth = 2;
          ctx.strokeRect(fx + s.pad * k - 3, y + (padY + li * lh) * k + 1, tw + 6, lh * k - 2);
          ctx.fillStyle = "#1c1917";
        }
        ctx.fillText(line, fx + s.pad * k, by);
      });
      ctx.restore();
      ctx.font = `700 13px ${ui}`;
      ctx.fillStyle = over ? "#b91c1c" : bad ? "#92400e" : "#a8a29e";
      ctx.fillText(
        over ? "収まりません" : bad ? `「${m.orphan}」が${Array.from(m.orphan ?? "").length}文字` : row === "after" && phrases.length < 2 ? "区切りなし" : `${m.lines.length}行`,
        fx + fw + 10,
        y + Math.min(h, 22) / 2 + 9,
      );
      y += h + gap;
    });
  });
  return cv.toDataURL("image/png");
}

Add to your project via shadcn CLI

npx shadcn@latest add https://designs.first-ch.com/r/phrase-break-heading.json