Japanese Punctuation Trim Generator | Heading HTML & CSS with text-spacing-trim and a Safari Fallback
Generates HTML and CSS that trim the space around brackets and punctuation in Japanese headings, then measures three equal-width rows — solid setting, this browser's default and the generated setting — character by character and shows the difference in px. In browsers without text-spacing-trim, such as Safari, only the punctuation to trim (line-start 「, 。(, 」「 …) is wrapped in a span and halved with halt, falling back to a negative margin when the font lacks halt; supporting browsers use native trimming inside @supports. Also shows what proportional kana (palt) changes: the width delta and which characters move. No dependencies. Headings are fictional samples.
Preview
TYP-04
約物詰めを3段で実測して、HTML・CSSに
このブラウザ: span方式(halt)・約物詰めに未対応
① ベタ組み
詰める約物 2字「新作」公開。(11月)
② このブラウザの初期値
幅 —「新作」公開。(11月)
③ 生成した組み
幅 —span+"halt"「新作」公開。(11月)
縦線は左端・詰めた箇所・右端、バッジは①との差(1文字ずつ実測)。
span方式が詰める行頭は、文頭と改行(<br>)の直後だけです。自然な折り返しの行頭はネイティブ方式だけが詰めます。
Read the full description
Generates HTML and CSS that trim the space around brackets and punctuation in Japanese headings, then measures three equal-width rows — solid setting, this browser's default and the generated setting — character by character and shows the difference in px. In browsers without text-spacing-trim, such as Safari, only the punctuation to trim (line-start 「, 。(, 」「 …) is wrapped in a span and halved with halt, falling back to a negative margin when the font lacks halt; supporting browsers use native trimming inside @supports. Also shows what proportional kana (palt) changes: the width delta and which characters move. No dependencies. Headings are fictional samples.
- Added:
- 2026-11-03
- Updated:
- 2026-11-04
- Dependencies:
- None
- tags
- #typography #japanese #heading #text-spacing-trim #font-feature-settings #halt #palt #safari #generator #css #keyboard #no-dependency #no-image
"use client";
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type CSSProperties,
type ReactNode,
} from "react";
/**
* 見出しの約物詰め(Safari でも効く HTML と CSS を生成し、ベタ組み・ブラウザの初期値と並べて実測する)
*
* 差別化: 既存の見出しタイポ(scroll-reveal-editorial・text-swap-tabs・watermark-heading-section・section-heading・
* typed-glitch-header・wind-blown-text)はどれも見出しの見た目や動きの見本。本ブロックは動きを持たず、和文見出しの約物の空きを
* 判定して実装用のコードを出す道具で、同じ幅の3段を1文字ずつ測って差を px で示す計測表示が主役。英字の小見出し・見出しの「。」止め・
* 末尾の矢印リンク・角丸・出現アニメは使わない。
*
* 汎用技法メモ:
* 1. 詰める約物の判定は text-spacing-trim: trim-start に合わせる。行頭の開き括弧と、約物の後の開き括弧(。( 」「 (「)は前側を、
* 閉じ約物の前の閉じ約物(」」 。」)は後側を半分にする。行頭として扱うのは文頭と改行(<br>)の直後だけ。
* 2. 判定した文字だけを span で包み、font-feature-settings:"halt" で半角にする。描画後に span の幅を測り、0.75em を超える
* (フォントに halt が無い)ときは font-feature-settings:normal +負の margin(-0.5em) に切り替える。
* 3. @supports (text-spacing-trim: trim-start) の中では span の指定を外し、ネイティブの約物詰めに任せる(折り返しの行頭にも効く)。
* 4. 差は Range.getClientRects で1文字ずつ測る。開き括弧の字面は全角の右半分にあるので左端は「字の箱の右端−0.5em」、
* 閉じ約物の右端は「箱の左端+0.5em」で見る。margin で詰めた字は箱が縮まないため、詰めた量は
* 「前の字の終わり→次の字の始まり」の間隔で比べる。
*/
const AMBER = "#d97706";
const PAGE_URL = "https://designs.first-ch.com/d/yakumono-spacing-compare";
const DEFAULT_TEXT = "「新作」公開。(11月)";
const EXAMPLES = [
DEFAULT_TEXT,
"『制作実績』(2026年)\n「選ばれる理由」",
"【11月限定】「初回診断」無料。",
"「無料相談」受付中。(年内は12/26まで)",
];
const MAX_LEN = 80;
const MAX_LINES = 4;
const SIZE_MIN = 20;
const SIZE_MAX = 72;
const focusRing =
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]";
const OPEN = new Set([..."「『([{〈《【〔〘〖⦅〝"]);
const CLOSE = new Set([..."」』)]}〉》】〕〙〗⦆〟、。,."]);
const MIDDLE = new Set([..."・:;"]);
export type Token = { text: string; trim?: "s" | "e" };
export type TrimMethod = "halt" | "margin";
type FontId = "sans" | "serif";
type View = "hero" | "card";
const FONTS: Record<FontId, { label: string; stack: string; css: string }> = {
sans: {
label: "Noto Sans JP",
stack: 'var(--font-noto-sans-jp), "Noto Sans JP", sans-serif',
css: '"Noto Sans JP", sans-serif',
},
serif: {
label: "端末の明朝",
stack:
'"Hiragino Mincho ProN", "Yu Mincho", YuMincho, "Noto Serif JP", "Noto Serif CJK JP", serif',
css: '"Hiragino Mincho ProN", "Yu Mincho", YuMincho, "Noto Serif JP", serif',
},
};
/** 入力をそろえる(改行は4行まで・長さは80字まで) */
export function normalizeText(text: string) {
const lines = text.replace(/\r\n?/g, "\n").split("\n").slice(0, MAX_LINES);
return Array.from(lines.join("\n")).slice(0, MAX_LEN).join("");
}
/** 1行ずつ、詰める約物だけを切り出す。s=前側(開き括弧)を半分、e=後側(閉じ約物)を半分 */
export function segment(text: string): Token[][] {
return normalizeText(text)
.split("\n")
.map((line) => {
const cs = Array.from(line);
const out: Token[] = [];
let buf = "";
cs.forEach((c, i) => {
const prev = cs[i - 1];
const next = cs[i + 1];
let trim: Token["trim"];
if (
OPEN.has(c) &&
(i === 0 ||
OPEN.has(prev) ||
CLOSE.has(prev) ||
MIDDLE.has(prev) ||
prev === " ")
)
trim = "s";
else if (
CLOSE.has(c) &&
next !== undefined &&
(CLOSE.has(next) || MIDDLE.has(next))
)
trim = "e";
if (trim) {
if (buf) out.push({ text: buf });
buf = "";
out.push({ text: c, trim });
} else buf += c;
});
if (buf) out.push({ text: buf });
return out;
});
}
const esc = (s: string) =>
s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
export function buildHtml(lines: Token[][], tag = "h2") {
const body = lines
.map((l) =>
l
.map((t) =>
t.trim
? `<span class="yk yk-${t.trim}">${esc(t.text)}</span>`
: esc(t.text),
)
.join(""),
)
.join("<br>");
return `<${tag} class="yk-heading">${body}</${tag}>`;
}
export function buildCss({
fontCss,
palt,
method,
}: {
fontCss: string;
palt: boolean;
method: TrimMethod;
}) {
const head = [
`.yk-heading {`,
` font-family: ${fontCss};`,
...(palt ? [` font-feature-settings: "palt";`] : []),
`}`,
];
const span =
method === "halt"
? [
`/* text-spacing-trim に未対応のブラウザ: 詰める約物だけ半角の字形にする */`,
`.yk { font-feature-settings: "halt"; }`,
]
: [
`/* text-spacing-trim に未対応のブラウザ: フォントに halt が無いので負の margin で詰める */`,
`.yk { font-feature-settings: normal; }`,
`.yk-s { margin-inline-start: -0.5em; }`,
`.yk-e { margin-inline-end: -0.5em; }`,
];
const native = [
`/* 対応ブラウザはネイティブの約物詰めに任せる */`,
`@supports (text-spacing-trim: trim-start) {`,
` .yk-heading { text-spacing-trim: trim-start; }`,
` .yk { font-feature-settings: inherit; margin: 0; }`,
`}`,
];
return [...head, "", ...span, "", ...native].join("\n");
}
export type CopyTarget = "code" | "link";
export type CopyResult = {
target: CopyTarget;
state: "ok" | "fail";
text: string;
};
/** コピーの結果は直近の1操作だけ。その対象で、コピーした文が今の出力と同じ間だけ有効(入力を変えたら外す) */
export function copyStatus(
copied: CopyResult | null,
target: CopyTarget,
text: string,
) {
return copied && copied.target === target && copied.text === text
? copied.state
: null;
}
/** palt の有無で1文字ずつ幅を比べ、幅の変わった字(重複なし)と合計の差を返す */
export function paltChange(chars: string[], plain: number[], palt: number[]) {
const changed: string[] = [];
let d = 0;
chars.forEach((c, i) => {
const x = (palt[i] ?? 0) - (plain[i] ?? 0);
d += x;
if (Math.abs(x) >= 0.5 && !changed.includes(c)) changed.push(c);
});
return { d, changed };
}
type Settings = {
text: string;
size: number;
font: FontId;
palt: boolean;
view: View;
};
const DEFAULTS: Settings = {
text: DEFAULT_TEXT,
size: 28,
font: "sans",
palt: false,
view: "hero",
};
export function encodeSettings(s: Settings) {
const p = new URLSearchParams();
p.set("t", s.text);
p.set("s", String(s.size));
p.set("f", s.font);
p.set("k", s.palt ? "1" : "0");
p.set("v", s.view);
return p.toString();
}
export function decodeSettings(hash: string): Settings | null {
const p = new URLSearchParams(hash.replace(/^#/, ""));
const t = p.get("t");
if (t === null) return null;
const size = Number(p.get("s"));
return {
text: normalizeText(t),
size:
Number.isFinite(size) && size >= SIZE_MIN && size <= SIZE_MAX
? Math.round(size)
: DEFAULTS.size,
font: p.get("f") === "serif" ? "serif" : "sans",
palt: p.get("k") === "1",
view: p.get("v") === "card" ? "card" : "hero",
};
}
// ---- 実測 ----
type Box = {
ch: string;
left: number;
right: number;
top: number;
bottom: number;
};
type Line = {
start: number;
end: number;
inkL: number;
inkR: number;
top: number;
bottom: number;
};
type Badge = {
x: number;
y: number;
d: number;
align: "start" | "center";
};
type Mark = {
lines: { x: number[]; top: number; bottom: number }[];
badges: Badge[];
sum: number;
};
/** 祖先に transform: scale があると getBoundingClientRect は拡大縮小後の値になるので、要素の CSS 上の幅との比で割り戻す */
function scaleOf(el: HTMLElement) {
const w = el.offsetWidth;
return w > 0 ? el.getBoundingClientRect().width / w || 1 : 1;
}
function measureChars(
el: HTMLElement,
origin: DOMRect,
k = scaleOf(el),
): Box[] {
const out: Box[] = [];
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
const range = document.createRange();
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const node = n as Text;
let off = 0;
for (const ch of Array.from(node.data)) {
range.setStart(node, off);
range.setEnd(node, off + ch.length);
const rs = Array.from(range.getClientRects());
const r = rs.find((x) => x.width > 0) ?? rs[0];
if (r)
out.push({
ch,
left: (r.left - origin.left) / k,
right: (r.right - origin.left) / k,
top: (r.top - origin.top) / k,
bottom: (r.bottom - origin.top) / k,
});
off += ch.length;
}
}
return out;
}
function toLines(chars: Box[], fs: number): Line[] {
const lines: Line[] = [];
chars.forEach((c, i) => {
const last = lines[lines.length - 1];
if (!last || c.top > chars[i - 1].top + (c.bottom - c.top) * 0.5)
lines.push({
start: i,
end: i,
inkL: 0,
inkR: 0,
top: c.top,
bottom: c.bottom,
});
else {
last.end = i;
last.bottom = Math.max(last.bottom, c.bottom);
}
});
for (const l of lines) {
const a = chars[l.start];
const b = chars[l.end];
l.inkL = OPEN.has(a.ch) ? Math.max(a.left, a.right - fs * 0.5) : a.left;
l.inkR = CLOSE.has(b.ch) ? Math.min(b.right, b.left + fs * 0.5) : b.right;
}
return lines;
}
/** 詰めた字の前後の間隔(前の字の終わり→次の字の始まり)。行頭なら本文の左端から */
function gapAt(chars: Box[], lines: Line[], k: number, contentLeft: number) {
const line = lines.find((l) => k >= l.start && k <= l.end);
if (!line) return null;
const prevEnd = k > line.start ? chars[k - 1].right : contentLeft;
const nextStart = k < line.end ? chars[k + 1].left : chars[k].right;
return {
prevEnd,
nextStart,
gap: nextStart - prevEnd,
lineStart: k === line.start,
line,
};
}
function analyze(
rows: (HTMLElement | null)[],
wraps: (HTMLElement | null)[],
trims: { index: number; side: "s" | "e" }[],
fs: number,
): Mark[] | null {
if (rows.some((r) => !r) || wraps.some((w) => !w)) return null;
const data = rows.map((el, i) => {
const origin = wraps[i]!.getBoundingClientRect();
const k = scaleOf(wraps[i]!);
const contentLeft = (el!.getBoundingClientRect().left - origin.left) / k;
const chars = measureChars(el!, origin, k);
return { chars, lines: toLines(chars, fs), contentLeft };
});
const ref = data[0];
// 本文の左端から各行の最後の字の箱の右端までを足す(行頭の空きを詰めた分も入り、行末の約物は箱で数えて折り返し位置に左右されない)
const total = (row: { chars: Box[]; lines: Line[]; contentLeft: number }) =>
row.lines.reduce(
(sum, l) => sum + row.chars[l.end].right - row.contentLeft,
0,
);
return data.map((row, r) => {
const badges: Badge[] = [];
const xs = row.lines.map((l) => [l.inkL, l.inkR]);
const diff = (k: number) => {
const g = gapAt(row.chars, row.lines, k, row.contentLeft);
const g0 = gapAt(ref.chars, ref.lines, k, ref.contentLeft);
return g && g0 ? { g, d: g.gap - g0.gap } : null;
};
// 行頭の開き括弧(改行の直後も、自然な折り返しの行頭も)は、①での同じ字の間隔と比べて左端に出す
row.lines.forEach((l) => {
if (r === 0 || !OPEN.has(row.chars[l.start].ch)) return;
const got = diff(l.start);
if (got && Math.abs(got.d) >= 0.5)
badges.push({ x: l.inkL, y: l.bottom, d: got.d, align: "start" });
});
for (const t of trims) {
const got = diff(t.index);
if (!got || got.g.lineStart) continue;
const x = t.side === "s" ? got.g.prevEnd : got.g.nextStart;
xs[row.lines.indexOf(got.g.line)].push(x);
if (r > 0 && Math.abs(got.d) >= 0.5)
badges.push({ x, y: got.g.line.bottom, d: got.d, align: "center" });
}
// 折り返しの位置が段ごとに違っても比べられるよう、全行の長さの合計で①と比べる
const sum = r === 0 ? 0 : total(row) - total(ref);
return {
lines: row.lines.map((l, j) => ({
x: xs[j],
top: l.top,
bottom: l.bottom,
})),
badges,
sum,
};
});
}
const fmt = (d: number) => `${d < 0 ? "−" : "+"}${Math.abs(Math.round(d))}px`;
// ---- 対応の判定 ----
const noop = () => () => {};
const nativeSnapshot = () =>
typeof CSS !== "undefined" && CSS.supports("text-spacing-trim", "trim-start");
export default function YakumonoSpacingCompare({
headingTag: Heading = "h2",
}: {
headingTag?: "h1" | "h2" | "p";
}) {
const uid = useId();
const [s, setS] = useState<Settings>(DEFAULTS);
const [forceSpan, setForceSpan] = useState(false);
const [method, setMethod] = useState<TrimMethod>("halt");
const [marks, setMarks] = useState<Mark[] | null>(null);
const [paltInfo, setPaltInfo] = useState<{
d: number;
changed: string[];
} | null>(null);
const [tick, setTick] = useState(0);
const [stickyTop, setStickyTop] = useState(0);
const [copyResult, setCopyResult] = useState<CopyResult | null>(null);
const supportsNative = useSyncExternalStore(
noop,
nativeSnapshot,
() => false,
);
const native = supportsNative && !forceSpan;
const rowRefs = useRef<(HTMLElement | null)[]>([null, null, null]);
const wrapRefs = useRef<(HTMLDivElement | null)[]>([null, null, null]);
const probeRef = useRef<HTMLParagraphElement>(null);
const paltProbeRefs = useRef<(HTMLParagraphElement | null)[]>([null, null]);
const boardRef = useRef<HTMLDivElement>(null);
const outRef = useRef<HTMLTextAreaElement>(null);
const linkRef = useRef<HTMLInputElement>(null);
const lines = useMemo(() => segment(s.text), [s.text]);
const trims = useMemo(() => {
const out: { index: number; side: "s" | "e" }[] = [];
let i = 0;
for (const l of lines)
for (const t of l) {
if (t.trim) out.push({ index: i, side: t.trim });
i += Array.from(t.text).length;
}
return out;
}, [lines]);
const font = FONTS[s.font];
const html = useMemo(() => buildHtml(lines), [lines]);
const css = useMemo(
() => buildCss({ fontCss: font.css, palt: s.palt, method }),
[font.css, s.palt, method],
);
const output = `${html}\n\n<style>\n${css}\n</style>`;
const shareUrl = `${PAGE_URL}#${encodeSettings(s)}`;
const copied = copyStatus(copyResult, "code", output);
const linkCopied = copyStatus(copyResult, "link", shareUrl);
const fs = s.view === "card" ? cardSize(s.size) : s.size;
// URL のフラグメントから見出しと設定を読む(共有リンクで開いたとき・戻る/進むで変わったとき)
useEffect(() => {
const apply = () => {
const got = decodeSettings(window.location.hash);
if (got) setS(got);
};
const id = requestAnimationFrame(apply);
window.addEventListener("hashchange", apply);
return () => {
cancelAnimationFrame(id);
window.removeEventListener("hashchange", apply);
};
}, []);
// フォントの読み込み・幅の変化で測り直す。見えない標本は折り返さないので、
// Web フォントへ差し替わると幅が変わる(loadingdone を取り逃しても測り直せる)
useEffect(() => {
const bump = () => setTick((n) => n + 1);
const fonts = document.fonts;
fonts?.ready.then(bump);
fonts?.addEventListener("loadingdone", bump);
const ro = new ResizeObserver(bump);
for (const el of [
boardRef.current,
probeRef.current,
...paltProbeRefs.current,
])
if (el) ro.observe(el);
return () => {
fonts?.removeEventListener("loadingdone", bump);
ro.disconnect();
};
}, []);
// 置いたページに上端へ貼りつくヘッダーがあれば、小さな比較をその下に貼りつける
useEffect(() => {
const header = document.querySelector("header");
if (!header) return;
const read = () => {
const pos = getComputedStyle(header).position;
setStickyTop(
pos === "sticky" || pos === "fixed"
? Math.round(header.getBoundingClientRect().height)
: 0,
);
};
read();
const ro = new ResizeObserver(read);
ro.observe(header);
return () => ro.disconnect();
}, []);
// 描画後に span の幅を測り、halt で半角にならないフォントなら負の margin に切り替える
useLayoutEffect(() => {
const el = probeRef.current;
if (!el) return;
const spans = Array.from(el.querySelectorAll<HTMLElement>(".yk"));
const k = scaleOf(el);
const wide = spans.some(
(sp) => sp.getBoundingClientRect().width / k > s.size * 0.75,
);
setMethod(wide ? "margin" : "halt");
}, [s.size, s.font, tick]);
// ③と同じ組みの見えない標本を palt なし・ありで1文字ずつ測り、palt だけで③の幅がいくつ変わるか・どの字が変わるかを出す
useLayoutEffect(() => {
const [a, b] = paltProbeRefs.current;
if (!a || !b) return;
const widths = (el: HTMLElement) =>
measureChars(el, el.getBoundingClientRect()).map((c) => ({
ch: c.ch,
w: c.right - c.left,
}));
const plain = widths(a);
const palt = widths(b);
setPaltInfo(
paltChange(
plain.map((c) => c.ch),
plain.map((c) => c.w),
palt.map((c) => c.w),
),
);
}, [s.text, s.font, fs, native, method, forceSpan, tick]);
// 3段を1文字ずつ測り、①との差を出す
useLayoutEffect(() => {
setMarks(analyze(rowRefs.current, wrapRefs.current, trims, fs));
}, [trims, fs, s.font, s.palt, s.view, native, method, tick, paltInfo]);
// 自動でコピーできなかったら、その対象の欄を選択して手でコピーできるようにする
useEffect(() => {
if (copied === "fail") {
outRef.current?.focus();
outRef.current?.select();
}
if (linkCopied === "fail") {
linkRef.current?.focus();
linkRef.current?.select();
}
}, [copied, linkCopied]);
const update = useCallback(
<K extends keyof Settings>(k: K, v: Settings[K]) =>
setS((p) => ({ ...p, [k]: v })),
[],
);
const copyText = async (target: CopyTarget, text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopyResult({ target, state: "ok", text });
} catch {
setCopyResult({ target, state: "fail", text });
}
};
const baseStyle: CSSProperties = { fontFamily: font.stack, fontSize: fs };
const styleFor = (r: number, size?: number, palt = s.palt): CSSProperties => {
const base = size ? { ...baseStyle, fontSize: size } : baseStyle;
if (r === 0)
return {
...base,
textSpacingTrim: "space-all",
fontFeatureSettings: "normal",
} as CSSProperties;
if (r === 1) return base;
return {
...base,
...(native
? { textSpacingTrim: "trim-start" }
: forceSpan
? { textSpacingTrim: "space-all" }
: {}),
fontFeatureSettings: palt ? '"palt"' : "normal",
} as CSSProperties;
};
const spanStyle = (side: "s" | "e"): CSSProperties =>
native
? { fontFeatureSettings: "inherit" }
: method === "halt"
? { fontFeatureSettings: '"halt"' }
: {
fontFeatureSettings: "normal",
[side === "s" ? "marginInlineStart" : "marginInlineEnd"]: "-0.5em",
};
// palt で幅の変わった字に引く下線(字の位置は動かさない)
const paltMarked =
s.palt && paltInfo ? new Set(paltInfo.changed) : new Set<string>();
const markStyle: CSSProperties = {
textDecorationLine: "underline",
textDecorationColor: AMBER,
textDecorationThickness: 2,
textUnderlineOffset: "0.2em",
};
const renderLines = (withSpans: boolean, marked?: Set<string>): ReactNode =>
lines.map((l, i) => (
<span key={i}>
{i > 0 && <br />}
{l.map((t, j) =>
t.trim && withSpans ? (
<span
key={j}
className={`yk yk-${t.trim}`}
style={spanStyle(t.trim)}
>
{t.text}
</span>
) : marked && marked.size > 0 ? (
<span key={j}>
{Array.from(t.text).map((c, k) =>
marked.has(c) ? (
<span key={k} className="palt-mark" style={markStyle}>
{c}
</span>
) : (
c
),
)}
</span>
) : (
<span key={j}>{t.text}</span>
),
)}
</span>
));
// 2行以上のときは、行の下に出すバッジ(高さ約16px)が次の行の字に掛からない行間を確保する
// (改行のほか、①が自然に折り返したときも。行間は折り返しの位置を変えないので測り直しで揺れない)
const multiLine = lines.length > 1 || (marks?.[0]?.lines.length ?? 1) > 1;
const badgeLeading = `max(${s.view === "card" ? "2.1em" : "1.9em"}, calc(1.5em + 20px))`;
const modeLabel = native
? "ネイティブ方式"
: method === "halt"
? "span方式(halt)"
: "span方式(負のmargin)";
const rowsInfo = [
{
n: "①",
name: "ベタ組み",
code: "text-spacing-trim: space-all",
},
{
n: "②",
name: "このブラウザの初期値",
code: supportsNative
? "指定なし(normal)"
: "指定なし(約物詰めに未対応)",
},
{
n: "③",
name: "生成した組み",
code: native
? `text-spacing-trim: trim-start${s.palt ? "+palt" : ""}`
: `span+${method === "halt" ? '"halt"' : "margin: -0.5em"}${s.palt ? "+palt" : ""}`,
},
];
const w2 = marks?.[1]?.sum;
const w3 = marks?.[2]?.sum;
const total = (w?: number) =>
w === undefined ? "—" : Math.abs(w) < 0.5 ? "±0px" : fmt(w);
const paltText = !paltInfo
? ""
: Math.abs(paltInfo.d) < 0.5
? s.palt
? "適用中・この見出しでは幅の変化なし"
: "この見出しでは幅の変化なし"
: s.palt
? `適用中・③が ${fmt(paltInfo.d)}`
: `入れると③が ${fmt(paltInfo.d)}`;
const shownChanged = paltInfo?.changed.slice(0, 8) ?? [];
const moreChanged = (paltInfo?.changed.length ?? 0) - shownChanged.length;
const segBtn = (on: boolean) =>
`flex min-h-11 flex-1 cursor-pointer items-center justify-center border px-3 text-[14px] font-medium transition-colors motion-reduce:transition-none has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-[#d97706] ${
on
? "border-stone-900 bg-stone-900 text-white"
: "border-stone-300 bg-white text-stone-700 hover:border-stone-500"
}`;
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-1 px-4 pb-3 pt-4 sm:px-6">
<div>
<p className="font-display text-[11px] font-semibold tracking-[0.18em] text-stone-500">
TYP-04
</p>
<Heading
id={`${uid}-h`}
className="mt-1 text-[1.05rem] font-bold leading-[1.5] [word-break:keep-all] sm:text-[1.3rem]"
>
約物詰めを3段で実測
<span className="hidden sm:inline">して、HTML・CSSに</span>
</Heading>
</div>
<p role="status" className="text-[12.5px] text-stone-600">
このブラウザ:{" "}
<strong className="font-bold text-stone-900">{modeLabel}</strong>
{!supportsNative
? "・約物詰めに未対応"
: forceSpan
? "・③は未対応時の組み"
: ""}
</p>
</div>
<div className="grid grid-cols-[minmax(0,1fr)] border-t border-stone-200 lg:grid-cols-[minmax(0,1fr)_20rem]">
{/* 3段の比較 */}
<div
ref={boardRef}
className="relative min-w-0 lg:border-r lg:border-stone-200"
>
<ol className="divide-y divide-stone-200">
{rowsInfo.map((info, r) => (
<li
key={info.n}
className={`compare-row px-4 pb-4 pt-2.5 sm:px-6 ${r === 2 ? "bg-amber-50/40" : ""}`}
>
<div className="flex items-start justify-between gap-3">
<p className="min-w-0 text-[13.5px] leading-snug">
<span className="font-bold">
{info.n} {info.name}
</span>
<code
className={`ml-2 font-mono text-[11.5px] text-stone-500 ${r === 2 ? "inline-block" : "hidden sm:inline-block"}`}
>
{info.code}
</code>
</p>
{r === 0 ? (
<span className="shrink-0 text-[12px] text-stone-500">
詰める約物{" "}
<strong className="font-display tabular-nums text-stone-900">
{trims.length}
</strong>
字
</span>
) : (
<span
className={`row-total shrink-0 border px-1.5 py-0.5 font-display text-[12px] font-semibold tabular-nums ${
r === 2
? "border-[#d97706] bg-[#d97706] text-white"
: "border-stone-300 text-stone-700"
}`}
>
幅 {total(r === 1 ? w2 : w3)}
</span>
)}
</div>
<div
className={
s.view === "card"
? "mt-2 w-[17rem] max-w-full border border-stone-200 bg-white"
: "mt-1.5"
}
>
{s.view === "card" && (
<div
aria-hidden
className="flex h-10 items-end bg-stone-100 px-3 pb-2"
>
<span className="h-px w-10 bg-stone-300" />
</div>
)}
<div className={s.view === "card" ? "px-4 pb-4 pt-2" : ""}>
{s.view === "card" && (
<p className="text-[12px] font-medium text-amber-700">
お知らせ
</p>
)}
<div
ref={(el) => void (wrapRefs.current[r] = el)}
className="relative"
>
<p
ref={(el) => void (rowRefs.current[r] = el)}
style={
multiLine
? { ...styleFor(r), lineHeight: badgeLeading }
: styleFor(r)
}
className={`font-bold text-stone-900 ${s.view === "card" ? "leading-[2.1]" : "leading-[1.9]"}`}
>
{renderLines(r === 2, r === 2 ? paltMarked : undefined)}
</p>
<Overlay mark={marks?.[r]} />
</div>
</div>
</div>
</li>
))}
</ol>
<p className="border-t border-stone-200 px-4 py-2 text-[12px] leading-relaxed text-stone-500 sm:px-6">
縦線は左端・詰めた箇所・右端、バッジは①との差(1文字ずつ実測)。
</p>
{/* halt の効き具合と palt の差を測るための見えない標本(長い見出しでもページを横にはみ出させない) */}
<div
aria-hidden
className="pointer-events-none invisible absolute inset-0 overflow-hidden"
>
<p
ref={probeRef}
aria-hidden
className="pointer-events-none invisible absolute left-0 top-0 whitespace-nowrap font-bold"
style={
{
fontFamily: font.stack,
fontSize: s.size,
textSpacingTrim: "space-all",
} as CSSProperties
}
>
<span className="yk" style={{ fontFeatureSettings: '"halt"' }}>
「
</span>
<span className="yk" style={{ fontFeatureSettings: '"halt"' }}>
。
</span>
</p>
{[false, true].map((palt, i) => (
<p
key={String(palt)}
ref={(el) => void (paltProbeRefs.current[i] = el)}
aria-hidden
className="pointer-events-none invisible absolute left-0 top-0 whitespace-nowrap font-bold"
style={styleFor(2, undefined, palt)}
>
{renderLines(true)}
</p>
))}
</div>
</div>
{/* 操作 */}
<div className="border-t border-stone-200 lg:border-t-0">
{/* 狭い画面で設定を触っている間も①と③を見比べられる小さな比較(広い画面では3段が隣にあるので出さない) */}
<div
style={{ top: stickyTop }}
className="mini-compare sticky z-10 border-b border-stone-200 bg-white/95 px-4 py-2 backdrop-blur-sm sm:px-6 lg:hidden"
>
{[0, 2].map((r) => (
<div key={r} className="flex items-center gap-3">
<span className="w-5 shrink-0 text-[12px] font-bold text-stone-500">
{r === 0 ? "①" : "③"}
</span>
<p
aria-hidden
style={styleFor(r, 17)}
className="min-w-0 flex-1 overflow-hidden whitespace-nowrap font-bold leading-[1.7] text-stone-900"
>
{renderLines(r === 2, r === 2 ? paltMarked : undefined)}
</p>
<span
className={`shrink-0 font-display text-[12px] font-semibold tabular-nums ${r === 2 ? "text-amber-700" : "text-stone-400"}`}
>
{r === 0 ? "基準" : `幅 ${total(w3)}`}
</span>
</div>
))}
</div>
<div className="space-y-5 px-4 py-5 sm:px-6">
<div>
<label htmlFor={`${uid}-t`} className="text-[14px] font-bold">
見出し文
<span className="ml-2 text-[12px] font-normal text-stone-500">
改行で2行目(4行まで)
</span>
</label>
<textarea
id={`${uid}-t`}
value={s.text}
rows={2}
onChange={(e) => update("text", normalizeText(e.target.value))}
className={`heading-input mt-2 block w-full resize-y border border-stone-300 bg-white p-3 text-[16px] leading-relaxed ${focusRing}`}
/>
<div className="mt-2 flex flex-wrap gap-2">
{EXAMPLES.map((ex) => (
<button
key={ex}
type="button"
aria-pressed={s.text === ex}
onClick={() => update("text", ex)}
className={`example min-h-9 border px-2.5 text-[13px] hover:border-[#d97706] hover:text-amber-800 ${s.text === ex ? "border-[#d97706] text-amber-800" : "border-stone-300 text-stone-700"} ${focusRing}`}
>
{ex.replace("\n", "/")}
</button>
))}
</div>
</div>
<div>
<label className="flex min-h-11 cursor-pointer items-center gap-3 text-[14px]">
<input
type="checkbox"
checked={s.palt}
onChange={(e) => update("palt", e.target.checked)}
aria-describedby={`${uid}-pr`}
className={`palt h-5 w-5 accent-[#d97706] ${focusRing}`}
/>
<span className="font-bold">
かなも詰める
<span className="ml-1 font-mono text-[12px] font-normal text-stone-500">
palt
</span>
</span>
</label>
<p
id={`${uid}-pr`}
aria-live="polite"
className={`palt-result ml-8 flex min-h-6 flex-wrap items-center gap-1.5 text-[13px] ${s.palt ? "text-amber-800" : "text-stone-600"}`}
>
<span>{paltText}</span>
{paltInfo && Math.abs(paltInfo.d) >= 0.5 && (
<>
<span className="sr-only">変わる字:</span>
{shownChanged.map((c) => (
<span
key={c}
className="border border-amber-300 bg-amber-50 px-1 font-bold text-amber-900"
>
{c}
</span>
))}
{moreChanged > 0 && <span>ほか{moreChanged}字</span>}
</>
)}
</p>
</div>
<div>
<div className="flex items-baseline justify-between">
<label htmlFor={`${uid}-s`} className="text-[14px] font-bold">
文字サイズ
</label>
<output
htmlFor={`${uid}-s`}
className="font-display text-[15px] font-semibold tabular-nums"
>
{s.size}px
</output>
</div>
<input
id={`${uid}-s`}
type="range"
min={SIZE_MIN}
max={SIZE_MAX}
step={1}
value={s.size}
onChange={(e) => update("size", Number(e.target.value))}
className={`mt-1 h-11 w-full cursor-pointer accent-[#d97706] ${focusRing}`}
/>
</div>
<fieldset>
<legend className="text-[14px] font-bold">フォント</legend>
<div className="mt-2 flex">
{(Object.keys(FONTS) as FontId[]).map((id) => (
<label key={id} className={segBtn(s.font === id)}>
<input
type="radio"
name={`${uid}-f`}
value={id}
checked={s.font === id}
onChange={() => update("font", id)}
className="sr-only"
/>
{FONTS[id].label}
</label>
))}
</div>
</fieldset>
<fieldset>
<legend className="text-[14px] font-bold">標本</legend>
<div className="mt-2 flex">
{(
[
["hero", "ヒーロー見出し"],
["card", "カード見出し"],
] as const
).map(([id, label]) => (
<label key={id} className={segBtn(s.view === id)}>
<input
type="radio"
name={`${uid}-v`}
value={id}
checked={s.view === id}
onChange={() => update("view", id)}
className="sr-only"
/>
{label}
</label>
))}
</div>
</fieldset>
{supportsNative && (
<label className="flex min-h-11 cursor-pointer items-center gap-3 text-[14px]">
<input
type="checkbox"
checked={forceSpan}
onChange={(e) => setForceSpan(e.target.checked)}
className={`force-span h-5 w-5 accent-[#d97706] ${focusRing}`}
/>
<span>③を span方式で描く(未対応ブラウザと同じ組み)</span>
</label>
)}
</div>
</div>
</div>
{/* 出力 */}
<div className="grid gap-5 border-t border-stone-200 px-4 py-5 sm:px-6 lg:grid-cols-[minmax(0,1fr)_20rem]">
<div className="min-w-0">
<label htmlFor={`${uid}-o`} className="text-[14px] font-bold">
HTML と CSS(@supports つき)
</label>
<textarea
id={`${uid}-o`}
ref={outRef}
readOnly
value={output}
rows={12}
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}`}
/>
</div>
<div className="flex flex-col">
<button
type="button"
onClick={() => copyText("code", output)}
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}`}
>
{copied === "ok" ? "コピー済み" : "HTML と CSS をコピー"}
</button>
<p
aria-live="polite"
className="copy-code-msg mt-1.5 min-h-5 text-[13px] leading-relaxed text-stone-600"
>
{copied === "ok" &&
"HTML は見出しの位置へ、style の中身は CSS へ貼れます"}
{copied === "fail" &&
"自動でコピーできませんでした。コード欄を選択したので Ctrl+C(⌘C)でコピーしてください"}
</p>
<button
type="button"
onClick={() => copyText("link", shareUrl)}
className={`copy-link 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}`}
>
{linkCopied === "ok"
? "リンクをコピーしました"
: "この見出しと設定のリンクをコピー"}
</button>
{linkCopied === "fail" && (
<>
<label htmlFor={`${uid}-l`} className="sr-only">
共有リンク
</label>
<input
id={`${uid}-l`}
ref={linkRef}
readOnly
value={shareUrl}
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="copy-link-msg mt-1.5 min-h-5 text-[13px] leading-relaxed text-stone-600"
>
{linkCopied === "ok" && "開くと同じ見出しと設定で3段が並びます"}
{linkCopied === "fail" &&
"自動でコピーできませんでした。上の欄を選択したので Ctrl+C(⌘C)でコピーしてください"}
</p>
<p className="mt-3 border-t border-stone-200 pt-3 text-[13px] leading-[1.75] text-stone-600">
span方式が詰める行頭は、文頭と改行(<br>)の直後だけです。自然な折り返しの行頭はネイティブ方式だけが詰めます。
</p>
</div>
</div>
</section>
);
}
const cardSize = (size: number) => Math.max(15, Math.round(size * 0.45));
function Overlay({ mark }: { mark?: Mark }) {
if (!mark) return null;
return (
<div aria-hidden className="pointer-events-none absolute inset-0">
{mark.lines.map((l, i) =>
l.x.map((x, j) => (
<span
key={`${i}-${j}`}
className="absolute w-px"
style={{
left: x,
top: l.top - 6,
height: l.bottom - l.top + 12,
background: AMBER,
opacity: j < 2 ? 1 : 0.7,
}}
/>
)),
)}
{mark.badges.map((b, i) => (
<span
key={i}
className="absolute whitespace-nowrap border border-[#d97706] bg-white px-1 py-px font-display text-[11px] font-semibold leading-none tabular-nums text-amber-800"
style={{
left: b.x,
top: b.y + 4,
transform: b.align === "center" ? "translateX(-50%)" : undefined,
}}
>
{fmt(b.d)}
</span>
))}
</div>
);
}
Add to your project via shadcn CLI
npx shadcn@latest add https://designs.first-ch.com/r/yakumono-spacing-compare.json