BLK-119Blocks

Inner vs Outer Noshi Preview: see where the gift paper sits when the box arrives (React)

A gift-wrapping preview that shows whether to put the noshi paper inside or outside the wrapping. Pick hand delivery or shipping and the occasion (year-end gift, New Year gift, return gift, thank-you, wedding gift) to get a recommendation, then drag one slider through wrap, arrive and open to see the layer order, what the recipient sees first and where the noshi appears when the box is opened. Shipping adds a sample delivery slip on top. The inscription is set vertically, the cord knot changes with the occasion, and you can switch the placement by hand. The state lives in the URL query so a shared link opens the same box. Includes a compact component (delivery, purpose, placement) to sit beside an order form. SVG and CSS custom properties only, no images.

Preview

内のし・外のし、届いた箱のどこにある?

配送の御歳暮は内のし

伝票や運ぶ途中の汚れからのし紙を守るため、包装紙の内側にかける内のしが目安です。

品物にのし紙をかけてから、包装紙で包みます

手渡しは外のし、配送は内のしが目安。用途・店舗・地域で異なります。

条件配送・御歳暮・内のし変える
渡し方
用途
のしの位置(手で切り替え)

重ねる順(下から)1品物2のし紙3包装紙

内のし・外のしの説明

内のしは品物にのし紙をかけてから包装し、外のしは包装した上にのし紙をかけます。手渡しは表書きが見える外のし、配送は伝票や汚れを避ける内のしが目安です。

水引は、何度あってもよいお祝い(御歳暮・御年賀・御礼・出産などの内祝)は蝶結び、結婚祝いは結び切りの図にしています。結婚の内祝も結び切りにします。

伝票の貼る位置は一例です。マナーの正誤を判定するものではなく、用途・店舗・地域で異なります。選んだ条件はURLにだけ入り、送信も保存もされません。

注文欄の横に置く(組み込み方)

図とスライダーと1行の目安だけの部品も同じファイルから出しています。選択欄は注文フォームの側に置き、値を props で渡します。

import { NoshiPlacementPreview } from "@/components/noshi-gift-preview";

// 注文フォームの「のし」欄の横に。選択値をそのまま渡す
<NoshiPlacementPreview
  delivery={form.delivery}      // "tewatashi" | "haisou"
  purpose={form.purpose}        // "oseibo" | "onenga" | "uchiiwai" | "orei" | "kekkon"
  placement={form.placement}    // "uchi" | "soto"(省略すると目安)
/>
delivery
"tewatashi" | "haisou"渡し方。配送のときは「届く」で伝票の層が乗る
purpose
"oseibo" | "onenga" | "uchiiwai" | "orei" | "kekkon"用途。表書きと水引の結び方が変わる
placement
"uchi" | "soto"内のし・外のし。省略すると渡し方と用途から目安を使う
initialStage
0 | 1 | 2 = 1最初に見せる段(包む・届く・開ける)
配送の御歳暮は 内のし伝票や運ぶ途中の汚れからのし紙を守るため、包装紙の内側にかける内のしが目安です。
Share on X

Read the full description

A gift-wrapping preview that shows whether to put the noshi paper inside or outside the wrapping. Pick hand delivery or shipping and the occasion (year-end gift, New Year gift, return gift, thank-you, wedding gift) to get a recommendation, then drag one slider through wrap, arrive and open to see the layer order, what the recipient sees first and where the noshi appears when the box is opened. Shipping adds a sample delivery slip on top. The inscription is set vertically, the cord knot changes with the occasion, and you can switch the placement by hand. The state lives in the URL query so a shared link opens the same box. Includes a compact component (delivery, purpose, placement) to sit beside an order form. SVG and CSS custom properties only, no images.

Added:
2026-11-18
Dependencies:
None
tags
#form #gift #noshi #japanese #svg #css-variables #range-slider #url-state #share #vertical-text #reduced-motion #no-image
"use client";

import { useEffect, useId, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent } from "react";
import { Montserrat } from "next/font/google";

const montserrat = Montserrat({ weight: ["600", "700"], subsets: ["latin"], display: "swap", preload: false });

/**
 * 内のし・外のしの早見図(渡し方と用途を選ぶと、箱を包む→届く→開けるの3段でのしの位置を見せる)BLK-119
 *
 * 差別化: exploded-layer-diagram は仕組みの層をスクロールで引き離して読む説明図、フォーム棚の既存は入力欄そのもの。
 * 本ブロックは「2つの選択 → 図と1行の目安」を返す判定フォームで、操作は工程のスライダー1本、状態はURLのクエリで共有する。
 * 英字の小見出し・見出しの「。」止め・末尾の矢印リンク・角丸・スクロール出現は使わない。
 *
 * 汎用技法メモ:
 * 1. **斜投影の箱は「面の行列」1つで描ける**。上面の (u, v) → 画面を matrix(1, 0, SX, SY, x, y) にすると、
 *    上面の絵(水引・表書き・包装紙の柄)は平らな座標で描いたまま箱に貼れる。縦書きの表書きも
 *    writing-mode: vertical-rl の SVG text をこの g に入れるだけで、上面に寝た向きになる。
 * 2. **3段の工程を CSS 変数 --p(0〜2)1本で配る**。A = clamp(0, p, 1)(重なる)と B = clamp(0, p − 1, 1)(外れる)を
 *    calc に書き、層 k を k·E·(1 − A) だけずらすと「包む」の分解図、外側の層だけ (1 − A + B) にすると「開ける」で
 *    元の位置へ戻っていく。React の再描画は値の書き換え1回で、各層は transform と opacity だけが動く。
 * 3. 一瞬だけ出す物(伝票・「最初に見える面」の枠)は opacity を clamp(0, min((p − s)/w, (e − p)/w), 1) の窓にする。
 * 4. ドラッグ中は transition を切って指に吸い付かせ、離した・目盛りを押したときだけ最寄りの段へ補間する。
 * 5. prefers-reduced-motion では motion-reduce:hidden / motion-reduce:grid で、スライダーの図の代わりに
 *    --p を 0・1・2 に固定した静止図3枚を並べる(JS で分岐しないので、描画のずれも出ない)。
 */

