3D製品コンフィギュレーター(部位を選んで色と素材を替える)
製品を部位ごとに選んで色と素材を組み立てる、3Dの製品コンフィギュレーター。抽象形状のラウンジチェア(座面・背もたれ・肘掛け・脚の4部位)を画面上でクリックするか部位ボタンで選び、5色の色見本と3種の素材(つや・マット・布)を切り替えると、右の構成表に部位ごとの色・素材・加算額、合計の目安と納期の目安が同時に反映され、変更した行と合計が短く光る。スマートフォン幅では構成表が操作欄の下に回るため、合計と納期だけを画面下に貼り付けて操作中も見えるようにしている。入力の正は本物のラジオボタン(fieldset と legend)で、矢印キーでの移動・読み上げ・無効化(脚には布を選べない)がブラウザの標準動作のまま揃うため、キーボードだけで操作が完結する。3D側のクリックは Raycaster で部位を拾う近道で、選んだ部位は一回り大きい裏面の複製(反転ハル)でアンバーに縁取られ、部位ボタンの下線・構成表の該当行・引き出し線つきの部位ラベルも同じアンバーでそろえる。その部位が見やすい角度へ椅子が向きを変えて小さく浮き上がる。椅子は角を大きく丸めた箱を頂点単位で押し出して座面と背もたれの中央を膨らませ、脚は肘掛けの真下に通して1本の柱として床まで続く形にしている。素材は1つの MeshPhysicalMaterial のパラメータ差し替えで作り、つやは低い粗さとクリアコート、マットは高い粗さ、布はシーン(毛足の照り)と、64pxの canvas に糸の丸みをグラデーションで描いた籠目の bumpMap で表す。UV は面の向きごとに位置から振り直すので、座面の上面でも側面でも織り目の大きさがそろう。映り込みは白い部屋と発光板を PMREMGenerator で畳んだ環境マップ、影は ShadowMaterial の床と、椅子の下に敷いた放射グラデーションの接地影で、画像・モデルファイルは一切使わない。色見本の色が画面でもその色に見えるよう、トーンマッピングは NeutralToneMapping にしている。描画はオンデマンドで、視点・色・浮き上がりの補間が終わると描画ループを止める。3Dライブラリ(three)は画面に入った実寸表示のときだけ useEffect 内の動的importで読み込み(本番ビルドの実測で追加チャンク計 753,967バイト・gzip 187,132バイト)、一覧の縮小カード・WebGL非対応・コンテキスト喪失・低速環境では、同じ部位・色・素材を斜め前から見た線画(SVG)で表示する。prefers-reduced-motion では補間も浮き上がりも使わず、変更のたびに最終状態を1枚だけ描く。見積もり依頼は送り先の定数を設定するまで送信せず、問い合わせページへ渡す内容(部位ごとの色・素材、合計、納期)をその場に示すので、押しても構成は消えない。価格と納期はサンプル。角丸・末尾の矢印リンク・英字の小見出しは使わず、ラジオの区画と構成表を hairline 罫線で組んでいる。
プレビュー
座面から脚まで、部位ごとに選べる椅子
4部位・5色・3素材/33,750通り
椅子か部位ボタンで部位を選び、色と素材を替えると金額の目安が連動します
クリックで部位を選択・ドラッグで回転(矢印キーでも回転・Enterで部位の正面へ)
構成と金額の目安
- 01座面
- 生成り・布
- +6,000
- 02背もたれ
- 生成り・布
- +5,000
- 03肘掛け
- 墨・マット
- ±0
- 04脚
- 琥珀・つや
- +4,500
- 本体
- 68,000
合計の目安(税込)
83,500円
納期の目安 約5週間受注色を1か所に含むため、標準より2週間ほど延びます
製品・価格・納期はすべて構成を示すためのサンプルです。自社の品目と価格表に差し替えてお使いください。見積もり依頼は、送り先を自社の問い合わせページに設定すると、選んだ構成・合計・納期をそのページへ渡します(見本では送信しません)。画面の色はディスプレイによって実物と異なって見えることがあります。
説明の全文を読む
製品を部位ごとに選んで色と素材を組み立てる、3Dの製品コンフィギュレーター。抽象形状のラウンジチェア(座面・背もたれ・肘掛け・脚の4部位)を画面上でクリックするか部位ボタンで選び、5色の色見本と3種の素材(つや・マット・布)を切り替えると、右の構成表に部位ごとの色・素材・加算額、合計の目安と納期の目安が同時に反映され、変更した行と合計が短く光る。スマートフォン幅では構成表が操作欄の下に回るため、合計と納期だけを画面下に貼り付けて操作中も見えるようにしている。入力の正は本物のラジオボタン(fieldset と legend)で、矢印キーでの移動・読み上げ・無効化(脚には布を選べない)がブラウザの標準動作のまま揃うため、キーボードだけで操作が完結する。3D側のクリックは Raycaster で部位を拾う近道で、選んだ部位は一回り大きい裏面の複製(反転ハル)でアンバーに縁取られ、部位ボタンの下線・構成表の該当行・引き出し線つきの部位ラベルも同じアンバーでそろえる。その部位が見やすい角度へ椅子が向きを変えて小さく浮き上がる。椅子は角を大きく丸めた箱を頂点単位で押し出して座面と背もたれの中央を膨らませ、脚は肘掛けの真下に通して1本の柱として床まで続く形にしている。素材は1つの MeshPhysicalMaterial のパラメータ差し替えで作り、つやは低い粗さとクリアコート、マットは高い粗さ、布はシーン(毛足の照り)と、64pxの canvas に糸の丸みをグラデーションで描いた籠目の bumpMap で表す。UV は面の向きごとに位置から振り直すので、座面の上面でも側面でも織り目の大きさがそろう。映り込みは白い部屋と発光板を PMREMGenerator で畳んだ環境マップ、影は ShadowMaterial の床と、椅子の下に敷いた放射グラデーションの接地影で、画像・モデルファイルは一切使わない。色見本の色が画面でもその色に見えるよう、トーンマッピングは NeutralToneMapping にしている。描画はオンデマンドで、視点・色・浮き上がりの補間が終わると描画ループを止める。3Dライブラリ(three)は画面に入った実寸表示のときだけ useEffect 内の動的importで読み込み(本番ビルドの実測で追加チャンク計 753,967バイト・gzip 187,132バイト)、一覧の縮小カード・WebGL非対応・コンテキスト喪失・低速環境では、同じ部位・色・素材を斜め前から見た線画(SVG)で表示する。prefers-reduced-motion では補間も浮き上がりも使わず、変更のたびに最終状態を1枚だけ描く。見積もり依頼は送り先の定数を設定するまで送信せず、問い合わせページへ渡す内容(部位ごとの色・素材、合計、納期)をその場に示すので、押しても構成は消えない。価格と納期はサンプル。角丸・末尾の矢印リンク・英字の小見出しは使わず、ラジオの区画と構成表を hairline 罫線で組んでいる。
- 追加日:
- 2026-10-01
- 更新日:
- 2026-10-27
- 依存:
- three
- tags
- #3d #product-configurator #customizer #ecommerce #webgl #interactive #keyboard #form #pricing #no-image #dynamic-import
"use client";
import { useEffect, useId, useRef, useState, type FormEvent, type KeyboardEvent } from "react";
import { Montserrat } from "next/font/google";
// 型だけの import。tsc が消すので 3Dライブラリのコードは1バイトも入らない(実体は下の動的 import)。
import type * as THREE from "three";
const montserrat = Montserrat({ weight: ["600", "700"], subsets: ["latin"], display: "swap" });
/**
* 3D製品コンフィギュレーター(部位を選んで色と素材を替える)
*
* 差し替えの早見表(自社の品目にするときに書き換える定数):
* 部位 PARTS[].id seat 座面 / back 背もたれ / arms 肘掛け / legs 脚(3D側は addMesh の第1引数に同じ id を渡す)
* 素材 FINISHES[].id gloss つや / matte マット / fabric 布。部位ごとの加算額は PARTS[].finishPrice(null=その部位では選べない)
* 色 SWATCHES[] kinari #e8e0d0 / sumi #2f2b28 / koke #66724f / ai #34475f / kohaku #d97706
* premium: true の色は受注色で、1部位 +PREMIUM_PRICE 円・納期は PREMIUM_LEAD_WEEKS 週
* 合計 BASE_PRICE + 部位ごとの(素材の加算 + 受注色の加算)。計算は partPrice の1か所だけ
* 送り先 QUOTE_ACTION(null の間は送信せず、問い合わせページへ渡す内容を画面に出す)
*
* 自分のモデルに置き換える最小例(GLB を使う場合。createConfigurator を async にし、GLTFLoader を追加で動的 import する):
* const gltf = await new GLTFLoader().loadAsync("/models/chair.glb"); // Blender でメッシュ名を seat / back / arms / legs にしておく
* gltf.scene.traverse((o) => {
* if (!(o instanceof T.Mesh) || !(o.name in rigs)) return;
* addMesh(o.name as PartId, o.geometry, o.position.toArray(), [o.rotation.x, o.rotation.y, o.rotation.z], [0, 0.05, 0]);
* });
* // 「椅子(形はすべてコード生成)」の addMesh 群をこれに替えれば、素材の差し替え・縁取り・クリックでの部位選択はそのまま効く
* // (ノードが入れ子のときは o.updateWorldMatrix(true, false) で親の変形を geometry に焼いてから渡す)
*
* 差別化: 既存の3D標本(three-object-gallery-hero)は完成品を切り替えて眺める展示、地球儀(globe-reach-arcs)は
* 座標データの説明図だった。本ブロックは1つの製品を部位ごとに選んで「色×素材」を組み立てる入力フォームで、
* 選んだ構成・加算額・合計・納期の目安が右の台帳へ同時に反映される。角丸・末尾の矢印リンク・英字の小見出しは置かない。
*
* 汎用技法メモ:
* 1. **正はフォーム、3Dは従**。部位・色・素材はすべて本物の `<input type="radio">`(fieldset + legend)で持つ。
* 矢印キーでの移動・読み上げ・無効化(脚に布は選べない)がブラウザ任せで揃い、3Dが無い環境でも操作が完結する。
* 3D側のクリック(Raycaster)は「部位ラジオを選ぶ近道」にすぎない。
* 2. **素材は1つの MeshPhysicalMaterial のパラメータ差し替えで作る**。つや=roughness 低+clearcoat、
* マット=roughness 高、布=sheen(布の産毛の照り)+ bumpMap。織り目の bumpMap は 32px の canvas に
* 描いた籠目を CanvasTexture にして繰り返すだけで、画像ファイルは要らない。
* clearcoat・sheen・bumpMap の有無はシェーダの分岐が変わるので、切り替え時に `needsUpdate = true`。
* 3. **トーンマッピングは NeutralToneMapping**。ACES は色見本の彩度と明度を大きく曲げるので、
* 「選んだ色が画面でその色に見える」ことが要る用途では Neutral の方が素直。
* 4. **選択中の部位は反転ハル(BackSide の一回り大きい複製)で縁取る**。拡大率を軸ごとに
* `1 + 2t / 寸法` で出すと、細い脚でも厚い座面でも縁の太さがそろう。
* 5. **描画はオンデマンド**。視点の補間・色の補間・部位の小さな跳ねが終わったら rAF を止め、
* 操作のたびに回し直す。低速判定(立ち上がり10フレームを捨て、48フレームの平均が32ms超で
* 解像度を下げ、なお遅ければ平面図へ降格)は「動いたフレーム」だけで数える。
* 6. 起動条件は「画面内」かつ「縮小プレビューでない」(rect.width ÷ offsetWidth)。WebGL が無い・
* コンテキストを失った・フレームが間に合わないときは、同じ部位・色・素材を SVG の線画で出す。
* 7. prefers-reduced-motion では補間も跳ねも使わず、変更のたびに最終状態を1枚だけ描く。
*
* 文言・製品形状・価格・配色はすべて First CH のオリジナル(価格はサンプル)。
*/
type ThreeModule = typeof import("three");
type RoundedBoxCtor = typeof import("three/examples/jsm/geometries/RoundedBoxGeometry.js").RoundedBoxGeometry;
const AMBER = 0xd97706;
/* ------------------------------------------------------------------ データ */
type PartId = "seat" | "back" | "arms" | "legs";
type FinishId = "gloss" | "matte" | "fabric";
type ColorId = "kinari" | "sumi" | "koke" | "ai" | "kohaku";
type Part = {
id: PartId;
name: string;
no: string;
/** 選んだときに向ける視点(台の回転・カメラの仰角) */
view: { yaw: number; elev: number };
/** ラベルを付ける点(椅子のローカル座標) */
anchor: [number, number, number];
/** 素材ごとの加算額。null はその部位では選べない */
finishPrice: Record<FinishId, number | null>;
};
const PARTS: Part[] = [
{
id: "seat",
name: "座面",
no: "01",
view: { yaw: -0.6, elev: 0.46 },
anchor: [0.2, 0.96, 0.3],
finishPrice: { gloss: 4000, matte: 0, fabric: 6000 },
},
{
id: "back",
name: "背もたれ",
no: "02",
view: { yaw: 0.55, elev: 0.28 },
anchor: [0, 1.74, -0.6],
finishPrice: { gloss: 3000, matte: 0, fabric: 5000 },
},
{
id: "arms",
name: "肘掛け",
no: "03",
view: { yaw: -1.05, elev: 0.32 },
anchor: [0.8, 1.2, 0.3],
finishPrice: { gloss: 2000, matte: 0, fabric: 3000 },
},
{
id: "legs",
name: "脚",
no: "04",
view: { yaw: -0.42, elev: 0.08 },
anchor: [0.82, 0.24, 0.42],
finishPrice: { gloss: 2500, matte: 0, fabric: null },
},
];
const PART_INDEX: Record<PartId, number> = { seat: 0, back: 1, arms: 2, legs: 3 };
type Finish = { id: FinishId; name: string; note: string };
const FINISHES: Finish[] = [
{ id: "gloss", name: "つや", note: "艶のある塗装仕上げ。水拭きしやすく、光を受けると輪郭が立ちます" },
{ id: "matte", name: "マット", note: "艶を抑えた仕上げ。指紋が目立たず、落ち着いた見え方になります" },
{ id: "fabric", name: "布", note: "織り布の張り地。やわらかく、光が表面の毛足で散ります" },
];
type Swatch = { id: ColorId; name: string; hex: string; premium: boolean };
const SWATCHES: Swatch[] = [
{ id: "kinari", name: "生成り", hex: "#e8e0d0", premium: false },
{ id: "sumi", name: "墨", hex: "#2f2b28", premium: false },
{ id: "koke", name: "苔", hex: "#66724f", premium: false },
{ id: "ai", name: "藍", hex: "#34475f", premium: true },
{ id: "kohaku", name: "琥珀", hex: "#d97706", premium: true },
];
const SWATCH: Record<ColorId, Swatch> = Object.fromEntries(SWATCHES.map((s) => [s.id, s])) as Record<ColorId, Swatch>;
const FINISH: Record<FinishId, Finish> = Object.fromEntries(FINISHES.map((f) => [f.id, f])) as Record<FinishId, Finish>;
const BASE_PRICE = 68000;
const PREMIUM_PRICE = 2000;
const LEAD_WEEKS = 3;
const PREMIUM_LEAD_WEEKS = 5;
// 見積もり依頼の送り先(例: "/contact")。入れると構成を GET で渡すので、受け取った値をフォームの初期値に入れる。
// null の間は見本として送信せず、渡す内容を画面に出す(存在しないページへ飛んで構成が消えるのを防ぐ)
const QUOTE_ACTION: string | null = null;
type Choice = { color: ColorId; finish: FinishId };
type Config = Record<PartId, Choice>;
const DEFAULT_CONFIG: Config = {
seat: { color: "kinari", finish: "fabric" },
back: { color: "kinari", finish: "fabric" },
arms: { color: "sumi", finish: "matte" },
legs: { color: "kohaku", finish: "gloss" },
};
/** 組み合わせの総数(部位ごとに 色の数 × 選べる素材の数 を掛ける) */
const COMBINATIONS = PARTS.reduce(
(acc, p) => acc * SWATCHES.length * FINISHES.filter((f) => p.finishPrice[f.id] !== null).length,
1,
);
// toLocaleString はSSRとブラウザで結果が割れうるので使わない
const yen = (n: number) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const partPrice = (p: Part, c: Choice) => (p.finishPrice[c.finish] ?? 0) + (SWATCH[c.color].premium ? PREMIUM_PRICE : 0);
/* ------------------------------------------------------------------ 3D */
type ConfiguratorApi = {
apply: (config: Config, active: PartId) => void;
nudge: (dYaw: number, dElev: number) => void;
recenter: () => void;
setRunning: (running: boolean) => void;
dispose: () => void;
};
type ConfiguratorOptions = {
canvas: HTMLCanvasElement;
host: HTMLElement;
label: HTMLElement;
config: Config;
active: PartId;
onPick: (part: PartId) => void;
onFirstFrame: () => void;
onFail: () => void;
};
/** 布の織り目(籠目)を 64px の canvas に描き、bumpMap 用のテクスチャにする。
* 糸は中央が高く両端が低いグラデーションで描く(段差が硬いと、遠目で縞のちらつきになる) */
function makeWeave(T: ThreeModule) {
const size = 64;
const cell = 16;
const c = document.createElement("canvas");
c.width = size;
c.height = size;
const ctx = c.getContext("2d");
if (ctx) {
ctx.fillStyle = "#3a3a3a";
ctx.fillRect(0, 0, size, size);
const thread = (x: number, y: number, w: number, h: number, across: boolean) => {
const g = across ? ctx.createLinearGradient(0, y, 0, y + h) : ctx.createLinearGradient(x, 0, x + w, 0);
g.addColorStop(0, "#5a5a5a");
g.addColorStop(0.5, "#f0f0f0");
g.addColorStop(1, "#5a5a5a");
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
};
for (let cy = 0; cy < size / cell; cy++) {
for (let cx = 0; cx < size / cell; cx++) {
const x = cx * cell;
const y = cy * cell;
// 横2本/縦2本を市松に並べる(籠目)
if ((cx + cy) % 2 === 0) {
thread(x, y + 1, cell, 6, true);
thread(x, y + 9, cell, 6, true);
} else {
thread(x + 1, y, 6, cell, false);
thread(x + 9, y, 6, cell, false);
}
}
}
}
const tex = new T.CanvasTexture(c);
tex.wrapS = T.RepeatWrapping;
tex.wrapT = T.RepeatWrapping;
tex.colorSpace = T.NoColorSpace;
return tex;
}
/** 接地の柔らかい影(中心ほど濃い楕円)。ShadowMaterial の輪郭影の下に敷き、床との接点をはっきりさせる */
function makeContactShadow(T: ThreeModule) {
const size = 128;
const c = document.createElement("canvas");
c.width = size;
c.height = size;
const ctx = c.getContext("2d");
if (ctx) {
const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
g.addColorStop(0, "rgba(35,31,27,0.55)");
g.addColorStop(0.45, "rgba(35,31,27,0.28)");
g.addColorStop(1, "rgba(35,31,27,0)");
ctx.fillStyle = g;
ctx.fillRect(0, 0, size, size);
}
const tex = new T.CanvasTexture(c);
tex.colorSpace = T.SRGBColorSpace;
return tex;
}
/** クッションのふくらみ。薄い軸(seat は y・背もたれは z)の面を、中央ほど外へ押し出す。
* 縁は動かさないので、角の丸みはそのままに中央だけが張る */
function puff(geo: THREE.BufferGeometry, axis: "y" | "z", amount: number) {
geo.computeBoundingBox();
const box = geo.boundingBox;
if (!box) return;
const hx = (box.max.x - box.min.x) / 2;
const hy = (box.max.y - box.min.y) / 2;
const hz = (box.max.z - box.min.z) / 2;
const pos = geo.attributes.position;
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const y = pos.getY(i);
const z = pos.getZ(i);
if (axis === "y") {
const w = Math.max(0, 1 - (x / hx) ** 2) * Math.max(0, 1 - (z / hz) ** 2);
pos.setY(i, y + Math.sign(y) * amount * w * Math.abs(y / hy));
} else {
const w = Math.max(0, 1 - (x / hx) ** 2) * Math.max(0, 1 - (y / hy) ** 2);
pos.setZ(i, z + Math.sign(z) * amount * w * Math.abs(z / hz));
}
}
pos.needsUpdate = true;
geo.computeVertexNormals();
}
/** 面の向きごとに位置から UV を振り直す(箱投影)。面の大きさが違っても織り目の目の大きさがそろう */
function boxUv(geo: THREE.BufferGeometry, tile: number) {
const pos = geo.attributes.position;
const nor = geo.attributes.normal;
const uv = geo.attributes.uv;
if (!uv) return;
for (let i = 0; i < pos.count; i++) {
const nx = Math.abs(nor.getX(i));
const ny = Math.abs(nor.getY(i));
const nz = Math.abs(nor.getZ(i));
const [u, v] =
nx >= ny && nx >= nz ? [pos.getZ(i), pos.getY(i)] : ny >= nz ? [pos.getX(i), pos.getZ(i)] : [pos.getX(i), pos.getY(i)];
uv.setXY(i, u / tile, v / tile);
}
uv.needsUpdate = true;
}
function createConfigurator(T: ThreeModule, RoundedBox: RoundedBoxCtor, opts: ConfiguratorOptions): ConfiguratorApi {
const { canvas, host, label, onPick, onFirstFrame, onFail } = opts;
const renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: "low-power" });
let dpr = Math.min(window.devicePixelRatio || 1, 2);
renderer.setPixelRatio(dpr);
renderer.toneMapping = T.NeutralToneMapping;
renderer.toneMappingExposure = 0.94;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFShadowMap;
const scene = new T.Scene();
const camera = new T.PerspectiveCamera(30, 1, 0.1, 40);
const TARGET_Y = 0.84;
const geometries: THREE.BufferGeometry[] = [];
const materials: THREE.Material[] = [];
const keep = <G extends THREE.BufferGeometry>(g: G) => {
geometries.push(g);
return g;
};
// --- 環境マップ: 白い部屋+発光板を畳んで作る(画像は読まない)-------------------------
const envScene = new T.Scene();
const envBox = new T.BoxGeometry();
const envMats: THREE.Material[] = [];
const roomMat = new T.MeshBasicMaterial({ color: 0xefebe4, side: T.BackSide });
envMats.push(roomMat);
const room = new T.Mesh(envBox, roomMat);
room.scale.set(20, 14, 20);
envScene.add(room);
const panel = (intensity: number, color: number, p: [number, number, number], s: [number, number, number]) => {
const mat = new T.MeshBasicMaterial({ color: new T.Color(color).multiplyScalar(intensity) });
envMats.push(mat);
const m = new T.Mesh(envBox, mat);
m.position.set(...p);
m.scale.set(...s);
envScene.add(m);
};
panel(9, 0xffffff, [-3.6, 3.4, 2.8], [0.1, 3.2, 4.4]); // キー(左上の面光源)
panel(4, 0xfff4e6, [4.2, 1.6, 1.4], [0.1, 2.8, 3.6]); // フィル
panel(6, 0xffffff, [0, 6.4, 0], [5, 0.1, 5]); // トップ
panel(1.8, AMBER, [0, 0.2, -5.8], [4, 2.2, 0.1]); // 背面のアンバー(つやの映り込みに色を差す)
const pmrem = new T.PMREMGenerator(renderer);
const envTarget = pmrem.fromScene(envScene, 0.03);
scene.environment = envTarget.texture;
scene.environmentIntensity = 0.9;
envBox.dispose();
for (const m of envMats) m.dispose();
pmrem.dispose();
// --- ライト -------------------------------------------------------------------------------
const key = new T.DirectionalLight(0xffffff, 1.9);
key.position.set(2.2, 4.2, 2.8);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.near = 1;
key.shadow.camera.far = 12;
key.shadow.camera.left = -2;
key.shadow.camera.right = 2;
key.shadow.camera.top = 2;
key.shadow.camera.bottom = -2;
key.shadow.bias = -0.0008;
key.shadow.radius = 4;
scene.add(key);
scene.add(new T.HemisphereLight(0xffffff, 0xe7dfd2, 0.7));
const groundGeo = keep(new T.PlaneGeometry(12, 12));
const groundMat = new T.ShadowMaterial({ opacity: 0.2, color: 0x231f1b });
materials.push(groundMat);
const ground = new T.Mesh(groundGeo, groundMat);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// --- 椅子(形はすべてコード生成)-----------------------------------------------------------
const chair = new T.Group();
scene.add(chair);
const weave = makeWeave(T);
weave.anisotropy = renderer.capabilities.getMaxAnisotropy();
const outlineOn = new T.MeshBasicMaterial({ color: AMBER, side: T.BackSide });
const outlineHover = new T.MeshBasicMaterial({ color: 0xa8a29e, side: T.BackSide });
materials.push(outlineOn, outlineHover);
// 接地の柔らかい影。椅子と一緒に回るよう chair の子にする(脚の位置に合わせて少し横長)
const contactTex = makeContactShadow(T);
const contactMat = new T.MeshBasicMaterial({ map: contactTex, transparent: true, depthWrite: false, toneMapped: false });
materials.push(contactMat);
const contact = new T.Mesh(keep(new T.PlaneGeometry(2.3, 1.75)), contactMat);
contact.rotation.x = -Math.PI / 2;
contact.position.y = 0.002;
contact.renderOrder = -1;
chair.add(contact);
type PartRig = {
id: PartId;
group: THREE.Group;
mat: THREE.MeshPhysicalMaterial;
meshes: { mesh: THREE.Mesh; outline: THREE.Mesh; home: THREE.Vector3; hop: THREE.Vector3 }[];
color: THREE.Color;
colorTarget: THREE.Color;
finish: FinishId | null;
};
const rigs: Record<PartId, PartRig> = {} as Record<PartId, PartRig>;
const pickables: THREE.Mesh[] = [];
const addPart = (id: PartId) => {
const group = new T.Group();
chair.add(group);
const mat = new T.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.7 });
materials.push(mat);
rigs[id] = { id, group, mat, meshes: [], color: new T.Color(), colorTarget: new T.Color(), finish: null };
return group;
};
// 織り目1枚(籠目4×4)が覆う長さ。面の大小に関係なく目の大きさがそろう
const WEAVE_TILE = 0.16;
const OUTLINE = 0.016;
const addMesh = (
id: PartId,
geo: THREE.BufferGeometry,
pos: [number, number, number],
rot: [number, number, number],
hop: [number, number, number],
) => {
const rig = rigs[id];
keep(geo);
boxUv(geo, WEAVE_TILE);
const mesh = new T.Mesh(geo, rig.mat);
mesh.position.set(...pos);
mesh.rotation.set(...rot);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.part = id;
// 反転ハル。軸ごとに 1 + 2t/寸法 で拡げると、細い脚でも厚い座面でも縁の太さがそろう
geo.computeBoundingBox();
const size = new T.Vector3();
geo.boundingBox?.getSize(size);
const outline = new T.Mesh(geo, outlineOn);
outline.scale.set(1 + (2 * OUTLINE) / size.x, 1 + (2 * OUTLINE) / size.y, 1 + (2 * OUTLINE) / size.z);
outline.visible = false;
mesh.add(outline);
rig.group.add(mesh);
rig.meshes.push({ mesh, outline, home: mesh.position.clone(), hop: new T.Vector3(...hop) });
pickables.push(mesh);
};
// 肘掛けの真下に脚を置き、肘掛け→脚が1本の柱として床まで通る構成にする(接合部で段差を作らない)
const ARM_X = 0.8;
addPart("legs");
const legGeo = () => new T.CylinderGeometry(0.046, 0.03, 0.68, 28);
for (const [x, z] of [
[-ARM_X, 0.4],
[ARM_X, 0.4],
[-ARM_X, -0.4],
[ARM_X, -0.4],
] as const) {
// 脚は下へ細くなり、外へ少し開く(上端は肘掛けの下面の中央に収まる)
addMesh("legs", legGeo(), [x, 0.34, z], [Math.sign(z) * 0.06, 0, -Math.sign(x) * 0.06], [Math.sign(x) * 0.07, 0, Math.sign(z) * 0.05]);
}
// 左右の脚をつなぐ幕板(座面の下に隠れ、正面からは座面の影の中に細く見える)
addMesh("legs", new RoundedBox(ARM_X * 2, 0.05, 0.86, 2, 0.02), [0, 0.63, 0], [0, 0, 0], [0, -0.06, 0]);
addPart("seat");
const seatGeo = new RoundedBox(1.42, 0.26, 1.1, 6, 0.11);
puff(seatGeo, "y", 0.05);
addMesh("seat", seatGeo, [0, 0.79, 0.02], [0, 0, 0], [0, 0.1, 0]);
addPart("back");
const backGeo = new RoundedBox(1.42, 0.92, 0.26, 6, 0.12);
puff(backGeo, "z", 0.05);
addMesh("back", backGeo, [0, 1.3, -0.48], [-0.2, 0, 0], [0, 0.03, -0.1]);
addPart("arms");
for (const side of [-1, 1]) {
// 幅の半分近い半径で角を落とし、角材ではなく張りのある板に見せる
addMesh("arms", new RoundedBox(0.17, 0.52, 1.06, 6, 0.075), [side * ARM_X, 0.94, -0.01], [0, 0, 0], [side * 0.09, 0, 0]);
}
const white = new T.Color(0xffffff);
const setFinish = (rig: PartRig, finish: FinishId) => {
if (rig.finish === finish) return;
rig.finish = finish;
const m = rig.mat;
// つや=鋭い映り込み、マット=映り込みを広くぼかした柔らかい陰影、布=毛足の照り+織り目の凹凸
m.roughness = finish === "gloss" ? 0.14 : finish === "matte" ? 0.66 : 0.92;
m.metalness = 0;
m.clearcoat = finish === "gloss" ? 1 : 0;
m.clearcoatRoughness = 0.05;
m.sheen = finish === "fabric" ? 1 : 0;
m.sheenRoughness = 0.5;
m.bumpMap = finish === "fabric" ? weave : null;
m.bumpScale = 3;
m.envMapIntensity = finish === "gloss" ? 1.3 : finish === "matte" ? 0.75 : 0.55;
// clearcoat・sheen・bumpMap の有無はシェーダの分岐が変わる
m.needsUpdate = true;
};
const paintColor = (rig: PartRig) => {
rig.mat.color.copy(rig.color);
rig.mat.sheenColor.copy(rig.color).lerp(white, 0.35);
};
// --- 状態 ------------------------------------------------------------------------------
const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
let motionOK = !motionQuery.matches;
let running = false;
let raf = 0;
let last = 0;
let firstFrame = true;
let active: PartId = opts.active;
let hovered: PartId | null = null;
let yaw = 0;
let elev = 0.3;
let yawTarget = 0;
let elevTarget = 0.3;
let hopT = 1;
let frames = 0;
let elapsed = 0;
let degraded = false;
let width = 1;
let height = 1;
let dist = 5;
const HOP_SEC = 0.55;
const HOP_AMP = 0.9;
const aim = (id: PartId) => {
const v = PARTS[PART_INDEX[id]].view;
let y = v.yaw;
while (y - yaw > Math.PI) y -= Math.PI * 2;
while (y - yaw < -Math.PI) y += Math.PI * 2;
yawTarget = y;
elevTarget = v.elev;
};
const paintOutlines = () => {
for (const id of Object.keys(rigs) as PartId[]) {
const rig = rigs[id];
for (const m of rig.meshes) {
m.outline.visible = id === active || id === hovered;
m.outline.material = id === active ? outlineOn : outlineHover;
}
}
};
const placeHops = (k: number) => {
const rig = rigs[active];
for (const id of Object.keys(rigs) as PartId[]) {
for (const m of rigs[id].meshes) {
m.mesh.position.copy(m.home);
if (id === rig.id && k > 0) m.mesh.position.addScaledVector(m.hop, k);
}
}
};
const anchor = new T.Vector3();
const placeLabel = () => {
anchor.set(...PARTS[PART_INDEX[active]].anchor);
anchor.applyMatrix4(chair.matrixWorld);
anchor.project(camera);
const x = ((anchor.x + 1) / 2) * width;
const y = ((1 - anchor.y) / 2) * height;
label.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px) translate(-50%, calc(-100% - 12px))`;
label.style.opacity = "1";
};
const placeCamera = () => {
camera.position.set(0, TARGET_Y + Math.sin(elev) * dist, Math.cos(elev) * dist);
camera.lookAt(0, TARGET_Y, 0);
};
const renderOnce = () => {
chair.rotation.y = yaw;
placeCamera();
chair.updateMatrixWorld();
renderer.render(scene, camera);
placeLabel();
if (firstFrame) {
firstFrame = false;
onFirstFrame();
}
};
/** 補間を使わずに最終状態を置く(モーション低減・画面外・停止中の共通経路) */
const settle = () => {
yaw = yawTarget;
elev = elevTarget;
hopT = 1;
for (const rig of Object.values(rigs)) {
rig.color.copy(rig.colorTarget);
paintColor(rig);
}
placeHops(0);
renderOnce();
};
const resize = () => {
const rect = host.getBoundingClientRect();
width = Math.max(1, Math.round(rect.width));
height = Math.max(1, Math.round(rect.height));
const aspect = width / height;
camera.aspect = aspect;
camera.updateProjectionMatrix();
// 椅子(高さ約1.8・回したときの幅約1.9)が縦横どちらでも収まる距離を逆算する
const t = Math.tan((camera.fov * Math.PI) / 360);
dist = Math.max(1.22 / t, 1.3 / (t * aspect));
renderer.setSize(width, height, false);
};
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = Math.min((now - last) / 1000, 0.06);
last = now;
const ease = 1 - Math.pow(0.002, dt);
yaw += (yawTarget - yaw) * ease;
elev += (elevTarget - elev) * ease;
let colorsDone = true;
for (const rig of Object.values(rigs)) {
rig.color.lerp(rig.colorTarget, 1 - Math.pow(0.0005, dt));
const d =
Math.abs(rig.color.r - rig.colorTarget.r) +
Math.abs(rig.color.g - rig.colorTarget.g) +
Math.abs(rig.color.b - rig.colorTarget.b);
if (d < 0.002) rig.color.copy(rig.colorTarget);
else colorsDone = false;
paintColor(rig);
}
hopT = Math.min(1, hopT + dt / HOP_SEC);
placeHops(Math.sin(Math.PI * hopT) * HOP_AMP);
renderOnce();
// 低スペック対策: 動いたフレームだけで数える(立ち上がり10フレームを捨て、続く48フレームの平均)
frames += 1;
if (frames > 10 && frames <= 58) {
elapsed += dt * 1000;
if (frames === 58 && elapsed / 48 > 32) {
if (degraded) {
stop();
onFail();
return;
}
degraded = true;
dpr = Math.max(1, dpr * 0.6);
renderer.setPixelRatio(dpr);
resize();
frames = 0;
elapsed = 0;
}
}
const viewDone = Math.abs(yawTarget - yaw) < 1e-3 && Math.abs(elevTarget - elev) < 1e-3;
if (viewDone && colorsDone && hopT >= 1) {
yaw = yawTarget;
elev = elevTarget;
renderOnce();
stop();
}
};
/** 変化があったときに呼ぶ。動かせない状況なら最終状態を1枚だけ描く */
const kick = () => {
if (!running || !motionOK) {
settle();
return;
}
if (raf) return;
last = performance.now();
raf = requestAnimationFrame(frame);
};
function stop() {
if (!raf) return;
cancelAnimationFrame(raf);
raf = 0;
}
const apply = (config: Config, nextActive: PartId) => {
for (const p of PARTS) {
const rig = rigs[p.id];
setFinish(rig, config[p.id].finish);
rig.colorTarget.set(SWATCH[config[p.id].color].hex);
}
if (nextActive !== active || firstFrame) {
active = nextActive;
aim(active);
hopT = firstFrame ? 1 : 0;
}
paintOutlines();
kick();
};
const onMotionChange = () => {
motionOK = !motionQuery.matches;
if (!motionOK) {
stop();
settle();
}
};
motionQuery.addEventListener("change", onMotionChange);
// --- ポインタ: クリックで部位を選ぶ・ドラッグで回す(回転はモーション低減時も許可)------------
const raycaster = new T.Raycaster();
const ndc = new T.Vector2();
const pickAt = (clientX: number, clientY: number): PartId | null => {
const rect = canvas.getBoundingClientRect();
ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
raycaster.setFromCamera(ndc, camera);
const hit = raycaster.intersectObjects(pickables, false)[0];
return hit ? (hit.object.userData.part as PartId) : null;
};
let pointerId: number | null = null;
let downX = 0;
let downY = 0;
let lastX = 0;
let lastY = 0;
let dragged = false;
const onPointerDown = (e: PointerEvent) => {
if (pointerId !== null) return;
pointerId = e.pointerId;
downX = lastX = e.clientX;
downY = lastY = e.clientY;
dragged = false;
canvas.setPointerCapture(e.pointerId);
};
const onPointerMove = (e: PointerEvent) => {
if (pointerId === null) {
// ホバー: 部位を薄い縁で示す
const h = e.pointerType === "mouse" ? pickAt(e.clientX, e.clientY) : null;
canvas.style.cursor = h ? "pointer" : "grab";
if (h !== hovered) {
hovered = h;
paintOutlines();
if (!raf) renderOnce();
}
return;
}
if (e.pointerId !== pointerId) return;
if (!dragged && Math.hypot(e.clientX - downX, e.clientY - downY) < 5) return;
dragged = true;
canvas.style.cursor = "grabbing";
const k = 3 / Math.max(width, 1);
yawTarget += (e.clientX - lastX) * k;
elevTarget = Math.max(0.02, Math.min(0.95, elevTarget + (e.clientY - lastY) * k));
// ドラッグ中は補間を待たずに指へ貼り付ける
yaw = yawTarget;
elev = elevTarget;
lastX = e.clientX;
lastY = e.clientY;
if (!raf) renderOnce();
};
const onPointerUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
pointerId = null;
if (canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
canvas.style.cursor = "grab";
if (!dragged && e.type === "pointerup") {
const id = pickAt(e.clientX, e.clientY);
if (id) onPick(id);
}
};
const onPointerLeave = () => {
if (hovered === null) return;
hovered = null;
paintOutlines();
if (!raf) renderOnce();
};
canvas.addEventListener("pointerdown", onPointerDown);
canvas.addEventListener("pointermove", onPointerMove);
canvas.addEventListener("pointerup", onPointerUp);
canvas.addEventListener("pointercancel", onPointerUp);
canvas.addEventListener("pointerleave", onPointerLeave);
const onContextLost = (e: Event) => {
e.preventDefault();
stop();
onFail();
};
canvas.addEventListener("webglcontextlost", onContextLost);
// canvas の寸法を書き換えると中身が消えるので、止まっていても必ず1枚描き直す
const ro = new ResizeObserver(() => {
resize();
renderOnce();
});
ro.observe(host);
resize();
// 最初の1枚(running はまだ false なので、最終状態を1枚だけ描いて onFirstFrame を呼ぶ)
apply(opts.config, opts.active);
return {
apply,
nudge: (dYaw, dElev) => {
yawTarget += dYaw;
elevTarget = Math.max(0.02, Math.min(0.95, elevTarget + dElev));
kick();
},
recenter: () => {
aim(active);
kick();
},
setRunning: (next) => {
running = next;
if (!next) stop();
else if (!firstFrame) kick();
},
dispose: () => {
stop();
ro.disconnect();
motionQuery.removeEventListener("change", onMotionChange);
canvas.removeEventListener("pointerdown", onPointerDown);
canvas.removeEventListener("pointermove", onPointerMove);
canvas.removeEventListener("pointerup", onPointerUp);
canvas.removeEventListener("pointercancel", onPointerUp);
canvas.removeEventListener("pointerleave", onPointerLeave);
canvas.removeEventListener("webglcontextlost", onContextLost);
for (const g of geometries) g.dispose();
for (const m of materials) m.dispose();
weave.dispose();
contactTex.dispose();
envTarget.dispose();
renderer.dispose();
renderer.forceContextLoss();
},
};
}
/* ------------------------------------------------------------------ 平面図(SVG) */
// 斜め前から見た線画。部位ごとに面(パス)を持ち、上面だけ明るく重ねて立体に見せる。
// 角は Q で丸め、座面と背もたれは縁を少し反らせてクッションの張りを出す。脚は肘掛けの真下に置く(3Dと同じ構成)
const FLAT: Record<PartId, { faces: string[]; tops: string[] }> = {
legs: {
faces: [
"M66 122 L72 122 L71 170 L67.5 170 Z",
"M194 122 L188 122 L189 170 L192.5 170 Z",
"M45.5 142 L54.5 142 L52.5 186 L47.5 186 Z",
"M214.5 142 L205.5 142 L207.5 186 L212.5 186 Z",
],
tops: [],
},
back: {
faces: ["M84 108 L176 108 L183.5 42 Q184.5 34 176.5 34 L83.5 34 Q75.5 34 76.5 42 Z"],
tops: ["M77 35 Q78 27 86 27 L174 27 Q182 27 183 35 Q130 31 77 35 Z"],
},
seat: {
faces: ["M62 117 Q130 112 198 117 L198 131 Q198 140 189 140 L71 140 Q62 140 62 131 Z"],
tops: ["M80 100 L180 100 Q186 100 189 104 L197 116 Q130 111 63 116 L71 104 Q74 100 80 100 Z"],
},
arms: {
faces: ["M40 99 Q40 92 47 92 L53 92 Q60 92 60 99 L60 142 L40 142 Z", "M220 99 Q220 92 213 92 L207 92 Q200 92 200 99 L200 142 L220 142 Z"],
tops: ["M42 92.5 L58 92.5 L77 75 Q78 74 76 74 L66 74 Q63 74 61 76 Z", "M218 92.5 L202 92.5 L183 75 Q182 74 184 74 L194 74 Q197 74 199 76 Z"],
},
};
// 奥から手前へ描く順
const FLAT_ORDER: PartId[] = ["legs", "back", "seat", "arms"];
/* ------------------------------------------------------------------ 本体 */
const STEP = (15 * Math.PI) / 180;
export default function ProductConfigurator3D() {
const uid = useId().replace(/:/g, "");
const headingId = `configurator-heading-${uid}`;
const hintId = `configurator-hint-${uid}`;
const stageRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const labelRef = useRef<HTMLSpanElement>(null);
const apiRef = useRef<ConfiguratorApi | null>(null);
const [live, setLive] = useState(false);
const [inView, setInView] = useState(false);
const [pageVisible, setPageVisible] = useState(true);
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
const [config, setConfig] = useState<Config>(DEFAULT_CONFIG);
const [active, setActive] = useState<PartId>("seat");
const [announce, setAnnounce] = useState("");
const [quoteShown, setQuoteShown] = useState(false);
// 変更が反映された行と合計を短く光らせる(n を進めて同じ部位の連続変更でも毎回光らせる)
const [pulse, setPulse] = useState<{ id: PartId; n: number } | null>(null);
const rowFlashRefs = useRef<Partial<Record<PartId, HTMLSpanElement | null>>>({});
const totalFlashRefs = useRef<(HTMLSpanElement | null)[]>([]);
// 起動時の構成は ref 経由で渡す(3Dを作り直すのは live が立つときの1回だけ)
const initialRef = useRef<{ config: Config; active: PartId }>({ config: DEFAULT_CONFIG, active: "seat" });
useEffect(() => {
initialRef.current = { config, active };
}, [config, active]);
// 起動条件: 画面内 かつ 実寸表示。一覧のカードは親に scale が掛かっているので
// rect.width(変形後)÷ offsetWidth(レイアウト幅)が 1 未満になり、3Dライブラリを読み込まない。
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const fullSize = el.offsetWidth > 0 ? rect.width / el.offsetWidth > 0.75 : true;
const io = new IntersectionObserver(
([entry]) => {
setInView(entry.isIntersecting);
if (entry.isIntersecting && fullSize) setLive(true);
},
{ rootMargin: "160px" },
);
io.observe(el);
const onVisibility = () => setPageVisible(document.visibilityState === "visible");
document.addEventListener("visibilitychange", onVisibility);
return () => {
io.disconnect();
document.removeEventListener("visibilitychange", onVisibility);
};
}, []);
useEffect(() => {
if (!live) return;
const canvas = canvasRef.current;
const host = stageRef.current;
const label = labelRef.current;
if (!canvas || !host || !label) return;
let cancelled = false;
const boot = async () => {
// 非対応なら重いライブラリを取りに行かず、平面図のまま確定させる
const probe = document.createElement("canvas");
const gl = probe.getContext("webgl2") ?? (probe.getContext("webgl") as WebGLRenderingContext | null);
if (!gl) {
setFailed(true);
return;
}
gl.getExtension("WEBGL_lose_context")?.loseContext();
const [T, { RoundedBoxGeometry }] = await Promise.all([
import("three"),
import("three/examples/jsm/geometries/RoundedBoxGeometry.js"),
]);
if (cancelled) return;
apiRef.current = createConfigurator(T, RoundedBoxGeometry, {
canvas,
host,
label,
config: initialRef.current.config,
active: initialRef.current.active,
onPick: (part) => setActive(part),
onFirstFrame: () => setReady(true),
onFail: () => setFailed(true),
});
};
boot().catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
apiRef.current?.dispose();
apiRef.current = null;
};
}, [live]);
useEffect(() => {
apiRef.current?.setRunning(inView && pageVisible && !failed);
}, [inView, pageVisible, failed, ready]);
useEffect(() => {
apiRef.current?.apply(config, active);
}, [config, active, ready]);
// モーション低減では光らせない(値はその場で書き換わるので、最終状態がそのまま見える)
useEffect(() => {
if (!pulse || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const frames = [{ opacity: 1 }, { opacity: 0 }];
const timing = { duration: 900, easing: "ease-out" };
rowFlashRefs.current[pulse.id]?.animate(frames, timing);
for (const el of totalFlashRefs.current) el?.animate(frames, timing);
}, [pulse]);
const part = PARTS[PART_INDEX[active]];
const choice = config[active];
const lines = PARTS.map((p) => ({ part: p, choice: config[p.id], price: partPrice(p, config[p.id]) }));
const total = BASE_PRICE + lines.reduce((s, l) => s + l.price, 0);
const premiumCount = lines.filter((l) => SWATCH[l.choice.color].premium).length;
const weeks = premiumCount > 0 ? PREMIUM_LEAD_WEEKS : LEAD_WEEKS;
const changed = active !== "seat" || PARTS.some((p) => {
const a = config[p.id];
const b = DEFAULT_CONFIG[p.id];
return a.color !== b.color || a.finish !== b.finish;
});
const say = (next: Config, id: PartId) => {
const c = next[id];
const sum = BASE_PRICE + PARTS.reduce((s, p) => s + partPrice(p, next[p.id]), 0);
setAnnounce(`${PARTS[PART_INDEX[id]].name}を${SWATCH[c.color].name}・${FINISH[c.finish].name}に変更。合計の目安 ${yen(sum)}円`);
};
const choose = (patch: Partial<Choice>) => {
const next = { ...config, [active]: { ...config[active], ...patch } };
setConfig(next);
say(next, active);
setPulse((p) => ({ id: active, n: (p?.n ?? 0) + 1 }));
};
const pickPart = (id: PartId) => {
setActive(id);
};
const reset = () => {
setConfig(DEFAULT_CONFIG);
setActive("seat");
setQuoteShown(false);
setAnnounce(`初期の構成に戻しました。合計の目安 ${yen(BASE_PRICE + PARTS.reduce((s, p) => s + partPrice(p, DEFAULT_CONFIG[p.id]), 0))}円`);
};
const onStageKey = (e: KeyboardEvent<HTMLDivElement>) => {
const api = apiRef.current;
if (!api) return;
const moves: Record<string, [number, number]> = {
ArrowLeft: [-STEP, 0],
ArrowRight: [STEP, 0],
ArrowUp: [0, STEP / 2],
ArrowDown: [0, -STEP / 2],
};
if (e.key in moves) {
e.preventDefault();
api.nudge(...moves[e.key]);
} else if (e.key === "Home" || e.key === "Enter") {
e.preventDefault();
api.recenter();
}
};
// 問い合わせページへ渡す内容(見本では送らずに画面へ出す)
const quoteQuery = [
...lines.map((l) => `${l.part.id}=${l.choice.color}-${l.choice.finish}`),
`total=${total}`,
`weeks=${weeks}`,
].join("&");
const onQuote = (e: FormEvent<HTMLFormElement>) => {
if (QUOTE_ACTION) return;
e.preventDefault();
setQuoteShown(true);
};
const show3d = ready && !failed;
const focusRing = "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-amber-600";
return (
<section aria-labelledby={headingId} className="@container w-full max-w-5xl bg-white text-gray-900">
{/* 冒頭: 見出しと1行の案内だけにして、椅子と操作を最初の画面に入れる。数は小さな補助表示にまとめる */}
<div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1">
<h2 id={headingId} className="text-[clamp(1.3rem,3.2vw,1.9rem)] leading-[1.35] font-bold tracking-tight">
座面から脚まで、
<span className="whitespace-nowrap">部位ごとに選べる椅子</span>
</h2>
<p className="text-[11.5px] whitespace-nowrap text-gray-500 tabular-nums">
{PARTS.length}部位・{SWATCHES.length}色・{FINISHES.length}素材/{yen(COMBINATIONS)}通り
</p>
</div>
<p className="mt-1.5 text-[13px] leading-[1.75] font-medium text-gray-600">
椅子か部位ボタンで部位を選び、色と素材を替えると金額の目安が連動します
</p>
<div className="mt-4 grid gap-6 @2xl:grid-cols-[minmax(0,1fr)_16.5rem] @2xl:gap-9">
<div className="min-w-0">
<div
ref={stageRef}
tabIndex={0}
role="group"
aria-roledescription="3Dプレビュー"
aria-label={`椅子の3Dプレビュー。選択中の部位は${part.name}`}
aria-describedby={hintId}
onKeyDown={onStageKey}
className="relative aspect-[4/3] w-full overflow-hidden border border-gray-200 bg-[radial-gradient(60%_55%_at_50%_58%,rgba(217,119,6,0.06)_0%,rgba(255,255,255,0)_70%),linear-gradient(180deg,#ffffff_0%,#f7f5f1_100%)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-600"
>
{/* 平面図: 3Dが立ち上がるまで・縮小プレビュー・WebGL非対応のときの表示。同じ部位・色・素材を持つ */}
<div
className={`absolute inset-0 flex flex-col items-center justify-center p-4 transition-opacity duration-700 motion-reduce:transition-none ${
show3d ? "pointer-events-none opacity-0" : "opacity-100"
}`}
>
<svg viewBox="0 0 260 200" aria-hidden="true" className="block h-auto w-full max-w-[26rem]">
<defs>
<pattern id={`weave-${uid}`} width="3" height="3" patternUnits="userSpaceOnUse">
<path d="M0 0.75h1.5M1.5 2.25h1.5M0.75 0v1.5M2.25 1.5v1.5" stroke="rgba(255,255,255,0.3)" strokeWidth="0.7" />
</pattern>
<linearGradient id={`gloss-${uid}`} x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity="0.6" />
<stop offset="0.3" stopColor="#fff" stopOpacity="0" />
<stop offset="0.72" stopColor="#fff" stopOpacity="0" />
<stop offset="0.8" stopColor="#fff" stopOpacity="0.25" />
<stop offset="0.86" stopColor="#fff" stopOpacity="0" />
</linearGradient>
{/* 前面の丸み: 上端を明るく、下端を暗く */}
<linearGradient id={`shade-${uid}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity="0.2" />
<stop offset="0.45" stopColor="#fff" stopOpacity="0" />
<stop offset="1" stopColor="#000" stopOpacity="0.18" />
</linearGradient>
<radialGradient id={`floor-${uid}`}>
<stop offset="0" stopColor="#231f1b" stopOpacity="0.2" />
<stop offset="1" stopColor="#231f1b" stopOpacity="0" />
</radialGradient>
</defs>
<ellipse cx="130" cy="179" rx="108" ry="15" fill={`url(#floor-${uid})`} />
{[50, 210].map((x) => (
<ellipse key={x} cx={x} cy="186" rx="8" ry="1.8" fill="rgba(35,31,27,0.22)" />
))}
{FLAT_ORDER.map((id) => {
const c = config[id];
const hex = SWATCH[c.color].hex;
const on = id === active;
const overlay = c.finish === "fabric" ? `url(#weave-${uid})` : c.finish === "gloss" ? `url(#gloss-${uid})` : "none";
const stroke = on ? "#d97706" : "rgba(41,37,36,0.55)";
const strokeWidth = on ? 1.6 : 0.5;
return (
<g key={id} onClick={() => pickPart(id)} className="cursor-pointer">
{FLAT[id].faces.map((d) => (
<g key={d}>
<path d={d} fill={hex} />
<path d={d} fill={`url(#shade-${uid})`} />
<path d={d} fill={overlay} stroke={stroke} strokeWidth={strokeWidth} strokeLinejoin="round" />
</g>
))}
{FLAT[id].tops.map((d) => (
<g key={d}>
<path d={d} fill={hex} />
<path d={d} fill="rgba(255,255,255,0.24)" />
<path d={d} fill={overlay} stroke={stroke} strokeWidth={strokeWidth} strokeLinejoin="round" />
</g>
))}
</g>
);
})}
</svg>
{failed && (
<p className="mt-2 text-center text-[11px] leading-[1.7] text-gray-500">
この環境では3D表示が使えないため、平面図で表示しています
</p>
)}
</div>
<canvas
ref={canvasRef}
aria-hidden="true"
className={`absolute inset-0 block size-full cursor-grab touch-pan-y transition-opacity duration-700 motion-reduce:transition-none ${
show3d ? "opacity-100" : "pointer-events-none opacity-0"
}`}
/>
{/* 部位ラベル(位置は3D側が transform で書き換える) */}
<div
aria-hidden="true"
className={`pointer-events-none absolute inset-0 transition-opacity duration-500 motion-reduce:transition-none ${
show3d ? "opacity-100" : "opacity-0"
}`}
>
<span
ref={labelRef}
className="absolute top-0 left-0 bg-amber-600 px-2 py-1 text-[12.5px] leading-none font-bold whitespace-nowrap text-white opacity-0 shadow-[0_1px_2px_rgba(0,0,0,0.18)]"
>
<span className={`${montserrat.className} mr-1 text-[10.5px] font-semibold text-amber-100 tabular-nums`}>{part.no}</span>
{part.name}
{/* 部位を指す短い引き出し線(下端がアンカーの位置) */}
<span aria-hidden="true" className="absolute top-full left-1/2 h-3 w-px -translate-x-1/2 bg-amber-600" />
</span>
</div>
<p
id={hintId}
className={`pointer-events-none absolute bottom-2.5 left-3 bg-white/85 px-1.5 text-[10.5px] leading-[1.6] text-gray-500 transition-opacity duration-500 motion-reduce:transition-none ${
show3d ? "opacity-100" : "opacity-0"
}`}
>
クリックで部位を選択・ドラッグで回転
<span className="sr-only @md:not-sr-only">(矢印キーでも回転・Enterで部位の正面へ)</span>
</p>
</div>
{/* 操作(ここが入力の正。3Dのクリックは部位ラジオを選ぶ近道) */}
<div className="mt-6 grid gap-6">
<fieldset className="min-w-0">
<legend className="text-[12px] font-bold tracking-wide text-gray-500">部位を選ぶ</legend>
<div className="mt-2.5 grid grid-cols-4 border-y border-l border-gray-200">
{PARTS.map((p) => {
const on = p.id === active;
return (
<label
key={p.id}
className={`relative flex cursor-pointer flex-col items-center gap-1 border-r border-gray-200 px-1 py-2.5 text-center ${focusRing} ${
on ? "bg-amber-50/60" : "hover:bg-gray-50"
}`}
>
<input
type="radio"
name={`part-${uid}`}
value={p.id}
checked={on}
onChange={() => pickPart(p.id)}
className="sr-only"
/>
<span
aria-hidden="true"
className={`absolute inset-x-0 -bottom-px h-[3px] origin-left bg-amber-600 transition-transform duration-300 ease-out motion-reduce:transition-none ${
on ? "scale-x-100" : "scale-x-0"
}`}
/>
<span className={`${montserrat.className} text-[10px] font-semibold text-gray-400 tabular-nums`}>{p.no}</span>
<span className={`text-[13px] font-bold whitespace-nowrap ${on ? "text-gray-900" : "text-gray-600"}`}>{p.name}</span>
</label>
);
})}
</div>
</fieldset>
<fieldset className="min-w-0">
<legend className="text-[12px] font-bold tracking-wide text-gray-500">
{part.name}の色
<span className="ml-2 font-medium text-gray-400">藍・琥珀は受注色(+{yen(PREMIUM_PRICE)}円)</span>
</legend>
<div className="mt-2.5 grid grid-cols-5 gap-2">
{SWATCHES.map((s) => {
const on = choice.color === s.id;
return (
<label key={s.id} className={`flex cursor-pointer flex-col items-center gap-1.5 ${focusRing}`}>
<input
type="radio"
name={`color-${uid}`}
value={s.id}
checked={on}
onChange={() => choose({ color: s.id })}
className="sr-only"
/>
<span
aria-hidden="true"
className={`block aspect-square w-full max-w-12 border p-[3px] ${on ? "border-amber-600" : "border-gray-200 hover:border-gray-400"}`}
>
<span className="block size-full" style={{ backgroundColor: s.hex }} />
</span>
<span className={`text-[11.5px] leading-none whitespace-nowrap ${on ? "font-bold text-gray-900" : "text-gray-500"}`}>
{s.name}
</span>
</label>
);
})}
</div>
</fieldset>
<fieldset className="min-w-0">
<legend className="text-[12px] font-bold tracking-wide text-gray-500">{part.name}の素材</legend>
<div className="mt-2.5 grid grid-cols-3 border-y border-l border-gray-200">
{FINISHES.map((f) => {
const price = part.finishPrice[f.id];
const disabled = price === null;
const on = choice.finish === f.id;
return (
<label
key={f.id}
className={`flex flex-col gap-1 border-r border-gray-200 px-2.5 py-2.5 ${focusRing} ${
disabled
? "cursor-not-allowed bg-[repeating-linear-gradient(135deg,#fafaf9_0_6px,#f5f5f4_6px_7px)] text-gray-300"
: on
? "cursor-pointer bg-amber-50/60"
: "cursor-pointer hover:bg-gray-50"
}`}
>
<input
type="radio"
name={`finish-${uid}`}
value={f.id}
checked={on}
disabled={disabled}
onChange={() => choose({ finish: f.id })}
className="sr-only"
/>
<span className="flex items-center gap-2">
<span
aria-hidden="true"
className={`size-2.5 flex-none border ${on ? "border-amber-600 bg-amber-600" : disabled ? "border-gray-200" : "border-gray-400"}`}
/>
<span className={`text-[13px] font-bold ${disabled ? "" : on ? "text-gray-900" : "text-gray-600"}`}>{f.name}</span>
</span>
<span className={`text-[11px] tabular-nums ${disabled ? "" : "text-gray-500"}`}>
{disabled ? "選べません" : price === 0 ? "加算なし" : `+${yen(price)}円`}
</span>
</label>
);
})}
</div>
<p className="mt-2.5 text-[12px] leading-[1.8] text-gray-500">
{FINISH[choice.finish].note}
{active === "legs" && <span className="block">脚は荷重がかかり汚れやすいため、布は選べない設定にしています</span>}
</p>
</fieldset>
</div>
{/* 狭い幅: 構成表は操作欄の下に回るので、合計だけを画面下に貼り付けて操作中も見えるようにする(内容は構成表と同じ) */}
<div
aria-hidden="true"
className="sticky bottom-0 z-10 mt-5 flex items-baseline justify-between gap-3 border-t-2 border-amber-600 bg-white/95 py-2.5 @2xl:hidden"
>
<span className="text-[12px] font-bold text-gray-500">
合計の目安<span className="ml-2 font-medium text-gray-400">納期 約{weeks}週間</span>
</span>
<span className="relative flex items-baseline gap-0.5 px-1 whitespace-nowrap">
<span
ref={(el) => {
totalFlashRefs.current[0] = el;
}}
className="pointer-events-none absolute inset-0 bg-amber-100 opacity-0"
/>
<span className={`${montserrat.className} relative text-[1.3rem] leading-none font-bold tabular-nums`}>{yen(total)}</span>
<span className="relative text-[12px] font-bold">円</span>
</span>
</div>
</div>
{/* 構成の要約(選んだ内容・加算額・合計・納期) */}
<div className="min-w-0 @2xl:border-l @2xl:border-gray-200 @2xl:pl-9">
<p className="text-[12px] font-bold tracking-wide text-gray-500">構成と金額の目安</p>
<dl className="mt-3 border-t border-gray-200">
{lines.map(({ part: p, choice: c, price }) => (
<div
key={p.id}
className={`relative grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-x-3 border-b border-gray-200 py-2.5 pr-1.5 pl-3 ${
p.id === active ? "bg-amber-50/70" : ""
}`}
>
{/* 選択中の行は、3Dの縁取り・部位ボタンの下線と同じアンバーの縦線で示す */}
<span
aria-hidden="true"
className={`absolute inset-y-0 left-0 w-[3px] origin-top bg-amber-600 transition-transform duration-300 ease-out motion-reduce:transition-none ${
p.id === active ? "scale-y-100" : "scale-y-0"
}`}
/>
<span
aria-hidden="true"
ref={(el) => {
rowFlashRefs.current[p.id] = el;
}}
className="pointer-events-none absolute inset-0 bg-amber-100 opacity-0"
/>
<dt className={`relative text-[12.5px] font-bold whitespace-nowrap ${p.id === active ? "text-amber-700" : "text-gray-900"}`}>
<span className={`${montserrat.className} mr-1.5 text-[10px] font-semibold text-gray-400 tabular-nums`}>{p.no}</span>
{p.name}
</dt>
<dd className="relative flex min-w-0 items-center gap-1.5 text-[12px] text-gray-600">
<span aria-hidden="true" className="size-2.5 flex-none border border-gray-300" style={{ backgroundColor: SWATCH[c.color].hex }} />
<span className="truncate">
{SWATCH[c.color].name}・{FINISH[c.finish].name}
</span>
</dd>
<dd className="relative text-right text-[11.5px] whitespace-nowrap text-gray-500 tabular-nums">
{price === 0 ? "±0" : `+${yen(price)}`}
</dd>
</div>
))}
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3 border-b border-gray-200 py-2.5 pr-1.5 pl-3">
<dt className="text-[12.5px] font-bold text-gray-900">本体</dt>
<dd className="text-right text-[11.5px] text-gray-500 tabular-nums">{yen(BASE_PRICE)}</dd>
</div>
</dl>
<div className="mt-5">
<p className="text-[12px] font-bold text-gray-500">合計の目安(税込)</p>
<p className="relative mt-1.5 flex w-fit items-baseline gap-1 pr-1 whitespace-nowrap">
<span
aria-hidden="true"
ref={(el) => {
totalFlashRefs.current[1] = el;
}}
className="pointer-events-none absolute -inset-x-1 -inset-y-0.5 bg-amber-100 opacity-0"
/>
<span className={`${montserrat.className} relative text-[2rem] leading-none font-bold tracking-tight tabular-nums`}>{yen(total)}</span>
<span className="relative text-[13px] font-bold">円</span>
</p>
<p className="mt-3 border-t border-gray-100 pt-3 text-[12px] leading-[1.8] text-gray-600">
納期の目安 <span className="font-bold text-gray-900">約{weeks}週間</span>
<span className="block text-[11.5px] text-gray-400">
{premiumCount > 0 ? `受注色を${premiumCount}か所に含むため、標準より2週間ほど延びます` : "標準色だけの構成です"}
</span>
</p>
</div>
<div className="mt-6 flex flex-wrap items-center gap-x-5 gap-y-3">
<form action={QUOTE_ACTION ?? undefined} method="get" onSubmit={onQuote}>
{lines.map((l) => (
<input key={l.part.id} type="hidden" name={l.part.id} value={`${l.choice.color}-${l.choice.finish}`} />
))}
<input type="hidden" name="total" value={total} />
<input type="hidden" name="weeks" value={weeks} />
<button
type="submit"
className="group inline-flex cursor-pointer items-center text-[13px] font-semibold text-gray-900 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-amber-600"
>
<span className="relative">
この構成で見積もりを依頼
<span
aria-hidden="true"
className="absolute -bottom-1 left-0 h-px w-full origin-left scale-x-100 bg-gray-900 transition-transform duration-300 ease-out group-hover:scale-x-0 motion-reduce:transition-none"
/>
<span
aria-hidden="true"
className="absolute -bottom-1 left-0 h-px w-full origin-right scale-x-0 bg-amber-600 transition-transform delay-150 duration-300 ease-out group-hover:origin-left group-hover:scale-x-100 motion-reduce:transition-none"
/>
</span>
</button>
</form>
<button
type="button"
onClick={reset}
disabled={!changed}
className="text-[12px] font-medium text-gray-500 underline decoration-gray-300 underline-offset-4 hover:text-gray-900 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-amber-600 disabled:cursor-default disabled:text-gray-300 disabled:no-underline"
>
初期の構成に戻す
</button>
</div>
{quoteShown && (
<p role="status" className="mt-3 border-l-2 border-amber-600 pl-3 text-[11.5px] leading-[1.8] text-gray-600">
見本のため送信していません。送り先(QUOTE_ACTION)を設定すると、次の内容を問い合わせページへ渡します
<code className="mt-1 block font-mono text-[10.5px] break-all text-gray-500">?{quoteQuery}</code>
</p>
)}
<p aria-live="polite" className="sr-only">
{announce}
</p>
</div>
</div>
<p className="mt-8 border-t border-gray-200 pt-6 text-[12px] leading-[1.9] text-gray-500">
製品・価格・納期はすべて構成を示すためのサンプルです。自社の品目と価格表に差し替えてお使いください。見積もり依頼は、送り先を自社の問い合わせページに設定すると、選んだ構成・合計・納期をそのページへ渡します(見本では送信しません)。画面の色はディスプレイによって実物と異なって見えることがあります。
</p>
</section>
);
}
shadcn CLI でプロジェクトに追加
npx shadcn@latest add https://designs.first-ch.com/r/product-configurator-3d.json