/* ------------------------------------------------------------------ データと判定 */

export type Delivery = "tewatashi" | "haisou";
export type Purpose = "oseibo" | "onenga" | "uchiiwai" | "orei" | "kekkon";
export type Placement = "uchi" | "soto";
export type NoshiState = { delivery: Delivery; purpose: Purpose; placement: Placement };

export const DELIVERIES: { id: Delivery; label: string }[] = [
  { id: "tewatashi", label: "手渡し" },
  { id: "haisou", label: "配送" },
];

export const PURPOSES: { id: Purpose; label: string; omote: string; knot: "chou" | "musubikiri" }[] = [
  { id: "oseibo", label: "御歳暮", omote: "御歳暮", knot: "chou" },
  { id: "onenga", label: "御年賀", omote: "御年賀", knot: "chou" },
  { id: "uchiiwai", label: "内祝", omote: "内祝", knot: "chou" },
  { id: "orei", label: "御礼", omote: "御礼", knot: "chou" },
  { id: "kekkon", label: "結婚祝い", omote: "寿", knot: "musubikiri" },
];

export const PLACEMENT_LABEL: Record<Placement, string> = { uchi: "内のし", soto: "外のし" };
const DELIVERY_LABEL: Record<Delivery, string> = { tewatashi: "手渡し", haisou: "配送" };
const purposeOf = (id: Purpose) => PURPOSES.find((x) => x.id === id) ?? PURPOSES[0];

export const DEFAULT_STATE: NoshiState = { delivery: "haisou", purpose: "oseibo", placement: "uchi" };

/** 渡し方と用途から決める初期値。内祝は控えめに贈る意味で内のし、ほかは手渡し=外・配送=内 */
export function recommend(delivery: Delivery, purpose: Purpose): Placement {
  if (purpose === "uchiiwai") return "uchi";
  return delivery === "haisou" ? "uchi" : "soto";
}

const isDelivery = (v: string | null): v is Delivery => v === "tewatashi" || v === "haisou";
const isPurpose = (v: string | null): v is Purpose => PURPOSES.some((x) => x.id === v);
const isPlacement = (v: string | null): v is Placement => v === "uchi" || v === "soto";

/** ?how=haisou&use=uchiiwai&place=uchi を読む。知らない値は既定に戻し、place が無ければ目安を使う */
export function parseQuery(search: string): NoshiState {
  const q = new URLSearchParams(search);
  const how = q.get("how");
  const use = q.get("use");
  const place = q.get("place");
  const delivery = isDelivery(how) ? how : DEFAULT_STATE.delivery;
  const purpose = isPurpose(use) ? use : DEFAULT_STATE.purpose;
  return { delivery, purpose, placement: isPlacement(place) ? place : recommend(delivery, purpose) };
}

export function toQuery(s: NoshiState): string {
  return `how=${s.delivery}&use=${s.purpose}&place=${s.placement}`;
}

/** 1行の目安。見出し(何を選んでいるか)・理由・目安から外したときの注意を返す */
export function advice(s: NoshiState): { head: string; line: string; note: string } {
  const rec = recommend(s.delivery, s.purpose);
  const p = purposeOf(s.purpose);
  const head = `${DELIVERY_LABEL[s.delivery]}の${p.label}は ${PLACEMENT_LABEL[s.placement]}`;
  let line: string;
  if (s.placement !== rec) {
    line =
      s.placement === "soto"
        ? s.delivery === "haisou"
          ? `目安は内のしです。外のしで配送すると、伝票がのし紙にかかったり、運ぶ途中で汚れたりすることがあります。`
          : `目安は内のしです。内祝を外のしで手渡すと、内祝だと一目で伝わります。`
        : `目安は外のしです。内のしで手渡すと、表書きは包装紙を開けるまで見えません。控えめに贈りたいときに選ばれます。`;
  } else if (s.purpose === "uchiiwai") {
    line =
      s.delivery === "haisou"
        ? "内祝は控えめに贈る意味もあり、配送なら汚れも避けられる内のしが目安です。"
        : "内祝は控えめに贈る意味で、手渡しでも内のしがよく選ばれます。";
  } else if (s.delivery === "haisou") {
    line = "伝票や運ぶ途中の汚れからのし紙を守るため、包装紙の内側にかける内のしが目安です。";
    if (s.purpose === "kekkon") line += "お祝いを表に見せたいときは、配送でも外のしにする店もあります。";
  } else {
    line = "渡すときに表書きが見えて、何の贈り物かすぐ伝わる外のしが目安です。";
  }
  return { head, line, note: "手渡しは外のし、配送は内のしが目安。用途・店舗・地域で異なります。" };
}

export type Stage = 0 | 1 | 2;
export const STAGES: { label: string }[] = [{ label: "包む" }, { label: "届く" }, { label: "開ける" }];

/** 段ごとの説明(図の下の1文) */
export function stageCaption(s: NoshiState, stage: Stage): string {
  const uchi = s.placement === "uchi";
  if (stage === 0) return uchi ? "品物にのし紙をかけてから、包装紙で包みます" : "品物を包装紙で包んでから、上にのし紙をかけます";
  if (stage === 1) {
    if (s.delivery === "haisou")
      return uchi ? "最初に見えるのは包装紙と伝票。のし紙は中で守られています" : "最初に見えるのは表書き。ただし伝票がのし紙にかかることがあります";
    return uchi ? "最初に見えるのは包装紙だけ。表書きは開けるまで見えません" : "手渡した瞬間に表書きが見え、何の贈り物か伝わります";
  }
  return uchi ? "包装紙を外すと、のし紙が出てきます" : "のし紙は包装紙と一緒に外れます。表書きは届いたときから見えています";
}

/** 下から重ねる順 */
export function layerOrder(placement: Placement): LayerId[] {
  return placement === "uchi" ? ["item", "noshi", "wrap"] : ["item", "wrap", "noshi"];
}

/* ------------------------------------------------------------------ 図(斜投影の箱・--p で動く) */

type LayerId = "item" | "noshi" | "wrap";
const LAYER_NAME: Record<LayerId, string> = { item: "品物", noshi: "のし紙", wrap: "包装紙" };

const W = 250; // 箱の幅
const D = 140; // 奥行き
const H = 54; // 高さ
const SX = -0.22; // 奥行き1あたりの横ずれ(奥ほど右)
const SY = 0.78; // 奥行きの縮み
const EX = 62; // 分解したときの1層ぶんのずれ
const EY = -176;
const SHU = "#cf3a24"; // 朱
const SUMI = "#1c1917"; // 墨
const AMBER = "#d97706";
const HAIR = "#a8a29e";
const PAD = 14;

/** 品物の上面の奥・左の角を原点にした画面座標 */
const P = (u: number, v: number, y: number): [number, number] => [u + v * SX, y + v * SY];
const pts = (list: [number, number][]) => list.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(" ");

type Geo = { m: number; top: number; h: number };
/** 層ごとの形(m: 品物からのはみ出し、top: 品物の上面からの高さ、h: 厚み)。重ね順で包装紙の高さが変わる */
function geometry(placement: Placement): Record<LayerId, Geo> {
  if (placement === "uchi") {
    return { item: { m: 0, top: 0, h: H }, noshi: { m: 0.8, top: -1.6, h: 12 }, wrap: { m: 4, top: -5, h: H + 5 } };
  }
  return { item: { m: 0, top: 0, h: H }, wrap: { m: 4, top: -4, h: H + 4 }, noshi: { m: 4.8, top: -5.6, h: 12 } };
}

function boxPolys(g: Geo) {
  const { m, top: y, h } = g;
  const a = P(-m, -m, y);
  const b = P(W + m, -m, y);
  const c = P(W + m, D + m, y);
  const d = P(-m, D + m, y);
  return {
    top: pts([a, b, c, d]),
    front: pts([d, c, [c[0], c[1] + h], [d[0], d[1] + h]]),
    right: pts([b, c, [c[0], c[1] + h], [b[0], b[1] + h]]),
    faceMatrix: `matrix(1 0 ${SX} ${SY} ${a[0].toFixed(2)} ${a[1].toFixed(2)})`,
    w: W + 2 * m,
    d: D + 2 * m,
    frontLeft: d,
  };
}

// viewBox: 「包む」の分解(3層)と、伝票の浮き上がりが収まる範囲
const VB = (() => {
  const xs: number[] = [];
  const ys: number[] = [];
  for (let k = 0; k < 3; k++) {
    for (const [u, v, y] of [
      [-6, -6, -8],
      [W + 6, -6, -8],
      [W + 6, D + 6, H],
      [-6, D + 6, H],
    ] as const) {
      const [x, yy] = P(u, v, y);
      xs.push(x + k * EX);
      ys.push(yy + k * EY);
    }
  }
  const x0 = Math.min(...xs) - PAD - 18;
  const y0 = Math.min(...ys) - PAD - 6;
  const x1 = Math.max(...xs) + PAD;
  const y1 = Math.max(...ys) + PAD + 22;
  return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
})();

const A = "clamp(0, var(--p), 1)";
const B = "clamp(0, calc(var(--p) - 1), 1)";
const shift = (k: number, outer: boolean): CSSProperties => {
  const f = outer ? `(1 - ${A} + ${B})` : `(1 - ${A})`;
  return { transform: `translate(calc(${EX * k}px * ${f}), calc(${EY * k}px * ${f}))` };
};
/** 「包む」で出て、外側の層は「開ける」でもう一度出る番号 */
const markerOpacity = (outer: boolean): CSSProperties => ({
  opacity: outer ? "max(clamp(0, calc(1 - var(--p) * 1.6), 1), clamp(0, calc((var(--p) - 1.45) * 2), 1))" : "clamp(0, calc(1 - var(--p) * 1.6), 1)",
});
const windowOpacity = (s: number, e: number, w: number): CSSProperties => ({
  opacity: `clamp(0, min(calc((var(--p) - ${s}) / ${w}), calc((${e} - var(--p)) / ${w})), 1)`,
});

const MOVE = "transition-[transform,opacity] duration-500 ease-[cubic-bezier(.2,.8,.2,1)] group-data-[drag=true]/fig:duration-0 motion-reduce:transition-none";

function NoshiFace({ w, d, omote, knot }: { w: number; d: number; omote: string; knot: "chou" | "musubikiri" }) {
  const cx = w / 2;
  const kv = d * 0.66;
  const n = [...omote].length;
  const fs = Math.min(n === 1 ? 32 : 24, (kv - 32) / (n * 1.12));
  return (
    <g>
      <rect width={w} height={d} fill="#fff" stroke={HAIR} strokeWidth={0.8} vectorEffect="non-scaling-stroke" />
      {/* 水引: 箱を横に回る帯。濃い色(朱)を右、白を左に置く */}
      {[-4, -1.5, 1, 3.5].map((o) => (
        <g key={o}>
          <line x1={0} y1={kv + o} x2={cx} y2={kv + o} stroke={HAIR} strokeWidth={2} />
          <line x1={0} y1={kv + o} x2={cx} y2={kv + o} stroke="#fff" strokeWidth={1} />
          <line x1={cx} y1={kv + o} x2={w} y2={kv + o} stroke={SHU} strokeWidth={1.4} />
        </g>
      ))}
      {knot === "chou" ? (
        <g>
          <ellipse cx={cx - 19} cy={kv - 7} rx={17} ry={7.5} transform={`rotate(-14 ${cx - 19} ${kv - 7})`} fill="none" stroke={HAIR} strokeWidth={3} />
          <ellipse cx={cx - 19} cy={kv - 7} rx={17} ry={7.5} transform={`rotate(-14 ${cx - 19} ${kv - 7})`} fill="none" stroke="#fff" strokeWidth={1.6} />
          <ellipse cx={cx + 19} cy={kv - 7} rx={17} ry={7.5} transform={`rotate(14 ${cx + 19} ${kv - 7})`} fill="none" stroke={SHU} strokeWidth={2.6} />
          <line x1={cx - 3} y1={kv + 3} x2={cx - 14} y2={kv + 22} stroke={HAIR} strokeWidth={2.4} />
          <line x1={cx + 3} y1={kv + 3} x2={cx + 14} y2={kv + 22} stroke={SHU} strokeWidth={2} />
          <rect x={cx - 5} y={kv - 6} width={10} height={11} fill={SHU} />
        </g>
      ) : (
        <g>
          <rect x={cx - 12} y={kv - 7} width={12} height={13} fill="#fff" stroke={HAIR} strokeWidth={0.9} vectorEffect="non-scaling-stroke" />
          <rect x={cx} y={kv - 7} width={12} height={13} fill={SHU} />
          <line x1={cx - 4} y1={kv + 6} x2={cx - 16} y2={kv + 20} stroke={HAIR} strokeWidth={2.2} />
          <line x1={cx + 4} y1={kv + 6} x2={cx + 16} y2={kv + 20} stroke={SHU} strokeWidth={2} />
        </g>
      )}
      {/* 熨斗(右上の飾り) */}
      <g transform={`translate(${w - 24} ${15}) rotate(-24)`}>
        <polygon points="0,-11 5,-6 5,11 0,14 -5,11 -5,-6" fill="#fff" stroke={SUMI} strokeWidth={0.9} />
        <rect x={-1.6} y={-5} width={3.2} height={13} fill={SHU} />
      </g>
      {/* 表書き(縦書き・名入れは作らない) */}
      <text
        x={cx}
        y={10}
        fill={SUMI}
        fontSize={fs}
        fontWeight={700}
        letterSpacing={n === 1 ? 0 : fs * 0.1}
        style={{ writingMode: "vertical-rl", fontFamily: "'Hiragino Mincho ProN','Yu Mincho','Noto Serif JP','Noto Sans JP',serif" }}
      >
        {omote}
      </text>
    </g>
  );
}

function WrapFace({ w, d, pid }: { w: number; d: number; pid: string }) {
  return (
    <g>
      <rect width={w} height={d} fill={`url(#${pid})`} stroke={HAIR} strokeWidth={0.8} vectorEffect="non-scaling-stroke" />
      {/* 斜め包みの合わせ目 */}
      <polyline points={`0,${d * 0.34} ${w * 0.62},${d} `} fill="none" stroke="#c9a77a" strokeWidth={0.9} vectorEffect="non-scaling-stroke" />
      <polyline points={`${w * 0.36},0 ${w},${d * 0.7}`} fill="none" stroke="#c9a77a" strokeWidth={0.9} vectorEffect="non-scaling-stroke" />
    </g>
  );
}

function ItemFace({ w, d }: { w: number; d: number }) {
  return (
    <g>
      <rect width={w} height={d} fill="#f5f5f4" stroke={HAIR} strokeWidth={0.8} vectorEffect="non-scaling-stroke" />
      <rect x={12} y={10} width={w - 24} height={d - 20} fill="none" stroke="#d6d3d1" strokeWidth={0.8} vectorEffect="non-scaling-stroke" />
    </g>
  );
}

const SIDE: Record<LayerId, [string, string]> = {
  item: ["#e7e5e4", "#d6d3d1"],
  noshi: ["#fafaf9", "#f0eeec"],
  wrap: ["#fdf3e3", "#f6e3c6"],
};

/** 箱の図。p(0=包む・1=届く・2=開ける)は親が --p で渡す */
export function NoshiBox({ state, className = "" }: { state: NoshiState; className?: string }) {
  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");
  const pid = `wrap-${uid}`;
  const geo = geometry(state.placement);
  const order = layerOrder(state.placement);
  const inner = new Set<LayerId>(state.placement === "uchi" ? ["item", "noshi"] : ["item"]);
  const p = purposeOf(state.purpose);
  const topGeo = geo[order[2]];
  const topPoly = boxPolys(topGeo);
  // 伝票: 一番上の面の手前右に貼る(貼り方の一例)
  const sg: Geo = { m: 0, top: topGeo.top - 1.2, h: 1.2 };
  const su0 = W * 0.47;
  const su1 = W * 0.9;
  const sv0 = D * 0.56;
  const sv1 = D * 0.94;
  const slip = pts([P(su0, sv0, sg.top), P(su1, sv0, sg.top), P(su1, sv1, sg.top), P(su0, sv1, sg.top)]);
  const slipMatrix = (() => {
    const o = P(su0, sv0, sg.top);
    return `matrix(1 0 ${SX} ${SY} ${o[0].toFixed(2)} ${o[1].toFixed(2)})`;
  })();
  const sw = su1 - su0;
  const sd = sv1 - sv0;
  const bottomRight = P(W, D, H);

  return (
    <svg viewBox={`${VB.x.toFixed(1)} ${VB.y.toFixed(1)} ${VB.w.toFixed(1)} ${VB.h.toFixed(1)}`} className={`block h-auto w-full ${className}`} aria-hidden="true">
      <defs>
        <pattern id={pid} width={18} height={18} patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
          <rect width={18} height={18} fill="#fffaf2" />
          <line x1={0} y1={0} x2={0} y2={18} stroke={AMBER} strokeOpacity={0.28} strokeWidth={1.2} />
          <circle cx={9} cy={9} r={1.4} fill={AMBER} fillOpacity={0.45} />
        </pattern>
      </defs>
      {/* 床の影 */}
      <polygon points={pts([P(-10, D + 12, H + 2), P(W + 14, D + 12, H + 2), P(W + 8, D + 20, H + 6), P(-16, D + 20, H + 6)])} fill="#f5f5f4" />
      {order.map((id, k) => {
        const g = geo[id];
        const b = boxPolys(g);
        const outer = !inner.has(id);
        return (
          <g key={id} data-layer={id} className={MOVE} style={shift(k, outer)}>
            <polygon points={b.right} fill={SIDE[id][1]} stroke={HAIR} strokeWidth={0.8} vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
            <polygon points={b.front} fill={SIDE[id][0]} stroke={HAIR} strokeWidth={0.8} vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
            <g transform={b.faceMatrix}>
              {id === "item" && <ItemFace w={b.w} d={b.d} />}
              {id === "wrap" && <WrapFace w={b.w} d={b.d} pid={pid} />}
              {id === "noshi" && <NoshiFace w={b.w} d={b.d} omote={p.omote} knot={p.knot} />}
            </g>
            <g className={MOVE} style={markerOpacity(outer)}>
              <rect x={b.frontLeft[0] - 26} y={b.frontLeft[1] - 9} width={20} height={20} fill={AMBER} />
              <text x={b.frontLeft[0] - 16} y={b.frontLeft[1] + 6} fill="#fff" fontSize={14} fontWeight={700} textAnchor="middle" className={montserrat.className}>
                {k + 1}
              </text>
            </g>
          </g>
        );
      })}

      {/* 届いたときに最初に見える面 */}
      <g className={MOVE} style={windowOpacity(0.7, 1.3, 0.22)}>
        <polygon points={topPoly.top} fill="none" stroke={AMBER} strokeWidth={2} strokeDasharray="6 4" vectorEffect="non-scaling-stroke" />
        <text x={P(0, -topGeo.m, topGeo.top)[0]} y={P(0, -topGeo.m, topGeo.top)[1] - 12} fill="#b45309" fontSize={15} fontWeight={700}>
          最初に見える面
        </text>
      </g>

      {state.delivery === "haisou" && (
        <g className={MOVE} style={shift(2, true)}>
          <g
            className={MOVE}
            style={{
              ...windowOpacity(0.55, 1.35, 0.25),
              transform: `translate(calc(36px * clamp(0, calc((var(--p) - 1) / 0.35), 1)), calc(-56px * (1 - clamp(0, calc((var(--p) - 0.55) / 0.4), 1)) - 60px * clamp(0, calc((var(--p) - 1) / 0.35), 1)))`,
            }}
          >
            <polygon points={slip} fill="#fff" stroke={SUMI} strokeWidth={1} vectorEffect="non-scaling-stroke" />
            <g transform={slipMatrix}>
              <rect x={6} y={5} width={sw * 0.3} height={7} fill={AMBER} fillOpacity={0.85} />
              {[17, 25, 33, 41].map((y) => (
                <line key={y} x1={6} y1={y} x2={sw - 8} y2={y} stroke={HAIR} strokeWidth={1} vectorEffect="non-scaling-stroke" />
              ))}
              <line x1={sw * 0.55} y1={sd * 0.12} x2={sw * 0.55} y2={sd * 0.3} stroke={HAIR} strokeWidth={1} vectorEffect="non-scaling-stroke" />
            </g>
          </g>
          <text
            x={bottomRight[0]}
            y={bottomRight[1] + 26}
            fill="#57534e"
            fontSize={14}
            textAnchor="end"
            className={MOVE}
            style={windowOpacity(0.65, 1.3, 0.2)}
          >
            伝票の貼る位置は一例です
          </text>
        </g>
      )}
    </svg>
  );
}

/* ------------------------------------------------------------------ スライダーと1行の目安 */

function StageSlider({ p, onChange, onSettle, label }: { p: number; onChange: (v: number) => void; onSettle: (s: Stage) => void; label: string }) {
  const stage = Math.round(p) as Stage;
  const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
    const d = e.key === "ArrowRight" || e.key === "ArrowUp" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowDown" ? -1 : 0;
    if (e.key === "Home" || e.key === "End") {
      e.preventDefault();
      onSettle(e.key === "Home" ? 0 : 2);
      return;
    }
    if (!d) return;
    e.preventDefault();
    onSettle(Math.max(0, Math.min(2, stage + d)) as Stage);
  };
  return (
    <div>
      <input
        type="range"
        min={0}
        max={200}
        step={1}
        value={Math.round(p * 100)}
        aria-label={label}
        aria-valuetext={STAGES[stage].label}
        onChange={(e) => onChange(Number(e.target.value) / 100)}
        onPointerUp={() => onSettle(stage)}
        onKeyDown={onKey}
        className="stage-range block h-11 w-full cursor-pointer appearance-none bg-transparent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706] [&::-moz-range-thumb]:h-6 [&::-moz-range-thumb]:w-6 [&::-moz-range-thumb]:rounded-none [&::-moz-range-thumb]:border-2 [&::-moz-range-thumb]:border-white [&::-moz-range-thumb]:bg-[#d97706] [&::-moz-range-track]:h-[3px] [&::-moz-range-track]:bg-stone-300 [&::-webkit-slider-runnable-track]:h-[3px] [&::-webkit-slider-runnable-track]:bg-stone-300 [&::-webkit-slider-thumb]:-mt-[10.5px] [&::-webkit-slider-thumb]:h-6 [&::-webkit-slider-thumb]:w-6 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-white [&::-webkit-slider-thumb]:bg-[#d97706] [&::-webkit-slider-thumb]:shadow-[0_0_0_1px_#b45309]"
      />
      <div className="grid grid-cols-3 text-[13px] font-bold">
        {STAGES.map((s, i) => (
          <button
            key={s.label}
            type="button"
            data-stage={i}
            aria-pressed={stage === i}
            onClick={() => onSettle(i as Stage)}
            className={`min-h-11 px-1 transition-colors duration-200 motion-reduce:transition-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#d97706] ${
              i === 0 ? "text-left" : i === 1 ? "text-center" : "text-right"
            } ${stage === i ? "text-[#b45309]" : "text-stone-500 hover:text-stone-800"}`}
          >
            <span className={`${montserrat.className} mr-1 text-[11px] tabular-nums`}>{i + 1}</span>
            {s.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function useStage(initial: number) {
  const [p, setP] = useState(initial);
  const [drag, setDrag] = useState(false);
  return {
    p,
    drag,
    onChange: (v: number) => {
      setDrag(true);
      setP(v);
    },
    onSettle: (s: Stage) => {
      setDrag(false);
      setP(s);
    },
  };
}

function StaticStrip({ state }: { state: NoshiState }) {
  return (
    <div className="@container hidden motion-reduce:block">
      <ol className="grid gap-4 @xl:grid-cols-3">
        {STAGES.map((s, i) => (
          <li key={s.label} className="border-t border-stone-200 pt-2" style={{ "--p": i } as CSSProperties}>
            <p className="text-[13px] font-bold text-stone-900">
              <span className={`${montserrat.className} mr-1 text-[11px] text-[#b45309]`}>{i + 1}</span>
              {s.label}
            </p>
            <NoshiBox state={state} className="mt-1" />
            <p className="mt-1 text-[12.5px] leading-[1.7] text-stone-600">{stageCaption(state, i as Stage)}</p>
          </li>
        ))}
      </ol>
    </div>
  );
}

/**
 * 注文欄の横に置く版。図とスライダーと1行の目安だけを出す(選択欄は注文フォームの側にある前提)
 */
export function NoshiPlacementPreview({
  delivery = "haisou",
  purpose = "oseibo",
  placement,
  initialStage = 1,
}: {
  delivery?: Delivery;
  purpose?: Purpose;
  /** 省略すると渡し方と用途から目安を使う */
  placement?: Placement;
  initialStage?: Stage;
}) {
  const state: NoshiState = { delivery, purpose, placement: placement ?? recommend(delivery, purpose) };
  const st = useStage(initialStage);
  const a = advice(state);
  return (
    <figure className="@container w-full max-w-sm border-y border-stone-200 bg-white py-3 text-stone-900">
      <div className="motion-reduce:hidden">
        <div className="group/fig" data-drag={st.drag} style={{ "--p": st.p } as CSSProperties}>
          <NoshiBox state={state} />
        </div>
        <StageSlider p={st.p} onChange={st.onChange} onSettle={st.onSettle} label="箱の段階(包む・届く・開ける)" />
      </div>
      <StaticStrip state={state} />
      <figcaption className="mt-2 text-[14px] leading-[1.7]">
        <span className="font-bold">{a.head}</span>
        <span className="mt-0.5 block text-[12.5px] text-stone-600">{a.line}</span>
      </figcaption>
    </figure>
  );
}

/* ------------------------------------------------------------------ 本体(ギャラリーの見本) */

const noopSubscribe = () => () => {};
const readSearch = () => window.location.search;
const serverSearch = () => "";
const readPage = () => window.location.origin + window.location.pathname;

const USAGE = `import { NoshiPlacementPreview } from "@/components/noshi-gift-preview";

// 注文フォームの「のし」欄の横に。選択値をそのまま渡す
<NoshiPlacementPreview
  delivery={form.delivery}      // "tewatashi" | "haisou"
  purpose={form.purpose}        // "oseibo" | "onenga" | "uchiiwai" | "orei" | "kekkon"
  placement={form.placement}    // "uchi" | "soto"(省略すると目安)
/>`;

const PROPS: [string, string, string][] = [
  ["delivery", '"tewatashi" | "haisou"', "渡し方。配送のときは「届く」で伝票の層が乗る"],
  ["purpose", '"oseibo" | "onenga" | "uchiiwai" | "orei" | "kekkon"', "用途。表書きと水引の結び方が変わる"],
  ["placement", '"uchi" | "soto"', "内のし・外のし。省略すると渡し方と用途から目安を使う"],
  ["initialStage", "0 | 1 | 2 = 1", "最初に見せる段(包む・届く・開ける)"],
];

export default function NoshiGiftPreview({ headingTag: Heading = "h2" }: { headingTag?: "h1" | "h2" | "p" }) {
  const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");
  const search = useSyncExternalStore(noopSubscribe, readSearch, serverSearch);
  const [picked, setPicked] = useState<NoshiState | null>(null);
  const state = picked ?? parseQuery(search);
  const st = useStage(0);
  const [copied, setCopied] = useState("");
  const timer = useRef(0);
  const page = useSyncExternalStore(noopSubscribe, readPage, serverSearch);

  useEffect(() => {
    const t = timer;
    return () => window.clearTimeout(t.current);
  }, []);

  const href = page ? `${page}?${toQuery(state)}` : "";

  const update = (next: NoshiState) => {
    setPicked(next);
    const url = new URL(window.location.href);
    url.search = toQuery(next);
    window.history.replaceState(window.history.state, "", url);
  };
  const pickCondition = (patch: Partial<Pick<NoshiState, "delivery" | "purpose">>) => {
    const d = patch.delivery ?? state.delivery;
    const u = patch.purpose ?? state.purpose;
    // 条件を変えたら、のしの位置は目安に戻す
    update({ delivery: d, purpose: u, placement: recommend(d, u) });
  };

  const copy = async (key: string, text: string) => {
    let ok = false;
    try {
      await navigator.clipboard.writeText(text);
      ok = true;
    } catch {
      ok = false;
    }
    setCopied(ok ? key : "fail");
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setCopied(""), 1800);
  };

  const a = advice(state);
  const rec = recommend(state.delivery, state.purpose);
  const order = layerOrder(state.placement);
  const shareText = `${a.head}? 箱を開けると、のしがどこにあるか見られる図`;

  const seg = (on: boolean) =>
    `min-h-11 border px-3 text-[14px] font-bold transition-colors duration-150 motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706] ${
      on ? "border-stone-900 bg-stone-900 text-white" : "border-stone-300 bg-white text-stone-700 hover:border-stone-900"
    }`;

  return (
    <section aria-labelledby={`${uid}-h`} className="@container w-full max-w-5xl border-y border-stone-200 bg-white px-4 py-6 text-stone-900 sm:px-8 sm:py-8">
      <div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1">
        <Heading id={`${uid}-h`} className="text-[clamp(1.3rem,3.6vw,1.8rem)] leading-[1.35] font-bold tracking-[0.01em]">
          内のし・外のし、届いた箱のどこにある?
        </Heading>
        <p className="hidden text-[13px] text-stone-500 @lg:block">スライダーで 包む・届く・開ける</p>
      </div>

      {/* 狭い幅は 目安 → 図とスライダー → 条件と共有 の順。広い幅は左に図、右に目安と条件 */}
      <div className="mt-3 grid gap-x-8 gap-y-3 border-t border-stone-200 pt-3 @2xl:mt-4 @2xl:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)] @2xl:grid-rows-[auto_1fr] @2xl:pt-5">
        {/* 結果(1行の目安) */}
        <div className="result @2xl:col-start-2 @2xl:row-start-1">
          <p className="hidden text-[13px] font-bold text-stone-500 @2xl:block">のしの位置の目安</p>
          <p className="text-[clamp(1.3rem,4.2vw,1.75rem)] leading-[1.3] font-bold @2xl:mt-1">
            {DELIVERY_LABEL[state.delivery]}の{purposeOf(state.purpose).label}は
            <span className="ml-1.5 inline-block border-b-[3px] border-[#d97706] whitespace-nowrap">{PLACEMENT_LABEL[state.placement]}</span>
          </p>
          <p className="mt-1.5 text-[14.5px] leading-[1.7] text-stone-800 @2xl:mt-2 @2xl:text-[15px]">{a.line}</p>
          <p className="mt-1 hidden text-[12.5px] leading-[1.7] text-stone-500 @2xl:block">{a.note}</p>
        </div>

        {/* 図とスライダー(入力1つ) */}
        <div className="@2xl:col-start-1 @2xl:row-span-2 @2xl:row-start-1">
          <div className="motion-reduce:hidden">
            <div className="fig group/fig mx-auto max-w-[30rem]" data-drag={st.drag} style={{ "--p": st.p } as CSSProperties}>
              <NoshiBox state={state} />
            </div>
            <div className="main-stage mx-auto max-w-[30rem]">
              <StageSlider p={st.p} onChange={st.onChange} onSettle={st.onSettle} label="箱の段階(包む・届く・開ける)" />
              <p className="mt-2 min-h-[3.2em] text-[13.5px] leading-[1.7] text-stone-700" aria-live="polite">
                {stageCaption(state, Math.round(st.p) as Stage)}
              </p>
            </div>
          </div>
          <StaticStrip state={state} />
        </div>

        {/* 既定値で畳んだ条件・重ね順・共有 */}
        <div className="@2xl:col-start-2 @2xl:row-start-2">
          <p className="text-[12.5px] leading-[1.7] text-stone-500 @2xl:hidden">{a.note}</p>
          <details className="cond group mt-3 border-y border-stone-200 @2xl:mt-1">
            <summary className="flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 text-[14px] marker:content-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#d97706] [&::-webkit-details-marker]:hidden">
              <span>
                <span className="text-stone-500">条件</span>
                <span className="ml-2 font-bold">
                  {DELIVERY_LABEL[state.delivery]}・{purposeOf(state.purpose).label}・{PLACEMENT_LABEL[state.placement]}
                </span>
              </span>
              <span className="text-[13px] font-bold text-[#b45309] group-open:hidden">変える</span>
              <span className="hidden text-[13px] font-bold text-stone-500 group-open:inline">閉じる</span>
            </summary>
            <div className="space-y-4 pb-4">
              <fieldset>
                <legend className="text-[13px] font-bold text-stone-600">渡し方</legend>
                <div className="mt-1.5 grid grid-cols-2 gap-2">
                  {DELIVERIES.map((d) => (
                    <button key={d.id} type="button" data-how={d.id} aria-pressed={state.delivery === d.id} onClick={() => pickCondition({ delivery: d.id })} className={seg(state.delivery === d.id)}>
                      {d.label}
                    </button>
                  ))}
                </div>
              </fieldset>
              <fieldset>
                <legend className="text-[13px] font-bold text-stone-600">用途</legend>
                <div className="mt-1.5 grid grid-cols-3 gap-2 @lg:grid-cols-5 @3xl:grid-cols-3">
                  {PURPOSES.map((u) => (
                    <button key={u.id} type="button" data-use={u.id} aria-pressed={state.purpose === u.id} onClick={() => pickCondition({ purpose: u.id })} className={seg(state.purpose === u.id)}>
                      {u.label}
                    </button>
                  ))}
                </div>
              </fieldset>
              <fieldset>
                <legend className="text-[13px] font-bold text-stone-600">のしの位置(手で切り替え)</legend>
                <div className="mt-1.5 grid grid-cols-2 gap-2">
                  {(["uchi", "soto"] as Placement[]).map((pl) => (
                    <button
                      key={pl}
                      type="button"
                      data-place={pl}
                      aria-pressed={state.placement === pl}
                      onClick={() => update({ ...state, placement: pl })}
                      className={seg(state.placement === pl)}
                    >
                      {PLACEMENT_LABEL[pl]}
                      {pl === rec && <span className="ml-1 text-[11px] font-normal opacity-80">(目安)</span>}
                    </button>
                  ))}
                </div>
              </fieldset>
            </div>
          </details>

          <p className="mt-4 text-[13px] text-stone-600">
            重ねる順(下から)
            {order.map((id, i) => (
              <span key={id} className="ml-2 inline-flex items-center gap-1 font-bold text-stone-900">
                <span className={`${montserrat.className} inline-flex h-4 w-4 items-center justify-center bg-[#d97706] text-[10px] text-white`}>{i + 1}</span>
                {LAYER_NAME[id]}
              </span>
            ))}
          </p>

          {/* 共有: この箱と目安をURLで送る */}
          <div className="share mt-5 border-t border-stone-200 pt-4">
            <p className="text-[13px] font-bold text-stone-600">同じ箱をURLで送る</p>
            <div className="mt-2 grid grid-cols-2 gap-2">
              <button
                type="button"
                data-copy="url"
                onClick={() => copy("url", href || window.location.href)}
                className="min-h-11 bg-[#d97706] px-3 text-[14px] font-bold text-white transition-colors duration-150 hover:bg-[#b45309] motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]"
              >
                {copied === "url" ? "コピーしました" : "URLをコピー"}
              </button>
              <a
                href={href ? `https://social-plugins.line.me/lineit/share?url=${encodeURIComponent(href)}` : undefined}
                target="_blank"
                rel="noopener noreferrer"
                className="flex min-h-11 items-center justify-center border border-stone-900 px-3 text-[14px] font-bold text-stone-900 transition-colors duration-150 hover:bg-stone-100 motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]"
              >
                LINEで送る
              </a>
            </div>
            <a
              href={href ? `https://x.com/intent/post?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(href)}` : undefined}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-2 inline-flex min-h-11 items-center text-[13px] font-bold text-stone-600 underline underline-offset-4 hover:text-stone-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]"
            >
              Xに投稿する
            </a>
            <p className="min-h-[1.4em] text-[12px] text-stone-500" aria-live="polite">
              {copied === "fail" ? "コピーできませんでした。アドレス欄のURLをそのまま送れます" : ""}
            </p>
          </div>
        </div>
      </div>

      <details className="mt-4 border-t border-stone-200 pt-3 text-[13px] leading-[1.8] text-stone-600">
        <summary className="min-h-11 cursor-pointer font-bold text-stone-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]">内のし・外のしの説明</summary>
        <p>内のしは品物にのし紙をかけてから包装し、外のしは包装した上にのし紙をかけます。手渡しは表書きが見える外のし、配送は伝票や汚れを避ける内のしが目安です。</p>
        <p className="mt-1">水引は、何度あってもよいお祝い(御歳暮・御年賀・御礼・出産などの内祝)は蝶結び、結婚祝いは結び切りの図にしています。結婚の内祝も結び切りにします。</p>
        <p className="mt-1">伝票の貼る位置は一例です。マナーの正誤を判定するものではなく、用途・店舗・地域で異なります。選んだ条件はURLにだけ入り、送信も保存もされません。</p>
      </details>

      <details className="mt-1 border-t border-stone-200 pt-3 text-[13px] leading-[1.8] text-stone-600">
        <summary className="min-h-11 cursor-pointer font-bold text-stone-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#d97706]">注文欄の横に置く(組み込み方)</summary>
        <div className="grid gap-6 @3xl:grid-cols-[minmax(0,1fr)_18rem]">
          <div>
            <p>図とスライダーと1行の目安だけの部品も同じファイルから出しています。選択欄は注文フォームの側に置き、値を props で渡します。</p>
            <pre className="mt-2 overflow-x-auto border border-stone-200 bg-stone-50 p-3 text-[11.5px] leading-[1.7] text-stone-800">
              <code>{USAGE}</code>
            </pre>
            <dl className="mt-3 divide-y divide-stone-200 border-y border-stone-200">
              {PROPS.map(([n, t, note]) => (
                <div key={n} className="grid gap-x-4 py-2 @lg:grid-cols-[7rem_minmax(0,1fr)]">
                  <dt className="font-mono text-[12px] font-bold text-stone-900">{n}</dt>
                  <dd className="text-[12.5px]">
                    <code className="text-[11.5px] text-[#b45309]">{t}</code>
                    <span className="block">{note}</span>
                  </dd>
                </div>
              ))}
            </dl>
          </div>
          <NoshiPlacementPreview delivery={state.delivery} purpose={state.purpose} placement={state.placement} />
        </div>
      </details>
    </section>
  );
}

Add to your project via shadcn CLI

npx shadcn@latest add https://designs.first-ch.com/r/noshi-gift-preview.json