From dc09b61779059fe6ce0b25a08eb71ae07767a827 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enes=20Yak=C4=B1=C5=9Ft=C4=B1r?= Date: Tue, 10 Nov 2026 19:13:46 +0300 Subject: [PATCH] feat: SketchUp klasik arayuzu, kisayollar, VCB olcu kutusu ve YakNet 3B bilesen havuzu --- apps/web/src/app/globals.css | 1128 +++++++++++- apps/web/src/components/SketchForgeEditor.tsx | 1601 ++++++++++++++--- apps/web/src/components/WorkplaneViewport.tsx | 946 ++++++++-- .../snapcad/AccessibilityCenter.tsx | 10 +- .../snapcad/EnterprisePrecisionBar.tsx | 88 +- .../snapcad/SketchUpDefaultTray.tsx | 990 ++++++++++ .../components/snapcad/SketchUpMenuBar.tsx | 532 ++++++ .../components/snapcad/SketchUpToolset.tsx | 251 +++ apps/web/src/lib/cloudComponents.ts | 356 ++++ apps/web/src/lib/shapeCatalog.ts | 4 + apps/web/src/lib/sketchupInterface.ts | 725 ++++++++ apps/web/src/lib/workplaneShapes.ts | 4 + cloud-api.php | 276 ++- database/schema.php | 25 + tests/unit/cloudComponents.test.ts | 87 + tests/unit/sketchupInterface.test.ts | 120 ++ 16 files changed, 6655 insertions(+), 488 deletions(-) create mode 100644 apps/web/src/components/snapcad/SketchUpDefaultTray.tsx create mode 100644 apps/web/src/components/snapcad/SketchUpMenuBar.tsx create mode 100644 apps/web/src/components/snapcad/SketchUpToolset.tsx create mode 100644 apps/web/src/lib/cloudComponents.ts create mode 100644 apps/web/src/lib/sketchupInterface.ts create mode 100644 tests/unit/cloudComponents.test.ts create mode 100644 tests/unit/sketchupInterface.test.ts diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 04f41f9..58c22bb 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -12559,9 +12559,9 @@ html[data-theme="light"] .enterprise-precision-bar { } .vcb-field { - width: 82px; + width: 122px; height: 24px; - padding: 0 24px 0 6px; + padding: 0 26px 0 8px; background: #0b0f19; border: 1px solid rgba(56, 189, 248, 0.4); border-radius: 5px; @@ -12676,8 +12676,16 @@ html[data-theme="light"] .enterprise-precision-bar { z-index: 45; } +.sketchforge-editor { + --editor-top: 80px; +} + +.sketchforge-editor.has-secondary-ribbon { + --editor-top: 156px; +} + .sketchforge-editor .secondary-toolbar { - top: 52px; + top: 80px; height: 76px; overflow-x: auto; overflow-y: hidden; @@ -12708,12 +12716,48 @@ html[data-theme="light"] .enterprise-precision-bar { } .sketchforge-editor .editor-body { - inset: 128px 0 38px 0 !important; - height: calc(100vh - 128px - 38px) !important; + inset: var(--editor-top, 80px) 0 38px 0 !important; + height: calc(100vh - var(--editor-top, 80px) - 38px) !important; + display: flex; + flex-direction: row; + overflow: hidden; } +.editor-center-stage { + position: relative; + flex: 1 1 auto; + min-width: 0; + height: 100%; + overflow: hidden; + display: flex; +} + +.editor-center-stage > .workplane-stage, +.sketchforge-editor .sketch-workspace-stage { + flex: 1 1 auto; + min-width: 0; + width: 100%; + height: 100% !important; +} + +.editor-center-stage > [aria-label="Boya Kovası ve Malzeme Paleti"] { + top: 12px; +} + +.sketchforge-editor .editor-toast { + left: 82px; + bottom: 48px; +} + +.sketchforge-editor .top-action-panel, .sketchforge-editor .edge-modifier-panel { - top: 138px !important; + top: calc(var(--editor-top, 80px) + 10px) !important; + z-index: 48; +} + +.sketchforge-editor.has-default-tray .edge-modifier-panel, +.sketchforge-editor.has-default-tray .top-action-panel { + right: 324px; } /* ========================================================================== @@ -14740,4 +14784,1076 @@ html[data-theme="light"] .error-action-btn.secondary { color: #38bdf8; } +/* ========================================================================== + SKETCHUP CLASSIC WORKSPACE CHROME (Menu Bar, Large Toolset, Default Tray) + ========================================================================== */ + +/* --- 1. Native-style Top Menu Bar (File..Help) --- */ +.sketchup-menubar { + position: fixed; + top: 52px; + left: 0; + right: 0; + height: 28px; + z-index: 44; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 0 10px; + background: #0d1322; + border-bottom: 1px solid rgba(148, 163, 184, 0.16); + color: #e2e8f0; + font-size: 12px; + user-select: none; +} + +html[data-theme="light"] .sketchup-menubar { + background: #f1f5f9; + border-bottom-color: #cbd5e1; + color: #1e293b; +} + +.sketchup-menubar-items { + display: flex; + align-items: center; + gap: 2px; + min-width: 0; +} + +.sketchup-menu-slot { + position: relative; +} + +.sketchup-menu-trigger { + display: inline-flex; + align-items: center; + height: 22px; + padding: 0 8px; + border: 1px solid transparent; + border-radius: 4px; + background: transparent; + color: inherit; + font-size: 12px; + font-weight: 600; + cursor: pointer; + white-space: nowrap; +} + +.sketchup-menu-trigger:hover, +.sketchup-menu-trigger.open { + background: rgba(56, 189, 248, 0.16); + border-color: rgba(56, 189, 248, 0.35); + color: #f8fafc; +} + +html[data-theme="light"] .sketchup-menu-trigger:hover, +html[data-theme="light"] .sketchup-menu-trigger.open { + background: #e2e8f0; + border-color: #94a3b8; + color: #0f172a; +} + +.sketchup-menu-trigger:focus-visible, +.sketchup-quick-chip:focus-visible, +.sketchup-menu-item:focus-visible, +.sketchup-tool-btn:focus-visible, +.sketchup-mini-pill:focus-visible, +.tray-section-trigger:focus-visible { + outline: 2px solid #38bdf8; + outline-offset: 1px; +} + +.sketchup-menu-dropdown { + position: absolute; + top: 26px; + left: 0; + z-index: 90; + min-width: 280px; + max-height: min(74vh, 520px); + overflow-y: auto; + padding: 5px; + background: #0f172a; + border: 1px solid rgba(148, 163, 184, 0.25); + border-radius: 8px; + box-shadow: 0 14px 36px rgba(2, 6, 23, 0.6); + display: flex; + flex-direction: column; + gap: 1px; +} + +html[data-theme="light"] .sketchup-menu-dropdown { + background: #ffffff; + border-color: #cbd5e1; + box-shadow: 0 12px 30px rgba(15, 23, 42, 0.18); +} + +.sketchup-menu-sep { + height: 1px; + margin: 4px 6px; + background: rgba(148, 163, 184, 0.18); +} + +html[data-theme="light"] .sketchup-menu-sep { + background: #e2e8f0; +} + +.sketchup-menu-item { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + padding: 5px 8px; + border: none; + border-radius: 5px; + background: transparent; + color: #e2e8f0; + font-size: 12px; + font-weight: 500; + text-align: left; + cursor: pointer; +} + +html[data-theme="light"] .sketchup-menu-item { + color: #1e293b; +} + +.sketchup-menu-item:hover:not(:disabled) { + background: #0284c7; + color: #ffffff; +} + +.sketchup-menu-item:disabled { + opacity: 0.42; + cursor: not-allowed; +} + +.sketchup-menu-check { + width: 14px; + height: 14px; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + color: #38bdf8; +} + +.sketchup-menu-item:hover:not(:disabled) .sketchup-menu-check { + color: #ffffff; +} + +.sketchup-menu-label { + flex: 1 1 auto; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sketchup-menu-shortcut { + margin-left: 10px; + padding: 1px 5px; + border-radius: 3px; + background: rgba(148, 163, 184, 0.14); + color: #94a3b8; + font-size: 10px; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} + +.sketchup-menu-item:hover:not(:disabled) .sketchup-menu-shortcut { + background: rgba(255, 255, 255, 0.2); + color: #ffffff; +} + +.sketchup-menubar-right { + display: flex; + align-items: center; + gap: 5px; + flex-shrink: 0; +} + +.sketchup-quick-chip { + display: inline-flex; + align-items: center; + gap: 4px; + height: 21px; + padding: 0 7px; + border-radius: 4px; + border: 1px solid rgba(148, 163, 184, 0.22); + background: rgba(255, 255, 255, 0.04); + color: #94a3b8; + font-size: 11px; + font-weight: 600; + cursor: pointer; +} + +html[data-theme="light"] .sketchup-quick-chip { + background: #ffffff; + border-color: #cbd5e1; + color: #475569; +} + +.sketchup-quick-chip.active { + background: rgba(14, 165, 233, 0.16); + border-color: rgba(56, 189, 248, 0.45); + color: #38bdf8; +} + +html[data-theme="light"] .sketchup-quick-chip.active { + background: #e0f2fe; + border-color: #0284c7; + color: #0369a1; +} + +.sketchup-quick-chip.keymap-chip { + background: rgba(16, 185, 129, 0.12); + border-color: rgba(16, 185, 129, 0.35); + color: #34d399; +} + +html[data-theme="light"] .sketchup-quick-chip.keymap-chip { + background: #ecfdf5; + border-color: #10b981; + color: #047857; +} + +/* --- 2. Left Large Toolset Dock --- */ +.sketchup-large-toolset { + width: 68px; + flex: 0 0 68px; + height: 100%; + overflow-y: auto; + overflow-x: hidden; + padding: 6px 5px; + background: #0b1120; + border-right: 1px solid rgba(148, 163, 184, 0.18); + display: flex; + flex-direction: column; + gap: 8px; + scrollbar-width: thin; + scrollbar-color: rgba(148, 163, 184, 0.3) transparent; +} + +html[data-theme="light"] .sketchup-large-toolset { + background: #f1f5f9; + border-right-color: #cbd5e1; +} + +.sketchup-tool-group { + display: flex; + flex-direction: column; + gap: 4px; + padding-bottom: 6px; + border-bottom: 1px solid rgba(148, 163, 184, 0.14); +} + +html[data-theme="light"] .sketchup-tool-group { + border-bottom-color: #cbd5e1; +} + +.sketchup-tool-group:last-child { + border-bottom: none; + padding-bottom: 10px; +} + +.sketchup-tool-grid, +.sketchup-mini-view-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 3px; +} + +.sketchup-tool-btn { + position: relative; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 5px; + border: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(30, 41, 59, 0.55); + color: #cbd5e1; + cursor: pointer; + transition: background-color 0.12s ease, border-color 0.12s ease, color 0.12s ease; +} + +html[data-theme="light"] .sketchup-tool-btn { + background: #ffffff; + border-color: #cbd5e1; + color: #334155; +} + +.sketchup-tool-btn:hover { + background: rgba(56, 189, 248, 0.16); + border-color: rgba(56, 189, 248, 0.45); + color: #ffffff; +} + +html[data-theme="light"] .sketchup-tool-btn:hover { + background: #e0f2fe; + border-color: #0284c7; + color: #0f172a; +} + +.sketchup-tool-btn.active { + background: #0284c7; + border-color: #38bdf8; + color: #ffffff; + box-shadow: 0 2px 8px rgba(2, 132, 199, 0.45); +} + +.sketchup-tool-key { + position: absolute; + right: 2px; + bottom: 1px; + font-size: 8px; + font-weight: 800; + line-height: 1; + opacity: 0.72; +} + +.sketchup-tool-sublabel { + font-size: 9px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; + color: #64748b; + text-align: center; +} + +.sketchup-mini-pill { + height: 20px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 4px; + border: 1px solid rgba(148, 163, 184, 0.18); + background: rgba(30, 41, 59, 0.45); + color: #94a3b8; + font-size: 8.5px; + font-weight: 800; + cursor: pointer; +} + +html[data-theme="light"] .sketchup-mini-pill { + background: #ffffff; + border-color: #cbd5e1; + color: #475569; +} + +.sketchup-mini-pill:hover, +.sketchup-mini-pill.active { + background: rgba(56, 189, 248, 0.22); + border-color: #38bdf8; + color: #38bdf8; +} + +html[data-theme="light"] .sketchup-mini-pill.active { + background: #0284c7; + border-color: #0284c7; + color: #ffffff; +} + +/* --- 3. Right Default Tray (Varsayılan Tepsi) --- */ +.sketchup-default-tray { + width: 310px; + flex: 0 0 310px; + height: 100%; + display: flex; + flex-direction: column; + background: #0b1120; + border-left: 1px solid rgba(148, 163, 184, 0.18); + color: #e2e8f0; + overflow: hidden; +} + +html[data-theme="light"] .sketchup-default-tray { + background: #f8fafc; + border-left-color: #cbd5e1; + color: #0f172a; +} + +.tray-top-header { + height: 32px; + padding: 0 12px; + display: flex; + align-items: center; + justify-content: space-between; + border-bottom: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(15, 23, 42, 0.9); + flex-shrink: 0; +} + +html[data-theme="light"] .tray-top-header { + background: #e2e8f0; + border-bottom-color: #cbd5e1; +} + +.tray-top-title { + font-size: 11px; + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.06em; + color: #94a3b8; +} + +html[data-theme="light"] .tray-top-title { + color: #334155; +} + +.tray-top-count { + font-size: 11px; + font-weight: 700; + color: #38bdf8; +} + +html[data-theme="light"] .tray-top-count { + color: #0284c7; +} + +.tray-accordion-scroll { + flex: 1 1 auto; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: thin; + scrollbar-color: rgba(148, 163, 184, 0.3) transparent; +} + +.tray-section { + border-bottom: 1px solid rgba(148, 163, 184, 0.14); +} + +html[data-theme="light"] .tray-section { + border-bottom-color: #e2e8f0; +} + +.tray-section-heading { + margin: 0; +} + +.tray-section-trigger { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 10px; + border: none; + background: rgba(30, 41, 59, 0.45); + color: #e2e8f0; + font-size: 12px; + font-weight: 700; + cursor: pointer; + text-align: left; +} + +html[data-theme="light"] .tray-section-trigger { + background: #f1f5f9; + color: #1e293b; +} + +.tray-section-trigger:hover { + background: rgba(56, 189, 248, 0.12); +} + +.tray-trigger-left { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.tray-section-body { + padding: 10px; + background: rgba(15, 23, 42, 0.45); +} + +html[data-theme="light"] .tray-section-body { + background: #ffffff; +} + +.tray-muted-note { + margin: 0; + font-size: 11.5px; + line-height: 1.45; + color: #94a3b8; +} + +html[data-theme="light"] .tray-muted-note { + color: #64748b; +} + +.tray-error-note { + margin: 0; + padding: 6px 8px; + border-radius: 6px; + background: rgba(239, 68, 68, 0.14); + color: #fca5a5; + font-size: 11px; +} + +html[data-theme="light"] .tray-error-note { + background: #fee2e2; + color: #b91c1c; +} + +.tray-form-stack { + display: flex; + flex-direction: column; + gap: 8px; +} + +.tray-field, +.tray-mini-field, +.tray-slider-field { + display: flex; + flex-direction: column; + gap: 3px; + font-size: 11px; + font-weight: 600; + color: #cbd5e1; +} + +html[data-theme="light"] .tray-field, +html[data-theme="light"] .tray-mini-field, +html[data-theme="light"] .tray-slider-field { + color: #334155; +} + +.tray-field input, +.tray-mini-field input, +.tray-select, +.tray-publish-box input { + width: 100%; + height: 27px; + padding: 0 8px; + border-radius: 5px; + border: 1px solid rgba(148, 163, 184, 0.25); + background: #0f172a; + color: #f8fafc; + font-size: 12px; +} + +html[data-theme="light"] .tray-field input, +html[data-theme="light"] .tray-mini-field input, +html[data-theme="light"] .tray-select, +html[data-theme="light"] .tray-publish-box input { + background: #ffffff; + border-color: #cbd5e1; + color: #0f172a; +} + +.tray-dim-row { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 6px; +} + +.tray-btn-row { + display: flex; + flex-wrap: wrap; + gap: 5px; +} + +.tray-pill-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + padding: 4px 8px; + border-radius: 5px; + border: 1px solid rgba(148, 163, 184, 0.25); + background: rgba(30, 41, 59, 0.65); + color: #cbd5e1; + font-size: 11px; + font-weight: 600; + cursor: pointer; +} + +html[data-theme="light"] .tray-pill-btn { + background: #f1f5f9; + border-color: #cbd5e1; + color: #334155; +} + +.tray-pill-btn.active { + background: rgba(14, 165, 233, 0.2); + border-color: #38bdf8; + color: #38bdf8; +} + +html[data-theme="light"] .tray-pill-btn.active { + background: #0284c7; + border-color: #0284c7; + color: #ffffff; +} + +.tray-comp-box { + display: flex; + flex-direction: column; + gap: 6px; + padding: 7px 8px; + border-radius: 6px; + background: rgba(56, 189, 248, 0.08); + border: 1px solid rgba(56, 189, 248, 0.22); +} + +.tray-comp-badge { + font-size: 11px; + font-weight: 700; + color: #38bdf8; +} + +.tray-action-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + padding: 6px 10px; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.28); + background: rgba(30, 41, 59, 0.8); + color: #e2e8f0; + font-size: 11.5px; + font-weight: 700; + cursor: pointer; +} + +html[data-theme="light"] .tray-action-btn { + background: #f1f5f9; + border-color: #cbd5e1; + color: #1e293b; +} + +.tray-action-btn.primary { + background: #0284c7; + border-color: #38bdf8; + color: #ffffff; +} + +.tray-search-box { + display: flex; + align-items: center; + gap: 6px; + padding: 0 8px; + height: 28px; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.25); + background: #0f172a; +} + +html[data-theme="light"] .tray-search-box { + background: #ffffff; + border-color: #cbd5e1; +} + +.tray-search-box input { + flex: 1 1 auto; + min-width: 0; + border: none; + background: transparent; + color: inherit; + font-size: 12px; + outline: none; +} + +.tray-icon-tiny { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + border-radius: 4px; + border: none; + background: transparent; + color: #94a3b8; + cursor: pointer; +} + +.tray-icon-tiny:hover { + background: rgba(148, 163, 184, 0.16); + color: #f8fafc; +} + +html[data-theme="light"] .tray-icon-tiny:hover { + color: #0f172a; +} + +.tray-icon-tiny.danger:hover { + background: rgba(239, 68, 68, 0.18); + color: #f87171; +} + +.tray-outliner-list, +.tray-tag-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 3px; + max-height: 200px; + overflow-y: auto; +} + +.tray-outliner-item, +.tray-tag-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 4px; + padding: 2px 4px; + border-radius: 5px; + background: rgba(30, 41, 59, 0.4); +} + +html[data-theme="light"] .tray-outliner-item, +html[data-theme="light"] .tray-tag-row { + background: #f1f5f9; +} + +.tray-outliner-item.selected { + background: rgba(2, 132, 199, 0.25); + outline: 1px solid rgba(56, 189, 248, 0.5); +} + +.tray-outliner-select, +.tray-tag-select { + flex: 1 1 auto; + min-width: 0; + display: flex; + align-items: center; + gap: 6px; + padding: 4px; + border: none; + background: transparent; + color: inherit; + font-size: 11.5px; + text-align: left; + cursor: pointer; +} + +.tray-mini-badge { + padding: 1px 4px; + border-radius: 3px; + background: rgba(56, 189, 248, 0.2); + color: #38bdf8; + font-size: 9px; + font-weight: 700; + flex-shrink: 0; +} + +.tray-outliner-actions { + display: flex; + align-items: center; + gap: 2px; +} + +.tray-outliner-actions button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + border: none; + border-radius: 4px; + background: transparent; + color: #94a3b8; + cursor: pointer; +} + +.tray-outliner-actions button:hover { + background: rgba(148, 163, 184, 0.16); + color: #ffffff; +} + +.tray-seg-tabs { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 4px; + padding: 3px; + border-radius: 6px; + background: #0f172a; +} + +html[data-theme="light"] .tray-seg-tabs { + background: #e2e8f0; +} + +.tray-seg-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + height: 24px; + border: none; + border-radius: 4px; + background: transparent; + color: #94a3b8; + font-size: 11px; + font-weight: 700; + cursor: pointer; +} + +.tray-seg-btn.active { + background: #0284c7; + color: #ffffff; +} + +.tray-prefab-list { + display: flex; + flex-direction: column; + gap: 5px; + max-height: 220px; + overflow-y: auto; +} + +.tray-prefab-card, +.tray-cloud-row { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(30, 41, 59, 0.5); + color: inherit; + text-align: left; + cursor: pointer; +} + +html[data-theme="light"] .tray-prefab-card, +html[data-theme="light"] .tray-cloud-row { + background: #f8fafc; + border-color: #cbd5e1; +} + +.tray-prefab-card:hover, +.tray-cloud-row:hover { + border-color: rgba(56, 189, 248, 0.45); +} + +.tray-prefab-dot { + width: 10px; + height: 10px; + border-radius: 50%; + flex-shrink: 0; +} + +.tray-prefab-info, +.tray-cloud-insert { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; + border: none; + background: transparent; + color: inherit; + text-align: left; + padding: 0; + cursor: pointer; +} + +.tray-prefab-info strong, +.tray-cloud-insert strong { + font-size: 11.5px; + font-weight: 700; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.tray-prefab-info small, +.tray-cloud-insert small { + font-size: 10px; + color: #94a3b8; +} + +.tray-publish-box { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px; + border-radius: 6px; + border: 1px solid rgba(56, 189, 248, 0.25); + background: rgba(14, 165, 233, 0.06); +} + +.tray-color-row { + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + gap: 5px; +} + +.tray-swatch { + height: 22px; + border-radius: 5px; + border: 2px solid transparent; + cursor: pointer; +} + +.tray-swatch.active { + border-color: #38bdf8; + box-shadow: 0 0 0 1px #0f172a; +} + +.tray-texture-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 5px; +} + +.tray-texture-tile { + display: flex; + flex-direction: column; + align-items: center; + gap: 3px; + padding: 5px 4px; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(30, 41, 59, 0.45); + color: inherit; + font-size: 10px; + font-weight: 600; + cursor: pointer; +} + +html[data-theme="light"] .tray-texture-tile { + background: #f1f5f9; + border-color: #cbd5e1; +} + +.tray-texture-tile.active { + border-color: #38bdf8; + background: rgba(56, 189, 248, 0.16); +} + +.tray-texture-swatch { + width: 100%; + height: 18px; + border-radius: 4px; +} + +.tray-style-list { + display: flex; + flex-direction: column; + gap: 4px; +} + +.tray-style-item { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.16); + background: rgba(30, 41, 59, 0.4); + color: inherit; + text-align: left; + cursor: pointer; +} + +html[data-theme="light"] .tray-style-item { + background: #f8fafc; + border-color: #cbd5e1; +} + +.tray-style-item.active { + border-color: #38bdf8; + background: rgba(56, 189, 248, 0.14); +} + +.tray-style-thumb { + width: 24px; + height: 24px; + border-radius: 5px; + border: 1px solid rgba(148, 163, 184, 0.35); + flex-shrink: 0; +} + +.tray-style-text { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; +} + +.tray-style-text strong { + font-size: 11.5px; + font-weight: 700; +} + +.tray-style-text small { + font-size: 10px; + color: #94a3b8; +} + +.tray-instructor-card { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px; + border-radius: 7px; + background: rgba(30, 41, 59, 0.5); + border: 1px solid rgba(148, 163, 184, 0.18); +} + +html[data-theme="light"] .tray-instructor-card { + background: #f8fafc; + border-color: #cbd5e1; +} + +.tray-instructor-head { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; +} + +.tray-instructor-head kbd { + padding: 1px 6px; + border-radius: 4px; + background: rgba(56, 189, 248, 0.2); + color: #38bdf8; + font-size: 10px; + font-weight: 700; +} + +.tray-instructor-hint { + margin: 0; + font-size: 11px; + line-height: 1.45; + color: #cbd5e1; +} + +html[data-theme="light"] .tray-instructor-hint { + color: #334155; +} + +.tray-instructor-steps { + margin: 0; + padding-left: 16px; + font-size: 11px; + line-height: 1.45; + color: #94a3b8; +} + +html[data-theme="light"] .tray-instructor-steps { + color: #475569; +} + +.tray-instructor-tip { + display: flex; + align-items: flex-start; + gap: 5px; + padding-top: 5px; + border-top: 1px dashed rgba(148, 163, 184, 0.25); + font-size: 10.5px; + color: #38bdf8; +} + +@media (max-width: 900px) { + .sketchup-default-tray { + width: 240px; + flex-basis: 240px; + } +} + diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 4bba80c..690ea0f 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -64,6 +64,26 @@ import { SketchWorkspace, type SketchMeasurement, type SketchPrimitive, type Ske import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel"; import { EnterprisePrecisionBar } from "./snapcad/EnterprisePrecisionBar"; import { EnterpriseTopBar } from "./snapcad/EnterpriseTopBar"; +import { SketchUpMenuBar } from "./snapcad/SketchUpMenuBar"; +import { SketchUpToolset } from "./snapcad/SketchUpToolset"; +import { SketchUpDefaultTray } from "./snapcad/SketchUpDefaultTray"; +import { + DEFAULT_SKETCHUP_PREFS, + SKETCHUP_PREFS_STORAGE_KEY, + SKETCHUP_TOOLS, + mapToolToCursorMode, + normalizeSketchUpPrefs, + parseVcbInput, + type DefaultTraySectionId, + type SketchUpToolId, + type SketchUpWorkspacePrefs, + type VisualStyleMode, +} from "@/lib/sketchupInterface"; +import { + detachComponentInstance, + getCloudUserPrefs, + saveCloudUserPrefs, +} from "@/lib/cloudComponents"; import { ARPreviewModal } from "./snapcad/ARPreviewModal"; import { FollowMeModal } from "./snapcad/FollowMeModal"; import { SolarStudyModal } from "./snapcad/SolarStudyModal"; @@ -5855,6 +5875,147 @@ export function SketchForgeEditor({ const [liveDragDistance, setLiveDragDistance] = useState(null); const [pendingPushPullValue, setPendingPushPullValue] = useState(null); const [isOrthographic, setIsOrthographic] = useState(false); + const [sketchUpPrefs, setSketchUpPrefs] = useState(DEFAULT_SKETCHUP_PREFS); + const sketchUpPrefsSyncTimerRef = useRef(null); + const [activeSketchUpTool, setActiveSketchUpTool] = useState("select"); + const [activeVisualStyle, setActiveVisualStyle] = useState("shaded"); + const [lastMoveVector, setLastMoveVector] = useState<{ dx: number; dy: number; dz: number; shapeIds: string[] } | null>(null); + const [lastCreatedShapeId, setLastCreatedShapeId] = useState(null); + const [vcbDisplayText, setVcbDisplayText] = useState(""); + + const persistSketchUpPrefs = useCallback((next: SketchUpWorkspacePrefs) => { + if (typeof window === "undefined") return; + try { + window.localStorage.setItem(SKETCHUP_PREFS_STORAGE_KEY, JSON.stringify(next)); + } catch { + // ignore localStorage quota errors + } + if (sketchUpPrefsSyncTimerRef.current !== null) { + window.clearTimeout(sketchUpPrefsSyncTimerRef.current); + } + sketchUpPrefsSyncTimerRef.current = window.setTimeout(() => { + sketchUpPrefsSyncTimerRef.current = null; + void saveCloudUserPrefs(next); + }, 500); + }, []); + + const updateSketchUpPrefs = useCallback( + (patch: Partial) => { + setSketchUpPrefs((current) => { + const next = normalizeSketchUpPrefs({ ...current, ...patch }); + persistSketchUpPrefs(next); + return next; + }); + }, + [persistSketchUpPrefs], + ); + + const openTraySection = useCallback( + (section: DefaultTraySectionId) => { + setSketchUpPrefs((current) => { + const openTraySections = current.openTraySections.includes(section) + ? current.openTraySections + : [...current.openTraySections, section]; + const next = normalizeSketchUpPrefs({ + ...current, + showDefaultTray: true, + openTraySections, + }); + persistSketchUpPrefs(next); + return next; + }); + }, + [persistSketchUpPrefs], + ); + + const toggleTraySection = useCallback( + (section: DefaultTraySectionId) => { + setSketchUpPrefs((current) => { + const exists = current.openTraySections.includes(section); + const openTraySections = exists + ? current.openTraySections.filter((s) => s !== section) + : [...current.openTraySections, section]; + const next = normalizeSketchUpPrefs({ ...current, openTraySections }); + persistSketchUpPrefs(next); + return next; + }); + }, + [persistSketchUpPrefs], + ); + + useEffect(() => { + let cancelled = false; + let localPrefs = DEFAULT_SKETCHUP_PREFS; + try { + const raw = window.localStorage.getItem(SKETCHUP_PREFS_STORAGE_KEY); + if (raw) { + localPrefs = normalizeSketchUpPrefs(JSON.parse(raw)); + setSketchUpPrefs(localPrefs); + } + } catch { + // ignore malformed localStorage + } + void getCloudUserPrefs().then((cloud) => { + if (cancelled || !cloud.ok || !cloud.prefs) return; + const merged = normalizeSketchUpPrefs({ ...localPrefs, ...cloud.prefs }); + setSketchUpPrefs(merged); + try { + window.localStorage.setItem(SKETCHUP_PREFS_STORAGE_KEY, JSON.stringify(merged)); + } catch { + // ignore storage quota errors + } + }); + return () => { + cancelled = true; + }; + }, []); + + useEffect(() => { + const onProjChanged = (event: Event) => { + const detail = (event as CustomEvent<{ isOrthographic?: boolean }>).detail; + if (typeof detail?.isOrthographic === "boolean") { + setIsOrthographic(detail.isOrthographic); + } + }; + const onVisualStyleEvt = (event: Event) => { + const style = (event as CustomEvent<{ style?: VisualStyleMode }>).detail?.style; + if (style) { + setActiveVisualStyle(style); + } + }; + window.addEventListener("snapcad:projection-changed", onProjChanged); + window.addEventListener("snapcad:set-visual-style", onVisualStyleEvt); + return () => { + window.removeEventListener("snapcad:projection-changed", onProjChanged); + window.removeEventListener("snapcad:set-visual-style", onVisualStyleEvt); + }; + }, []); + + const syncPushPullMode = useCallback((activeOrUpdater: boolean | ((prev: boolean) => boolean)) => { + setPushPullMode((prev) => { + const next = typeof activeOrUpdater === "function" ? activeOrUpdater(prev) : activeOrUpdater; + if (next) { + setPaintBucketMode(false); + setActiveSketchUpTool("push-pull"); + } else { + setActiveSketchUpTool((tool) => (tool === "push-pull" ? "select" : tool)); + } + return next; + }); + }, []); + + const syncPaintBucketMode = useCallback((activeOrUpdater: boolean | ((prev: boolean) => boolean)) => { + setPaintBucketMode((prev) => { + const next = typeof activeOrUpdater === "function" ? activeOrUpdater(prev) : activeOrUpdater; + if (next) { + setPushPullMode(false); + setActiveSketchUpTool("paint"); + } else { + setActiveSketchUpTool((tool) => (tool === "paint" ? "select" : tool)); + } + return next; + }); + }, []); const [sketchActive, setSketchActive] = useState(false); const [activeSketchWorkplane, setActiveSketchWorkplane] = useState( () => normalizePlacementWorkplane(initialPlacementWorkplane, initialPlacementElevation), @@ -7350,6 +7511,9 @@ export function SketchForgeEditor({ if (interactionHistoryTimerRef.current !== null) { window.clearTimeout(interactionHistoryTimerRef.current); } + if (sketchUpPrefsSyncTimerRef.current !== null) { + window.clearTimeout(sketchUpPrefsSyncTimerRef.current); + } sketchRevolveUpdateTimerRef.current.forEach((timer) => window.clearTimeout(timer)); sketchRevolveUpdateTimerRef.current.clear(); }; @@ -7540,7 +7704,7 @@ export function SketchForgeEditor({ commitShapes([...shapesRef.current, wallShape], wallShape.id, "Örnek Duvar eklendi"); playSynthesizedSound("pop"); } else if (actionType === "trigger_push_pull") { - setPushPullMode(true); + syncPushPullMode(true); setNotice("İt / Çek (Push/Pull) Modu aktif ('P') - Yüzeyleri uzatıp kısaltabilirsiniz"); playSynthesizedSound("pop"); } else if (actionType === "add_sample_roof") { @@ -7565,7 +7729,7 @@ export function SketchForgeEditor({ commitShapes([...shapesRef.current, roofShape], roofShape.id, "Örnek Çatı akıllıca tavana yerleştirildi"); playSynthesizedSound("pop"); } else if (actionType === "open_paint_bucket") { - setPaintBucketMode(true); + syncPaintBucketMode(true); setNotice("Boya Kovası Modu aktif ('B') - Doku ve renk seçip nesnelere tıklayın"); playSynthesizedSound("pop"); } else if (actionType === "create_component_sample") { @@ -7625,7 +7789,7 @@ export function SketchForgeEditor({ setIsARModalOpen(true); } }, - [commitShapes, handleRunStructuralTest], + [commitShapes, handleRunStructuralTest, syncPaintBucketMode, syncPushPullMode], ); const handleApplyWallCutout = useCallback( @@ -9736,6 +9900,643 @@ export function SketchForgeEditor({ ); }, [commitShapes, hasSelection, placementWorkplane, selectedIds, selectedShapes, shapes]); + const cursorCoordsRef = useRef(cursorCoords); + cursorCoordsRef.current = cursorCoords; + + const handleMakeComponent = useCallback(() => { + if (!hasSelection) { + setNotice("Bileşen (Component) oluşturmak için önce en az 1 nesne seçin"); + return; + } + const unlocked = selectedShapes.filter((s) => !s.locked); + if (unlocked.length === 0) { + setNotice("Seçili nesneler kilitli"); + return; + } + const selectedSet = new Set(unlocked.map((s) => s.id)); + const existingDef = unlocked.length === 1 ? unlocked[0].componentDefId : undefined; + const defId = existingDef || createLocalId("comp"); + const defName = + (unlocked.length === 1 ? unlocked[0].componentName : undefined) || + (unlocked.length === 1 ? unlocked[0].name : `${unlocked[0].name || "Bileşen"} Grubu`); + const nextShapes = shapesRef.current.map((shape) => + selectedSet.has(shape.id) + ? canonicalizeShape({ + ...shape, + componentDefId: defId, + componentName: defName, + }) + : shape, + ); + commitShapes( + nextShapes, + selectedIds, + `Bileşen tanımlandı: "${defName}" (${unlocked.length} öğe — kopyaladığınızda boyut ve malzeme senkronize edilir)`, + ); + playSynthesizedSound("chime"); + openTraySection("entity-info"); + }, [commitShapes, hasSelection, openTraySection, selectedIds, selectedShapes]); + + const handleMakeUnique = useCallback(() => { + if (!hasSelection) { + setNotice("Benzersiz yapmak için önce bir bileşen seçin"); + return; + } + const nextShapes = detachComponentInstance(shapesRef.current, selectedIds); + commitShapes( + nextShapes, + selectedIds, + "Seçili bileşen benzersiz (Make Unique) hale getirildi — kardeş kopyalardan ayrıldı", + ); + playSynthesizedSound("pop"); + }, [commitShapes, hasSelection, selectedIds]); + + const handleEraseShapeById = useCallback( + (shapeId: string) => { + const target = shapesRef.current.find((s) => s.id === shapeId); + if (!target) return; + if (target.locked) { + setNotice(`"${target.name || "Nesne"}" kilitli — Silgi (Eraser) kilidi açık nesneleri silebilir`); + return; + } + const next = shapesRef.current.filter((s) => s.id !== shapeId); + const nextSel = selectedIdsRef.current.filter((id) => id !== shapeId); + commitShapes(next, nextSel, `Silgi (E): "${target.name || "Nesne"}" silindi`); + playSynthesizedSound("pop"); + }, + [commitShapes], + ); + + const handleOffsetSelectedShape = useCallback( + (offsetMm = -15) => { + if (sketchActive) { + offsetCurrentSketch(offsetMm); + return; + } + const targets = selectedShapes.filter((s) => !s.locked); + if (targets.length === 0) { + setNotice("Ofset (F): En az bir kilitsiz şekil seçin (2B Eskizde iç/dış kontur, 3B'de eş merkezli kopya oluşturur)"); + return; + } + if (!Number.isFinite(offsetMm) || Math.abs(offsetMm) < 0.05) { + setNotice("Geçerli bir ofset mesafesi girin (örn. -10 veya 15 mm)"); + return; + } + const created: WorkplaneShape[] = targets.map((shape) => { + const clone = cloneWorkplaneShapeTreeWithFreshIds(shape, "offset"); + const nextWidth = Math.max(1, Number((shapeWidth(shape) + offsetMm * 2).toFixed(2))); + const nextDepth = Math.max(1, Number((shapeDepth(shape) + offsetMm * 2).toFixed(2))); + return canonicalizeShape({ + ...clone, + name: `${shape.name || "Şekil"} Ofset (${offsetMm > 0 ? `+${offsetMm}` : offsetMm} mm)`, + width: nextWidth, + depth: nextDepth, + size: Math.max(nextWidth, nextDepth), + elevation: offsetMm < 0 ? (shape.elevation ?? 0) + shape.height : (shape.elevation ?? 0), + }); + }); + commitShapes( + [...shapesRef.current, ...created], + created.map((s) => s.id), + `Ofset uygulandı (${offsetMm} mm): ${created.length} eş merkezli form eklendi`, + ); + playSynthesizedSound("chime"); + }, + [commitShapes, offsetCurrentSketch, selectedShapes, sketchActive], + ); + + const handleCommitDrawnShape = useCallback( + ( + kind: "box" | "cylinder" | "polygon", + bounds: { x: number; z: number; elevation: number; width: number; depth: number; height: number }, + ) => { + const label = + kind === "box" ? "Dikdörtgen Prizma" : kind === "cylinder" ? "Daire Silindir" : "Altıgen Prizma"; + const defaultColor = + kind === "box" ? "#e2e8f0" : kind === "cylinder" ? "#bae6fd" : "#fde68a"; + const w = Math.max(2, Number(bounds.width.toFixed(2))); + const d = Math.max(2, Number(bounds.depth.toFixed(2))); + const h = Math.max(1, Number(bounds.height.toFixed(2))); + const newShape = sceneShape({ + id: createLocalId(`draw-${kind}`), + name: label, + kind, + color: defaultColor, + x: Number(bounds.x.toFixed(2)), + z: Number(bounds.z.toFixed(2)), + elevation: Number(bounds.elevation.toFixed(2)), + width: w, + depth: d, + height: h, + size: Math.max(w, d), + sides: kind === "polygon" ? 6 : kind === "cylinder" ? 48 : undefined, + }); + setLastCreatedShapeId(newShape.id); + commitShapes( + [...shapesRef.current, newShape], + newShape.id, + `${label} oluşturuldu: ${w} × ${d} × ${h} mm (VCB kutusuna örn. 100;60 yazıp Enter'a basabilirsiniz)`, + ); + setVcbDisplayText(`${w};${d}`); + playSynthesizedSound("pop"); + }, + [commitShapes], + ); + + const handlePointerMoveVector = useCallback( + (vector: { dx: number; dy: number; dz: number; shapeIds: string[] }) => { + setLastMoveVector(vector); + const dist = Math.hypot(vector.dx, vector.dy, vector.dz); + if (dist > 0.01) { + setVcbDisplayText(dist.toFixed(2)); + } + }, + [], + ); + + const handleCommitVcbRaw = useCallback( + (raw: string) => { + const parsed = parseVcbInput(raw, { + prefer2dDimensions: activeSketchUpTool === "rectangle", + }); + if (parsed.kind === "empty") return; + if (parsed.kind === "invalid") { + setNotice("VCB biçimi anlaşılamadı. Örnek: 100;60 | 100;60;30 | *5 | /4 | 45° | 25"); + return; + } + + const targetIds = + selectedIdsRef.current.length > 0 + ? selectedIdsRef.current + : lastCreatedShapeId && shapesRef.current.some((s) => s.id === lastCreatedShapeId) + ? [lastCreatedShapeId] + : []; + const targetShapes = shapesRef.current.filter((s) => targetIds.includes(s.id) && !s.locked); + + if (parsed.kind === "array-multiply") { + const count = Math.min(40, Math.max(1, parsed.count)); + if (targetShapes.length === 0) { + setNotice("Doğrusal dizi (*N) için önce bir nesne seçin veya Taşı (Move) ile sürükleyin"); + return; + } + if (activeSketchUpTool === "rotate") { + const stepDeg = 15; + const copies: WorkplaneShape[] = []; + for (let i = 1; i <= count; i += 1) { + const angle = stepDeg * i; + for (const src of targetShapes) { + const clone = cloneWorkplaneShapeTreeWithFreshIds(src, "polar"); + copies.push( + canonicalizeShape({ + ...clone, + rotation: normalizeDegrees((src.rotation ?? 0) + angle), + }), + ); + } + } + commitShapes( + [...shapesRef.current, ...copies], + copies.map((c) => c.id), + `Dairesel dizi (*${count}): ${copies.length} kopya oluşturuldu (${stepDeg}° aralıkla)`, + ); + playSynthesizedSound("chime"); + return; + } + + const vec = lastMoveVector; + const hasValidVec = vec && Math.hypot(vec.dx, vec.dy, vec.dz) > 0.05; + const stepX = hasValidVec ? vec.dx : Math.max(25, shapeWidth(targetShapes[0]) + 10); + const stepY = hasValidVec ? vec.dy : 0; + const stepZ = hasValidVec ? vec.dz : 0; + const copies: WorkplaneShape[] = []; + for (let i = 1; i <= count; i += 1) { + for (const src of targetShapes) { + const clone = cloneWorkplaneShapeTreeWithFreshIds(src, "arr"); + copies.push( + canonicalizeShape({ + ...clone, + x: Number((src.x + stepX * i).toFixed(2)), + elevation: Number(((src.elevation ?? 0) + stepY * i).toFixed(2)), + z: Number((src.z + stepZ * i).toFixed(2)), + }), + ); + } + } + commitShapes( + [...shapesRef.current, ...copies], + [...targetIds, ...copies.map((c) => c.id)], + `Doğrusal dizi (*${count}): ${stepX.toFixed(1)}×${stepZ.toFixed(1)} adımla ${copies.length} kopya eklendi`, + ); + playSynthesizedSound("chime"); + return; + } + + if (parsed.kind === "array-divide") { + const count = Math.min(40, Math.max(2, parsed.count)); + if (targetShapes.length === 0) { + setNotice("Eşit aralıklı bölme (/N) için önce bir nesne seçin veya Taşı (Move) ile sürükleyin"); + return; + } + const vec = lastMoveVector; + const hasMoveOrigin = Boolean(vec && Math.hypot(vec.dx, vec.dy, vec.dz) > 0.05); + const spanX = hasMoveOrigin ? (vec as NonNullable).dx : Math.max(100, (shapeWidth(targetShapes[0]) + 10) * count); + const spanY = hasMoveOrigin ? (vec as NonNullable).dy : 0; + const spanZ = hasMoveOrigin ? (vec as NonNullable).dz : 0; + const sign = hasMoveOrigin ? -1 : 1; + const intermediates: WorkplaneShape[] = []; + for (let i = 1; i < count; i += 1) { + const t = i / count; + for (const src of targetShapes) { + const clone = cloneWorkplaneShapeTreeWithFreshIds(src, "div"); + intermediates.push( + canonicalizeShape({ + ...clone, + x: Number((src.x + sign * spanX * t).toFixed(2)), + elevation: Number(((src.elevation ?? 0) + sign * spanY * t).toFixed(2)), + z: Number((src.z + sign * spanZ * t).toFixed(2)), + }), + ); + } + } + commitShapes( + [...shapesRef.current, ...intermediates], + [...targetIds, ...intermediates.map((c) => c.id)], + `Aralık bölme (/${count}): ${intermediates.length} ara kopya yerleştirildi`, + ); + playSynthesizedSound("chime"); + return; + } + + if (parsed.kind === "dimensions-2d") { + if (targetShapes.length === 0) { + setNotice("Boyut güncellemek (W;D) için bir şekil seçin"); + return; + } + const nextW = Math.max(0.5, parsed.width); + const nextD = Math.max(0.5, parsed.depth); + const nextSet = new Set(targetShapes.map((s) => s.id)); + const next = shapesRef.current.map((s) => + nextSet.has(s.id) + ? canonicalizeShape({ ...s, width: nextW, depth: nextD, size: Math.max(nextW, nextD) }) + : s, + ); + commitShapes(next, targetIds, `VCB 2B ölçü uygulandı: ${nextW} × ${nextD} mm`); + playSynthesizedSound("pop"); + return; + } + + if (parsed.kind === "dimensions-3d") { + if (targetShapes.length === 0) { + setNotice("3B boyut güncellemek (W;D;H) için bir şekil seçin"); + return; + } + const nextW = Math.max(0.5, parsed.width); + const nextD = Math.max(0.5, parsed.depth); + const nextH = Math.max(0.5, parsed.height); + const nextSet = new Set(targetShapes.map((s) => s.id)); + const next = shapesRef.current.map((s) => + nextSet.has(s.id) + ? canonicalizeShape({ ...s, width: nextW, depth: nextD, height: nextH, size: Math.max(nextW, nextD) }) + : s, + ); + commitShapes(next, targetIds, `VCB 3B ölçü uygulandı: ${nextW} × ${nextD} × ${nextH} mm`); + playSynthesizedSound("pop"); + return; + } + + if (parsed.kind === "angle") { + if (activeSketchUpTool === "protractor") { + setArchitecturalGuides((curr) => [...curr, createAngledGuide(parsed.degrees, 0, 0)]); + setNotice(`Açılı kılavuz eklendi: ${parsed.degrees}°`); + playSynthesizedSound("pop"); + return; + } + if (targetShapes.length === 0) { + setNotice("Döndürmek için önce bir nesne seçin"); + return; + } + rotateSelectedBy(parsed.degrees); + return; + } + + const val = parsed.value; + if (activeSketchUpTool === "push-pull" || pushPullMode) { + setPendingPushPullValue(val); + setNotice(`İt/Çek VCB değeri uygulandı: ${val} mm`); + return; + } + if (activeSketchUpTool === "offset") { + handleOffsetSelectedShape(val); + return; + } + if (activeSketchUpTool === "rotate") { + rotateSelectedBy(val); + return; + } + if (activeSketchUpTool === "tape") { + const axis = axisLock ?? "x"; + setArchitecturalGuides((curr) => [...curr, createGuide(axis, val)]); + setNotice(`Kılavuz çizgisi (${axis.toUpperCase()} = ${val} mm) eklendi`); + playSynthesizedSound("pop"); + return; + } + if (activeSketchUpTool === "protractor") { + setArchitecturalGuides((curr) => [...curr, createAngledGuide(val, 0, 0)]); + setNotice(`İletki kılavuzu eklendi: ${val}°`); + playSynthesizedSound("pop"); + return; + } + if (activeSketchUpTool === "scale") { + if (targetShapes.length === 0 || val <= 0) { + setNotice("Ölçeklemek için pozitif bir çarpan (örn. 1.5 veya 2) girin ve nesne seçin"); + return; + } + const factor = Math.max(0.05, Math.min(50, val)); + const nextSet = new Set(targetShapes.map((s) => s.id)); + const next = shapesRef.current.map((s) => + nextSet.has(s.id) + ? canonicalizeShape({ + ...s, + width: Number((shapeWidth(s) * factor).toFixed(2)), + depth: Number((shapeDepth(s) * factor).toFixed(2)), + height: Number((s.height * factor).toFixed(2)), + size: Number((Math.max(shapeWidth(s), shapeDepth(s)) * factor).toFixed(2)), + }) + : s, + ); + commitShapes(next, targetIds, `Ölçek çarpanı uygulandı: ×${factor}`); + playSynthesizedSound("pop"); + return; + } + if (activeSketchUpTool === "move") { + if (targetShapes.length === 0) { + setNotice("Taşımak için önce bir nesne seçin"); + return; + } + const vec = lastMoveVector; + let dirX = axisLock === "z" ? 0 : 1; + let dirY = 0; + let dirZ = axisLock === "z" ? 1 : 0; + if (!axisLock && vec && Math.hypot(vec.dx, vec.dy, vec.dz) > 0.05) { + const len = Math.hypot(vec.dx, vec.dy, vec.dz); + dirX = vec.dx / len; + dirY = vec.dy / len; + dirZ = vec.dz / len; + } + const dx = Number((dirX * val).toFixed(2)); + const dy = Number((dirY * val).toFixed(2)); + const dz = Number((dirZ * val).toFixed(2)); + const nextSet = new Set(targetShapes.map((s) => s.id)); + const next = shapesRef.current.map((s) => + nextSet.has(s.id) + ? canonicalizeShape({ + ...s, + x: Number((s.x + dx).toFixed(2)), + elevation: Number(((s.elevation ?? 0) + dy).toFixed(2)), + z: Number((s.z + dz).toFixed(2)), + }) + : s, + ); + setLastMoveVector({ dx, dy, dz, shapeIds: targetIds }); + commitShapes(next, targetIds, `VCB taşıma uygulandı: ${val} mm`); + playSynthesizedSound("pop"); + return; + } + if (activeSketchUpTool === "circle" || activeSketchUpTool === "polygon") { + if (targetShapes.length === 0 || val <= 0) { + setNotice("Yarıçap güncellemek için pozitif bir yarıçap (mm) girin"); + return; + } + const dia = Number((val * 2).toFixed(2)); + const nextSet = new Set(targetShapes.map((s) => s.id)); + const next = shapesRef.current.map((s) => + nextSet.has(s.id) ? canonicalizeShape({ ...s, width: dia, depth: dia, size: dia }) : s, + ); + commitShapes(next, targetIds, `Yarıçap güncellendi: r = ${val} mm (çap ${dia} mm)`); + playSynthesizedSound("pop"); + return; + } + setPendingPushPullValue(val); + setNotice(`Hassas ölçü uygulandı: ${val} mm`); + }, + [ + activeSketchUpTool, + axisLock, + commitShapes, + handleOffsetSelectedShape, + lastCreatedShapeId, + lastMoveVector, + pushPullMode, + rotateSelectedBy, + ], + ); + + const handleCameraViewPreset = useCallback( + ( + view: + | "top" + | "bottom" + | "front" + | "back" + | "left" + | "right" + | "isometric" + | "extents" + | "selection" + | "previous" + | "two-point", + ) => { + if (typeof window === "undefined") return; + if (view === "isometric") { + window.dispatchEvent(new CustomEvent("snapcad:reset-view")); + } else if (view === "extents") { + window.dispatchEvent(new CustomEvent("snapcad:zoom-extents")); + } else if (view === "selection") { + window.dispatchEvent(new CustomEvent("snapcad:zoom-selection")); + } else if (view === "previous") { + window.dispatchEvent(new CustomEvent("snapcad:zoom-previous")); + } else if (view === "two-point") { + window.dispatchEvent(new CustomEvent("snapcad:toggle-two-point")); + } else { + window.dispatchEvent(new CustomEvent("snapcad:set-view-face", { detail: { face: view } })); + } + }, + [], + ); + + const handleSelectSketchUpTool = useCallback( + (tool: SketchUpToolId) => { + switch (tool) { + case "make-component": + handleMakeComponent(); + syncPushPullMode(false); + syncPaintBucketMode(false); + setActiveSketchUpTool("select"); + return; + case "follow-me": + setIsFollowMeModalOpen(true); + setNotice("Beni Takip Et (Follow Me) stüdyosu açıldı"); + return; + case "zoom-extents": + window.dispatchEvent(new CustomEvent("snapcad:zoom-extents")); + setNotice("Tüm model ekrana sığdırıldı (Zoom Extents - Shift+Z)"); + return; + case "zoom-selection": + window.dispatchEvent(new CustomEvent("snapcad:zoom-selection")); + setNotice("Seçili nesne çerçevelendi (Zoom Selection - Alt+Z)"); + return; + case "zoom-previous": + window.dispatchEvent(new CustomEvent("snapcad:zoom-previous")); + setNotice("Önceki kamera görünümüne dönüldü (Alt+P)"); + return; + case "section": + window.dispatchEvent(new CustomEvent("snapcad:toggle-section")); + setNotice("Kesit Düzlemi (Section Plane) değiştirildi"); + return; + case "walk": + window.dispatchEvent(new CustomEvent("snapcad:toggle-walk-mode")); + setNotice("İçinde Yürü (Walkthrough - WASD) modu değiştirildi"); + return; + case "xray": + setXRayMode((prev) => { + const next = !prev; + setNotice(next ? "Röntgen (X-Ray) Modu aktif (X)" : "Röntgen (X-Ray) Modu kapatıldı"); + playSynthesizedSound("pop"); + return next; + }); + return; + case "axes": + activateWorkplaneTool(); + setActiveSketchUpTool("axes"); + return; + case "protractor": { + const angles = [30, 45, 60, -30, -45]; + const nextAngle = angles[architecturalGuides.filter((g) => g.axis === "angle").length % angles.length]; + setArchitecturalGuides((current) => [...current, createAngledGuide(nextAngle, 0, 0)]); + setActiveSketchUpTool("protractor"); + syncPushPullMode(false); + syncPaintBucketMode(false); + setNotice(`İletki (Protractor): ${nextAngle}° kılavuzu eklendi (Farklı açı için VCB'ye örn. 35° yazın)`); + playSynthesizedSound("pop"); + return; + } + case "3d-text": { + const pt = calculateSmartPlacementPoint(shapesRef.current, { width: 42, depth: 10 }, placementWorkplane.origin); + const txtShape = sceneShape({ + id: createLocalId("text3d"), + name: "3B Metin", + kind: "text", + color: "#0ea5e9", + x: pt.x, + z: pt.z, + elevation: 0, + width: 42, + depth: 10, + height: 12, + size: 42, + text: "SNAPCAD", + font: "Multilanguage", + bevel: 0.4, + segments: 2, + }); + commitShapes([...shapesRef.current, txtShape], txtShape.id, "3B Metin eklendi"); + openTraySection("entity-info"); + playSynthesizedSound("pop"); + return; + } + case "line": + beginSketch("extrude"); + setActiveSketchTool("line"); + setActiveSketchUpTool("line"); + setNotice("Çizgi Aracı (Line - L) 2B Eskizde aktif"); + return; + case "freehand": + beginSketch("extrude"); + setActiveSketchTool("smooth"); + setActiveSketchUpTool("freehand"); + setNotice("Serbest Eğri (Freehand) 2B Eskizde aktif"); + return; + case "arc": + beginSketch("extrude"); + setActiveSketchTool("bezier"); + setActiveSketchUpTool("arc"); + setNotice("Yay / Eğri (Arc - A) 2B Eskizde aktif"); + return; + case "offset": + syncPushPullMode(false); + syncPaintBucketMode(false); + setActiveSketchUpTool("offset"); + handleOffsetSelectedShape(-15); + return; + case "tape": + syncPushPullMode(false); + syncPaintBucketMode(false); + setActiveSketchUpTool("tape"); + window.dispatchEvent(new CustomEvent("snapcad:toggle-ruler")); + setNotice(SKETCHUP_TOOLS.tape.hint); + return; + case "push-pull": + syncPushPullMode(true); + setNotice(`İt / Çek (Push/Pull - P): ${SKETCHUP_TOOLS["push-pull"].hint}`); + playSynthesizedSound("pop"); + return; + case "paint": + syncPaintBucketMode(true); + openTraySection("materials"); + setNotice(`Boya Kovası (Paint Bucket - B): ${SKETCHUP_TOOLS.paint.hint}`); + playSynthesizedSound("pop"); + return; + default: + syncPushPullMode(false); + syncPaintBucketMode(false); + setActiveSketchUpTool(tool); + if (tool === "select") setVcbDisplayText(""); + setNotice(`${SKETCHUP_TOOLS[tool].name}: ${SKETCHUP_TOOLS[tool].hint}`); + return; + } + }, + [ + activateWorkplaneTool, + architecturalGuides, + beginSketch, + commitShapes, + handleMakeComponent, + handleOffsetSelectedShape, + openTraySection, + placementWorkplane.origin, + setActiveSketchTool, + syncPaintBucketMode, + syncPushPullMode, + ], + ); + + const triggerRadarScan = useCallback(() => { + const currentShapes = shapesRef.current; + if (currentShapes.length === 0) { + speakTurkish("Sesli radar: Sahnede hiç nesne bulunmuyor."); + setNotice("Sesli radar: Sahnede hiç nesne bulunmuyor."); + } else if (selectedShapes.length > 0) { + sonifyAndAnnounceShape(selectedShapes[0]); + } else { + speakTurkish(`Sesli radar: ${currentShapes.length} nesne taranıyor.`); + setNotice(`Sesli radar: ${currentShapes.length} nesne taranıyor.`); + currentShapes.forEach((s, idx) => { + setTimeout(() => { + sonifyAndAnnounceShape(s); + }, idx * 240); + }); + } + }, [selectedShapes]); + + const triggerShortcutHelp = useCallback(() => { + const isClassic = sketchUpPrefs.keymapProfile === "classic-sketchup"; + const helpText = isClassic + ? "SketchUp Klasik + NVDA Kısayolları: Space Seçim, L Çizgi, R Dikdörtgen, C Daire, M Taşı, P İt-Çek, Q Döndür, S Ölçekle, F Ofset, E Silgi, B Boya, G Bileşen, O Yörünge, H Kaydır, Z Yakınlaştır, K Arka Kenarlar, X Röntgen, T Şerit Metre. NVDA Erişilebilirlik: İ veya F2 Sahne Denetçisi, Bölü veya V Komut Konsolu, F8 veya Alt+K Sesli Radar, Köşeli Parantez Nesne Gezintisi." + : "SnapCAD Standart + NVDA Kısayolları: İ Sahne Denetçisi, Bölü veya V Komut Konsolu, K veya F8 Sesli Radar, Köşeli Parantez Nesne Gezintisi, D Düzleme İndir, H Delik, S Katı, M Ayna, L Çizgi, T Şerit Metre, X Röntgen, P İt-Çek, B Boya."; + speakTurkish(helpText); + setNotice(helpText); + }, [sketchUpPrefs.keymapProfile]); + useEffect(() => { const isTypingTarget = (target: EventTarget | null) => { if (!(target instanceof HTMLElement)) { @@ -9752,6 +10553,7 @@ export function SketchForgeEditor({ const key = event.key.toLowerCase(); const shortcut = event.ctrlKey || event.metaKey; + const isClassicKeymap = sketchUpPrefs.keymapProfile === "classic-sketchup"; if (!isMovementKey(event.key) && !["Shift", "Control", "Meta", "Alt"].includes(event.key)) { keyboardMovement.finish(); @@ -9808,10 +10610,14 @@ export function SketchForgeEditor({ if (event.key === "Escape") { if (paintBucketMode) { - setPaintBucketMode(false); + syncPaintBucketMode(false); setNotice("Boya Kovası Modu kapatıldı"); return; } + if (activeSketchUpTool !== "select") { + handleSelectSketchUpTool("select"); + return; + } setSelectedIds([]); setNotice("Selection cleared"); return; @@ -9896,106 +10702,65 @@ export function SketchForgeEditor({ return; } - const geometryRotationDegrees = geometryRotationDegreesForShortcut(event); + const allowQuickRotateShortcut = !isClassicKeymap || event.shiftKey; + const geometryRotationDegrees = allowQuickRotateShortcut ? geometryRotationDegreesForShortcut(event) : null; if (geometryRotationDegrees !== null && hasSelection) { event.preventDefault(); rotateSelectedBy(geometryRotationDegrees); return; } + if ( + isClassicKeymap && + !shortcut && + !event.altKey && + !event.shiftKey && + (event.code === "Space" || event.key === " ") + ) { + const target = event.target instanceof HTMLElement ? event.target : null; + if (!target?.closest("button, a, [role='menuitem'], [role='menuitemcheckbox'], [role='tab'], [role='checkbox'], [role='radio'], summary")) { + event.preventDefault(); + handleSelectSketchUpTool("select"); + return; + } + } + if (isMovementKey(event.key)) { event.preventDefault(); keyboardMovement.keyDown(event); - } else if (key === "d" && hasSelection) { - event.preventDefault(); - dropSelectedToWorkplane(); - } else if (key === "h") { - event.preventDefault(); - setSelectionHoleMode(true); - } else if (key === "s") { - event.preventDefault(); - setSelectionHoleMode(false); - } else if (key === "m") { - event.preventDefault(); - toggleMirrorMode(); - } else if (key === "p" && !sketchActive) { - event.preventDefault(); - setPushPullMode((prev) => !prev); - } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyL" || key === "l") && !sketchActive) { - event.preventDefault(); - beginSketch("extrude"); - setActiveSketchTool("line"); - setNotice("Çizgi Çizim Modu aktif (L)"); - } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyT" || key === "t") && !sketchActive) { - event.preventDefault(); - const axis = Math.abs(cursorCoords.x) > Math.abs(cursorCoords.z) ? "z" : "x"; - const coord = axis === "z" ? cursorCoords.x : cursorCoords.z; - setArchitecturalGuides((current) => [...current, createGuide(axis, coord)]); - setNotice(`Şerit Metre / Kılavuz Çizgisi Eklendi (${axis.toUpperCase()} = ${coord.toFixed(1)} mm) - 'T'`); - playSynthesizedSound("pop"); - } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyX" || key === "x") && !sketchActive) { - event.preventDefault(); - setXRayMode((prev) => { - const next = !prev; - setNotice(next ? "Röntgen (X-Ray) Görünüm Modu aktif (X) - İç kısımlar görünür" : "Röntgen (X-Ray) Modu kapatıldı"); - playSynthesizedSound("pop"); - return next; - }); - } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyB" || key === "b") && !sketchActive) { - event.preventDefault(); - setPaintBucketMode((prev) => { - const next = !prev; - setNotice(next ? "Boya Kovası Modu Aktif (B) - Malzeme ve doku uygulamak için nesnelere tıklayın (Alt: Damlalık)" : "Boya Kovası kapatıldı"); - playSynthesizedSound("pop"); - return next; - }); } else if ( - (!shortcut && !event.altKey && !sketchActive && (event.code === "KeyI" || key === "i" || key === "ı")) || + (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyI" || key === "i" || key === "ı")) || event.key === "F2" || (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyA" || key === "a" || event.code === "KeyI" || key === "i")) ) { event.preventDefault(); handleOpenAudit(); } else if ( - (!shortcut && !event.altKey && !sketchActive && (event.code === "KeyV" || key === "v")) || + (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyV" || key === "v")) || event.key === "F4" || (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyV" || key === "v")) || (!shortcut && !event.altKey && (event.key === "/" || - event.code === "Slash" || event.code === "NumpadDivide" || - (event.shiftKey && (event.key === "/" || event.code === "Digit7")))) + (!event.shiftKey && event.code === "Slash"))) ) { event.preventDefault(); setIsVoiceCadModalOpen(true); } else if ( - (!shortcut && !event.altKey && !sketchActive && (event.code === "KeyK" || key === "k")) || + (!isClassicKeymap && !shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyK" || key === "k")) || event.key === "F8" || (event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyK" || key === "k" || event.code === "KeyS" || key === "s")) ) { event.preventDefault(); - const currentShapes = shapesRef.current; - if (currentShapes.length === 0) { - speakTurkish("Sesli radar: Sahnede hiç nesne bulunmuyor."); - } else if (selectedShapes.length > 0) { - sonifyAndAnnounceShape(selectedShapes[0]); - } else { - speakTurkish(`Sesli radar: ${currentShapes.length} nesne taranıyor.`); - currentShapes.forEach((s, idx) => { - setTimeout(() => { - sonifyAndAnnounceShape(s); - }, idx * 240); - }); - } + triggerRadarScan(); } else if ( - (!shortcut && !event.altKey && (key === "?" || (event.shiftKey && key === "?") || (!sketchActive && (key === "q" || event.code === "KeyQ")))) + !shortcut && + !event.altKey && + (key === "?" || (!isClassicKeymap && !event.shiftKey && (key === "q" || event.code === "KeyQ"))) ) { event.preventDefault(); - const helpText = - "SnapCAD 3B Kısayolları: İ tuşu sahne denetçisi. V tuşu sesli ve metin komut konsolu. K tuşu sesli radar taraması. Köşeli parantez tuşları nesneler arası gezinme. D tuşu çalışma düzlemine indirme. H tuşu delik modu. S tuşu katı modu. L tuşu çizgi çizimi. T tuşu şerit metre. X tuşu röntgen modu."; - speakTurkish(helpText); - setNotice(helpText); + triggerShortcutHelp(); } else if ( !shortcut && (event.code === "BracketLeft" || event.key === "[" || (event.altKey && event.key === "ArrowUp")) @@ -10028,57 +10793,175 @@ export function SketchForgeEditor({ } else { speakTurkish("Sahnede hiç nesne bulunmuyor."); } + } else if (!shortcut && !event.altKey && event.shiftKey && isClassicKeymap && (event.code === "KeyM" || key === "m")) { + event.preventDefault(); + toggleMirrorMode(); + } else if (!shortcut && !event.altKey && event.shiftKey && isClassicKeymap && (event.code === "KeyH" || key === "h")) { + event.preventDefault(); + setSelectionHoleMode(true); + } else if (!shortcut && !event.altKey && event.shiftKey && isClassicKeymap && (event.code === "KeyS" || key === "s")) { + event.preventDefault(); + setSelectionHoleMode(false); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyD" || key === "d") && hasSelection) { + event.preventDefault(); + dropSelectedToWorkplane(); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyP" || key === "p")) { + event.preventDefault(); + syncPushPullMode((prev) => !prev); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyL" || key === "l")) { + event.preventDefault(); + handleSelectSketchUpTool("line"); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyT" || key === "t")) { + event.preventDefault(); + const coords = cursorCoordsRef.current; + const axis = Math.abs(coords.x) > Math.abs(coords.z) ? "z" : "x"; + const coord = axis === "z" ? coords.x : coords.z; + setArchitecturalGuides((current) => [...current, createGuide(axis, coord)]); + syncPushPullMode(false); + syncPaintBucketMode(false); + setActiveSketchUpTool("tape"); + setNotice(`Şerit Metre / Kılavuz Çizgisi Eklendi (${axis.toUpperCase()} = ${coord.toFixed(1)} mm) - 'T'`); + playSynthesizedSound("pop"); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyX" || key === "x")) { + event.preventDefault(); + setXRayMode((prev) => { + const next = !prev; + setNotice(next ? "Röntgen (X-Ray) Görünüm Modu aktif (X) - İç kısımlar görünür" : "Röntgen (X-Ray) Modu kapatıldı"); + playSynthesizedSound("pop"); + return next; + }); + } else if (!shortcut && !event.altKey && !event.shiftKey && (event.code === "KeyB" || key === "b")) { + event.preventDefault(); + syncPaintBucketMode((prev) => { + const next = !prev; + setNotice( + next + ? "Boya Kovası Modu Aktif (B) - Malzeme ve doku uygulamak için nesnelere tıklayın (Alt: Damlalık)" + : "Boya Kovası kapatıldı", + ); + playSynthesizedSound("pop"); + return next; + }); + } else if (isClassicKeymap && !shortcut && !event.altKey && !event.shiftKey) { + if (event.code === "KeyG" || key === "g") { + event.preventDefault(); + handleMakeComponent(); + } else if (event.code === "KeyR" || key === "r") { + event.preventDefault(); + handleSelectSketchUpTool("rectangle"); + } else if (event.code === "KeyC" || key === "c") { + event.preventDefault(); + handleSelectSketchUpTool("circle"); + } else if (event.code === "KeyA" || key === "a") { + event.preventDefault(); + handleSelectSketchUpTool("arc"); + } else if (event.code === "KeyE" || key === "e") { + event.preventDefault(); + handleSelectSketchUpTool("eraser"); + } else if (event.code === "KeyM" || key === "m") { + event.preventDefault(); + handleSelectSketchUpTool("move"); + } else if (event.code === "KeyQ" || key === "q") { + event.preventDefault(); + handleSelectSketchUpTool("rotate"); + } else if (event.code === "KeyS" || key === "s") { + event.preventDefault(); + handleSelectSketchUpTool("scale"); + } else if (event.code === "KeyF" || key === "f") { + event.preventDefault(); + handleSelectSketchUpTool("offset"); + } else if (event.code === "KeyH" || key === "h") { + event.preventDefault(); + handleSelectSketchUpTool("pan"); + } else if (event.code === "KeyO" || key === "o") { + event.preventDefault(); + handleSelectSketchUpTool("orbit"); + } else if (event.code === "KeyZ" || key === "z") { + event.preventDefault(); + handleSelectSketchUpTool("zoom"); + } else if (event.code === "KeyK" || key === "k") { + event.preventDefault(); + const next = !sketchUpPrefs.backEdgesEnabled; + updateSketchUpPrefs({ backEdgesEnabled: next }); + setNotice(next ? "Arka Kenarlar (Back Edges - K) açıldı" : "Arka Kenarlar (K) kapatıldı"); + playSynthesizedSound("pop"); + } + } else if (!isClassicKeymap && !shortcut && !event.altKey && !event.shiftKey) { + if (key === "h") { + event.preventDefault(); + setSelectionHoleMode(true); + } else if (key === "s") { + event.preventDefault(); + setSelectionHoleMode(false); + } else if (key === "m") { + event.preventDefault(); + toggleMirrorMode(); + } } }; window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, [ - handleOpenAudit, - paintBucketMode, + activeSketchUpTool, beginSketch, - commitShapes, - offsetCurrentSketch, clearSketchMeasurement, + commitShapes, copySelected, cutSelected, deleteSelected, deleteSelectedSketchEntity, - duplicateSelected, dropSelectedToWorkplane, + duplicateSelected, groupSelected, + handleMakeComponent, + handleOpenAudit, + handleSelectSketchUpTool, hasSelection, keyboardMovement, + offsetCurrentSketch, + paintBucketMode, pasteShape, redo, rotateSelectedBy, rotateSelectedClosedSketch45, - sketchActive, - sketchRedo, - sketchMeasurement, - sketchSelection, - sketchUndo, - setSelectionHoleMode, - showHidden, - toggleHidden, - toggleMirrorMode, - toggleLocked, - toggleSelectedSketchImageLock, - setActiveSketchTool, - toolbarMode, - undo, - ungroupSelected, selectedIds, selectedShapes, + setActiveSketchTool, + setSelectionHoleMode, + shapes, + showHidden, + sketchActive, + sketchMeasurement, + sketchRedo, + sketchSelection, + sketchUndo, + sketchUpPrefs.backEdgesEnabled, + sketchUpPrefs.keymapProfile, + syncPaintBucketMode, + syncPushPullMode, + toggleHidden, + toggleLocked, + toggleMirrorMode, + toggleSelectedSketchImageLock, + toolbarMode, + triggerRadarScan, + triggerShortcutHelp, + undo, + ungroupSelected, + updateSketchUpPrefs, ]); + const secondaryRibbonVisible = sketchUpPrefs.showSecondaryRibbon || sketchActive; + const defaultTrayVisible = sketchUpPrefs.showDefaultTray && !(toolbarMode === "sketch" && sketchActive); + return (
{ if (event.dataTransfer?.types?.includes("Files")) { event.preventDefault(); @@ -10098,9 +10981,9 @@ export function SketchForgeEditor({ activeStudio={pushPullMode ? "push-pull" : "3d-solid"} onStudioChange={(studio) => { if (studio === "push-pull") { - setPushPullMode(true); + syncPushPullMode(true); } else if (studio === "3d-solid") { - setPushPullMode(false); + syncPushPullMode(false); } else if (onHome) { onHome(); } @@ -10123,126 +11006,203 @@ export function SketchForgeEditor({ cloudSyncStatus="synced" lastSyncedText="Eşitlendi" /> - setPushPullMode((prev) => !prev)} - toolbarMode={toolbarMode} - projectName={projectName} - onProjectNameChange={onProjectNameChange} - showProjectNameInToolbar={showProjectNameInToolbar} - onToolbarModeChange={(mode) => { - setToolbarMode(mode); - setWorkplaneMode(false); - setTopPanel(null); - setMenuOpen(false); + setXRayMode((prev) => !prev)} + isOrthographic={isOrthographic} + onToggleProjection={() => { + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("snapcad:toggle-projection")); + } }} canUndo={!projectInteractionActive && (historyIndex > 0 || Boolean(edgeModifier))} canRedo={!projectInteractionActive && historyIndex < history.length - 1} - canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} - canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))} - canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} - hasClipboard={clipboard.length > 0 || systemClipboardSupported} hasSelection={hasSelection} - hiddenShapeCount={shapes.filter((shape) => shape.hidden).length} - selectionHidden={hasSelection && selectedShapes.every((shape) => shape.hidden)} - alignMode={alignMode} - canAlign={selectedShapes.length > 1} - canEdgeModify={selectedShapes.length === 1 && Boolean(selectedShape && !selectedShape.locked && !selectedShape.hole)} - edgeModifierKind={edgeModifier?.kind ?? null} - mirrorMode={mirrorMode} - sketchActive={sketchActive} - sketchOperation={sketchOperation} - sketchTool={sketchTool} - sketchCanUndo={sketchHistoryIndex > 0} - sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1} - canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)} - onStartSketch={(operation) => beginSketch(operation)} - onEditSketch={beginSketchEdit} - onSketchTool={setActiveSketchTool} - onSketchPrimitive={(primitive) => addSketchPrimitive(primitive, { x: 0, z: 0 })} - onSketchImage={() => { - if (sketchTool !== "select") { - setNotice("Choose Select before adding a sketch image"); - return; - } - sketchImageInputRef.current?.click(); + canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} + canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} + hiddenCount={shapes.filter((shape) => shape.hidden).length} + guidesCount={architecturalGuides.length} + onUndo={undo} + onRedo={redo} + onCut={cutSelected} + onCopy={copySelected} + onPaste={pasteShape} + onDuplicate={duplicateSelected} + onDelete={deleteSelected} + onSelectAll={() => { + setSelectedIds(shapes.filter((shape) => !shape.hidden).map((shape) => shape.id)); + setNotice("Tüm görünür nesneler seçildi"); }} - onSketchUndo={sketchUndo} - onSketchRedo={sketchRedo} - onSketchFinish={finishSketch} - onSketchCancel={cancelSketch} - onHome={onHome} - onStartLine={() => { - beginSketch("extrude"); - setActiveSketchTool("line"); - setNotice("Çizgi Çizim Modu aktif (L)"); - }} - onOpenFollowMe={() => setIsFollowMeModalOpen(true)} - onOpenSolarStudy={() => setIsSolarModalOpen(true)} - onToggleGuides={() => { - const axis = Math.abs(cursorCoords.x) > Math.abs(cursorCoords.z) ? "z" : "x"; - const coord = axis === "z" ? cursorCoords.x : cursorCoords.z; - setArchitecturalGuides((current) => [...current, createGuide(axis, coord)]); - setNotice(`Şerit Metre / Kılavuz Çizgisi Eklendi (${axis.toUpperCase()} = ${coord.toFixed(1)} mm) - 'T'`); + onClearSelection={() => { + setSelectedIds([]); + setNotice("Seçim bırakıldı"); }} + onMakeComponent={handleMakeComponent} + onMakeUnique={handleMakeUnique} + onGroup={groupSelected} + onUngroup={ungroupSelected} + onToggleHidden={toggleHidden} + onShowHidden={showHidden} onClearGuides={() => { setArchitecturalGuides([]); setNotice("Tüm kılavuz çizgileri temizlendi"); }} - guidesCount={architecturalGuides.length} - onOffsetSketch={() => offsetCurrentSketch(-15)} - xRayMode={xRayMode} - onToggleXRay={() => { - setXRayMode((prev) => !prev); - }} + onOpenImport={() => setTopPanel("import")} + onOpenExport={() => setTopPanel("export")} + onBackToDashboard={onHome} onOpenLayers={() => setIsLayersModalOpen(true)} - onAddProtractorGuide={() => { - const angles = [30, 45, 60, -30, -45]; - const nextAngle = angles[architecturalGuides.filter((g) => g.axis === "angle").length % angles.length]; - setArchitecturalGuides((current) => [...current, createAngledGuide(nextAngle, 0, 0)]); - setNotice(`Açı Kılavuzu Eklendi (${nextAngle}° Çatı/Rampa Eğimi)`); - }} + onOpenSolar={() => setIsSolarModalOpen(true)} + onOpenFollowMe={() => setIsFollowMeModalOpen(true)} onOpenTerrain={() => setIsTerrainModalOpen(true)} - paintBucketMode={paintBucketMode} - onTogglePaintBucket={() => { - setPaintBucketMode((prev) => { - const next = !prev; - setNotice( - next - ? "Boya Kovası Modu Aktif (B) - Malzeme ve doku uygulamak için nesnelere tıklayın (Alt: Damlalık)" - : "Boya Kovası kapatıldı", - ); - return next; - }); + onOpenWallOpening={() => setIsWallOpeningModalOpen(true)} + onRunStructuralTest={handleRunStructuralTest} + onOpenAudit={handleOpenAudit} + onOpenVoiceCad={() => setIsVoiceCadModalOpen(true)} + onOpenTutorial={() => setIsInteractiveTutorialOpen(true)} + onOpenDailyChallenges={() => setIsDailyChallengesOpen(true)} + onOpenWorkspaceSettings={() => { + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("sketchforge:open-workspace-settings")); + } }} - onOpenWallCutout={() => setIsWallOpeningModalOpen(true)} - onAlign={toggleAlignMode} - onChamfer={() => edgeModifier?.kind === "chamfer" ? cancelEdgeModifier() : startEdgeModifier("chamfer")} - onCopy={copySelected} - onDelete={deleteSelected} - onDuplicate={duplicateSelected} - onDropToWorkplane={dropSelectedToWorkplane} - onGroup={groupSelected} - onIntersect={intersectSelected} - onFillet={() => edgeModifier?.kind === "fillet" ? cancelEdgeModifier() : startEdgeModifier("fillet")} - onMirror={toggleMirrorMode} - onPaste={pasteShape} - onRedo={redo} - onSnap={snapSelected} - onShowHidden={showHidden} - onToggleHidden={toggleHidden} - onUngroup={ungroupSelected} - onUndo={undo} - onTopPanel={(panel) => { - setTopPanel((current) => (current === panel ? null : panel)); - setMenuOpen(false); - }} - onAddShape={(shape) => { - addShape(shape); - setTopPanel(null); - setMenuOpen(false); + onOpenA11ySettings={() => { + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("snapcad:open-a11y-drawer")); + } }} + onReadShortcutHelp={triggerShortcutHelp} + onRadarScan={triggerRadarScan} + onCameraView={handleCameraViewPreset} /> + {secondaryRibbonVisible ? ( + syncPushPullMode((prev) => !prev)} + toolbarMode={toolbarMode} + projectName={projectName} + onProjectNameChange={onProjectNameChange} + showProjectNameInToolbar={showProjectNameInToolbar} + onToolbarModeChange={(mode) => { + setToolbarMode(mode); + setWorkplaneMode(false); + setTopPanel(null); + setMenuOpen(false); + }} + canUndo={!projectInteractionActive && (historyIndex > 0 || Boolean(edgeModifier))} + canRedo={!projectInteractionActive && historyIndex < history.length - 1} + canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} + canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))} + canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} + hasClipboard={clipboard.length > 0 || systemClipboardSupported} + hasSelection={hasSelection} + hiddenShapeCount={shapes.filter((shape) => shape.hidden).length} + selectionHidden={hasSelection && selectedShapes.every((shape) => shape.hidden)} + alignMode={alignMode} + canAlign={selectedShapes.length > 1} + canEdgeModify={selectedShapes.length === 1 && Boolean(selectedShape && !selectedShape.locked && !selectedShape.hole)} + edgeModifierKind={edgeModifier?.kind ?? null} + mirrorMode={mirrorMode} + sketchActive={sketchActive} + sketchOperation={sketchOperation} + sketchTool={sketchTool} + sketchCanUndo={sketchHistoryIndex > 0} + sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1} + canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)} + onStartSketch={(operation) => beginSketch(operation)} + onEditSketch={beginSketchEdit} + onSketchTool={setActiveSketchTool} + onSketchPrimitive={(primitive) => addSketchPrimitive(primitive, { x: 0, z: 0 })} + onSketchImage={() => { + if (sketchTool !== "select") { + setNotice("Choose Select before adding a sketch image"); + return; + } + sketchImageInputRef.current?.click(); + }} + onSketchUndo={sketchUndo} + onSketchRedo={sketchRedo} + onSketchFinish={finishSketch} + onSketchCancel={cancelSketch} + onHome={onHome} + onStartLine={() => { + beginSketch("extrude"); + setActiveSketchTool("line"); + setNotice("Çizgi Çizim Modu aktif (L)"); + }} + onOpenFollowMe={() => setIsFollowMeModalOpen(true)} + onOpenSolarStudy={() => setIsSolarModalOpen(true)} + onToggleGuides={() => { + const axis = Math.abs(cursorCoords.x) > Math.abs(cursorCoords.z) ? "z" : "x"; + const coord = axis === "z" ? cursorCoords.x : cursorCoords.z; + setArchitecturalGuides((current) => [...current, createGuide(axis, coord)]); + setNotice(`Şerit Metre / Kılavuz Çizgisi Eklendi (${axis.toUpperCase()} = ${coord.toFixed(1)} mm) - 'T'`); + }} + onClearGuides={() => { + setArchitecturalGuides([]); + setNotice("Tüm kılavuz çizgileri temizlendi"); + }} + guidesCount={architecturalGuides.length} + onOffsetSketch={() => offsetCurrentSketch(-15)} + xRayMode={xRayMode} + onToggleXRay={() => { + setXRayMode((prev) => !prev); + }} + onOpenLayers={() => setIsLayersModalOpen(true)} + onAddProtractorGuide={() => { + const angles = [30, 45, 60, -30, -45]; + const nextAngle = angles[architecturalGuides.filter((g) => g.axis === "angle").length % angles.length]; + setArchitecturalGuides((current) => [...current, createAngledGuide(nextAngle, 0, 0)]); + setNotice(`Açı Kılavuzu Eklendi (${nextAngle}° Çatı/Rampa Eğimi)`); + }} + onOpenTerrain={() => setIsTerrainModalOpen(true)} + paintBucketMode={paintBucketMode} + onTogglePaintBucket={() => { + syncPaintBucketMode((prev) => { + const next = !prev; + setNotice( + next + ? "Boya Kovası Modu Aktif (B) - Malzeme ve doku uygulamak için nesnelere tıklayın (Alt: Damlalık)" + : "Boya Kovası kapatıldı", + ); + return next; + }); + }} + onOpenWallCutout={() => setIsWallOpeningModalOpen(true)} + onAlign={toggleAlignMode} + onChamfer={() => edgeModifier?.kind === "chamfer" ? cancelEdgeModifier() : startEdgeModifier("chamfer")} + onCopy={copySelected} + onDelete={deleteSelected} + onDuplicate={duplicateSelected} + onDropToWorkplane={dropSelectedToWorkplane} + onGroup={groupSelected} + onIntersect={intersectSelected} + onFillet={() => edgeModifier?.kind === "fillet" ? cancelEdgeModifier() : startEdgeModifier("fillet")} + onMirror={toggleMirrorMode} + onPaste={pasteShape} + onRedo={redo} + onSnap={snapSelected} + onShowHidden={showHidden} + onToggleHidden={toggleHidden} + onUngroup={ungroupSelected} + onUndo={undo} + onTopPanel={(panel) => { + setTopPanel((current) => (current === panel ? null : panel)); + setMenuOpen(false); + }} + onAddShape={(shape) => { + addShape(shape); + setTopPanel(null); + setMenuOpen(false); + }} + /> + ) : null}
{toolbarMode === "sketch" && sketchActive ? ( ) : ( - modifierAvailableEdgeIds.includes(edge.id)) ?? []} - selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []} - onModifierEdgeToggle={toggleModifierEdge} - challengeTutorial={challengeTutorial} - onChallengeTutorialFinish={onChallengeTutorialFinish} - themePreference={themePreference} - resolvedTheme={resolvedTheme} - onThemePreferenceChange={onThemePreferenceChange} - pushPullMode={pushPullMode} - onPushPullModeChange={setPushPullMode} - onCursorUpdate={(coords, faceInfo) => { - setCursorCoords(coords); - setActiveFaceInfo(faceInfo ?? null); - }} - onPushPullDrag={setLiveDragDistance} - pendingPushPullValue={pendingPushPullValue} - onClearPendingPushPullValue={() => setPendingPushPullValue(null)} - architecturalGuides={architecturalGuides} - paintBucketMode={paintBucketMode} - onPaintShape={handlePaintShape} - /> + <> + {sketchUpPrefs.showLeftToolset ? ( + setXRayMode((prev) => !prev)} + backEdgesEnabled={sketchUpPrefs.backEdgesEnabled} + onToggleBackEdges={() => updateSketchUpPrefs({ backEdgesEnabled: !sketchUpPrefs.backEdgesEnabled })} + onCameraPreset={(v) => handleCameraViewPreset(v)} + /> + ) : null} +
+ modifierAvailableEdgeIds.includes(edge.id)) ?? []} + selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []} + onModifierEdgeToggle={toggleModifierEdge} + challengeTutorial={challengeTutorial} + onChallengeTutorialFinish={onChallengeTutorialFinish} + themePreference={themePreference} + resolvedTheme={resolvedTheme} + onThemePreferenceChange={onThemePreferenceChange} + pushPullMode={pushPullMode} + onPushPullModeChange={syncPushPullMode} + onCursorUpdate={(coords, faceInfo) => { + cursorCoordsRef.current = coords; + setCursorCoords(coords); + setActiveFaceInfo(faceInfo ?? null); + }} + onPushPullDrag={setLiveDragDistance} + pendingPushPullValue={pendingPushPullValue} + onClearPendingPushPullValue={() => setPendingPushPullValue(null)} + architecturalGuides={architecturalGuides} + paintBucketMode={paintBucketMode} + onPaintShape={handlePaintShape} + cursorToolMode={mapToolToCursorMode(activeSketchUpTool)} + keymapProfile={sketchUpPrefs.keymapProfile} + visualStyle={activeVisualStyle} + onVisualStyleChange={setActiveVisualStyle} + skyGroundEnabled={sketchUpPrefs.skyGroundEnabled} + backEdgesEnabled={sketchUpPrefs.backEdgesEnabled} + onEraseShape={handleEraseShapeById} + onCommitDrawnShape={handleCommitDrawnShape} + onPointerMoveVector={handlePointerMoveVector} + onVcbHintUpdate={setVcbDisplayText} + /> + + syncPaintBucketMode(false)} + activeTexture={activePaintTexture} + onSelectTexture={setActivePaintTexture} + activeColor={activePaintColor} + onSelectColor={setActivePaintColor} + /> +
+ {defaultTrayVisible ? ( + { + commitShapes(nextShapes, selectedIds, customNotice || "Sahne güncellendi"); + }} + onInsertShapes={(newShapes, customNotice) => { + commitShapes( + [...shapesRef.current, ...newShapes], + newShapes.map((s) => s.id), + customNotice || "Bileşen sahneye eklendi", + ); + playSynthesizedSound("chime"); + }} + onMakeComponent={handleMakeComponent} + onMakeUnique={handleMakeUnique} + activeTool={activeSketchUpTool} + visualStyle={activeVisualStyle} + onSelectVisualStyle={setActiveVisualStyle} + xRayMode={xRayMode} + onToggleXRay={() => setXRayMode((prev) => !prev)} + backEdgesEnabled={sketchUpPrefs.backEdgesEnabled} + onToggleBackEdges={() => updateSketchUpPrefs({ backEdgesEnabled: !sketchUpPrefs.backEdgesEnabled })} + skyGroundEnabled={sketchUpPrefs.skyGroundEnabled} + onToggleSkyGround={() => updateSketchUpPrefs({ skyGroundEnabled: !sketchUpPrefs.skyGroundEnabled })} + activePaintColor={activePaintColor} + onSelectPaintColor={setActivePaintColor} + activePaintTexture={activePaintTexture} + onSelectPaintTexture={setActivePaintTexture} + paintBucketMode={paintBucketMode} + onTogglePaintBucket={() => syncPaintBucketMode((prev) => !prev)} + solarSettings={solarSettings} + onChangeSolarSettings={setSolarSettings} + scenes={scenes} + onAddScene={handleAddScene} + onDeleteScene={handleDeleteScene} + onSelectScene={handleSelectScene} + onOpenLayersModal={() => setIsLayersModalOpen(true)} + onZoomSelection={() => handleCameraViewPreset("selection")} + onNotice={setNotice} + /> + ) : null} + )}
{edgeModifier ? ( @@ -10672,20 +11721,6 @@ export function SketchForgeEditor({ commitShapes([...shapesRef.current, newShape], newShape.id, `${newShape.name} eklendi`); }} /> - - setPaintBucketMode(false)} - activeTexture={activePaintTexture} - onSelectTexture={setActivePaintTexture} - activeColor={activePaintColor} - onSelectColor={setActivePaintColor} - /> setIsInteractiveTutorialOpen(false)} @@ -10749,19 +11784,29 @@ export function SketchForgeEditor({ cursorZ: cursorCoords.z, activeFaceInfo, currentValue: liveDragDistance, - valueLabel: pushPullMode ? "İtme / Çekme" : "Ölçü", + valueLabel: pushPullMode ? "İtme / Çekme" : undefined, isDragging: liveDragDistance !== null, }} activeTool={pushPullMode ? "push-pull" : "select"} - onToolChange={(tool) => setPushPullMode(tool === "push-pull")} + activeSketchUpTool={activeSketchUpTool} + vcbDisplayText={vcbDisplayText} + onToolChange={(tool) => syncPushPullMode(tool === "push-pull")} snapGrid={snapGrid} onSnapGridChange={setSnapGrid} isOrthographic={isOrthographic} - onToggleProjection={() => setIsOrthographic((prev) => !prev)} - onCommitValue={(val) => { - setPendingPushPullValue(val); - setNotice(`Hassas ölçü uygulandı: ${val} mm`); + onToggleProjection={() => { + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("snapcad:toggle-projection")); + } }} + onSetCameraView={(face) => handleCameraViewPreset(face)} + onResetView={() => { + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("snapcad:reset-view")); + } + }} + onCommitVcbRaw={handleCommitVcbRaw} + onCommitValue={(val) => handleCommitVcbRaw(String(val))} axisLock={axisLock} />
diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 7c7d284..1a97d6d 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -88,6 +88,21 @@ import { } from "@/components/workplane/TransformOverlay"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, MeasurementAccuracy, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; import type { CadModifierEdge } from "@/lib/cadModifierTypes"; +import type { UiKeymapProfile, ViewportCursorMode, VisualStyleMode } from "@/lib/sketchupInterface"; + +type ViewportRenderStyle = { + visualStyle: VisualStyleMode; + backEdges: boolean; + xRay: boolean; + theme: ResolvedAppTheme; +}; + +const DEFAULT_RENDER_STYLE: ViewportRenderStyle = { + visualStyle: "shaded", + backEdges: false, + xRay: false, + theme: "light", +}; const WORKPLANE_WIDTH = 200; const WORKPLANE_DEPTH = 140; @@ -261,6 +276,19 @@ type WorkplaneViewportProps = { architecturalGuides?: ArchitecturalGuide[]; paintBucketMode?: boolean; onPaintShape?: (shapeId: string, isEyedropper?: boolean) => void; + cursorToolMode?: ViewportCursorMode; + keymapProfile?: UiKeymapProfile; + visualStyle?: VisualStyleMode; + onVisualStyleChange?: (style: VisualStyleMode) => void; + skyGroundEnabled?: boolean; + backEdgesEnabled?: boolean; + onEraseShape?: (shapeId: string) => void; + onCommitDrawnShape?: ( + kind: "box" | "cylinder" | "polygon", + bounds: { x: number; z: number; elevation: number; width: number; depth: number; height: number }, + ) => void; + onPointerMoveVector?: (vector: { dx: number; dy: number; dz: number; shapeIds: string[] }) => void; + onVcbHintUpdate?: (text: string) => void; }; type WorkspaceSettings = WorkplaneWorkspaceSettings; @@ -319,6 +347,7 @@ type ThreeState = { controls: OrbitControls; workplaneLayer: THREE.Group; workplanePreviewLayer: THREE.Group; + drawPreviewLayer: THREE.Group; shapeLayer: THREE.Group; helperLayer: THREE.Group; transformGuideLayer: THREE.Group; @@ -337,6 +366,8 @@ type ThreeState = { lastOverlaySync: number; lastViewCubeSync: number; rotationHandleSides: RotationHandleSides | null; + getCursorToolMode?: () => ViewportCursorMode; + skyBackdropTexture?: THREE.Texture | null; disposeInteractionListeners: () => void; resize: () => void; }; @@ -999,10 +1030,15 @@ function shapeTransformSignature(shape: WorkplaneShape) { ].join("|"); } -function shapeMaterialSignature(shape: WorkplaneShape): string { +function shapeMaterialSignature(shape: WorkplaneShape, renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE): string { return JSON.stringify({ color: shape.color, + texture: shape.texture ?? "none", hole: Boolean(shape.hole), + visualStyle: renderStyle.visualStyle, + backEdges: renderStyle.backEdges, + xRay: renderStyle.xRay, + theme: renderStyle.theme, imagePlate: shapeResourceId(shape.imagePlate), imageData: shape.imagePlate?.dataUrl ?? "", sourceFormat: shape.importedMesh?.sourceFormat ?? "", @@ -1010,7 +1046,7 @@ function shapeMaterialSignature(shape: WorkplaneShape): string { cadEdges: shapeResourceId(shape.cadDisplayEdges), cadEdgesVersion: shape.cadDisplayEdgesVersion ?? 0, cadEdgeDimensions: shape.cadDisplayEdges?.length ? [shapeWidth(shape), shapeDepth(shape), shape.height] : null, - groupedMaterials: shape.groupedShapes?.map((child) => [child.id, child.hidden, shapeMaterialSignature(shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child)]), + groupedMaterials: shape.groupedShapes?.map((child) => [child.id, child.hidden, shapeMaterialSignature(shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child, renderStyle)]), }); } @@ -2451,6 +2487,16 @@ export function WorkplaneViewport({ architecturalGuides = [], paintBucketMode = false, onPaintShape, + cursorToolMode = "select", + keymapProfile = "classic-sketchup", + visualStyle: controlledVisualStyle, + onVisualStyleChange, + skyGroundEnabled = false, + backEdgesEnabled = false, + onEraseShape, + onCommitDrawnShape, + onPointerMoveVector, + onVcbHintUpdate, }: WorkplaneViewportProps) { const pushPullModeRef = useRef(pushPullMode); pushPullModeRef.current = pushPullMode; @@ -2458,6 +2504,27 @@ export function WorkplaneViewport({ paintBucketModeRef.current = paintBucketMode; const onPaintShapeRef = useRef(onPaintShape); onPaintShapeRef.current = onPaintShape; + const cursorToolModeRef = useRef(cursorToolMode); + cursorToolModeRef.current = cursorToolMode; + const keymapProfileRef = useRef(keymapProfile); + keymapProfileRef.current = keymapProfile; + const onEraseShapeRef = useRef(onEraseShape); + onEraseShapeRef.current = onEraseShape; + const onCommitDrawnShapeRef = useRef(onCommitDrawnShape); + onCommitDrawnShapeRef.current = onCommitDrawnShape; + const onPointerMoveVectorRef = useRef(onPointerMoveVector); + onPointerMoveVectorRef.current = onPointerMoveVector; + const onVcbHintUpdateRef = useRef(onVcbHintUpdate); + onVcbHintUpdateRef.current = onVcbHintUpdate; + const drawSessionRef = useRef<{ + kind: "rectangle" | "circle" | "polygon"; + pointerId: number; + startWorld: THREE.Vector3; + currentWorld: THREE.Vector3; + workplane: PlacementWorkplane; + plane: THREE.Plane; + hasMoved: boolean; + } | null>(null); const pushPullSessionRef = useRef<{ shapeId: string; initialShape: WorkplaneShape; @@ -2500,10 +2567,36 @@ export function WorkplaneViewport({ const walkKeysRef = useRef({ w: false, a: false, s: false, d: false, q: false, e: false, space: false }); const walkLastPointerRef = useRef({ x: 0, y: 0 }); const lastFootstepRef = useRef(0); - const [visualStyle, setVisualStyle] = useState<"shaded" | "blueprint" | "cyberpunk" | "clay">("shaded"); + const [internalVisualStyle, setInternalVisualStyle] = useState("shaded"); + const visualStyle: VisualStyleMode = controlledVisualStyle ?? internalVisualStyle; + const setVisualStyle = useCallback( + (nextStyle: VisualStyleMode) => { + if (controlledVisualStyle === undefined) { + setInternalVisualStyle(nextStyle); + } + onVisualStyleChange?.(nextStyle); + }, + [controlledVisualStyle, onVisualStyleChange], + ); + const [xRayActive, setXRayActive] = useState(false); + const renderStyle = useMemo( + () => ({ + visualStyle, + backEdges: backEdgesEnabled, + xRay: xRayActive, + theme: resolvedTheme, + }), + [backEdgesEnabled, resolvedTheme, visualStyle, xRayActive], + ); + const renderStyleRef = useRef(renderStyle); + renderStyleRef.current = renderStyle; + const skyGroundEnabledRef = useRef(skyGroundEnabled); + skyGroundEnabledRef.current = skyGroundEnabled; const [visualStylesMenuOpen, setVisualStylesMenuOpen] = useState(false); const [soundEnabled, setSoundEnabled] = useState(() => soundEngine.isEnabled()); const [twoPointMode, setTwoPointMode] = useState(false); + const twoPointModeRef = useRef(twoPointMode); + twoPointModeRef.current = twoPointMode; const cameraTransitionRef = useRef<{ startTime: number; duration: number; @@ -2982,6 +3075,7 @@ export function WorkplaneViewport({ shouldBuildCutPreviews(transformRef.current, dragRef.current), modifierActiveRef.current, placementWorkplaneRef.current, + renderStyleRef.current, ); refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { @@ -3043,6 +3137,7 @@ export function WorkplaneViewport({ shouldBuildCutPreviews(transformRef.current, dragRef.current), modifierActiveRef.current, placementWorkplaneRef.current, + renderStyleRef.current, ); refreshDragPreviewObjects(threeRef.current, dragRef.current); if (threeRef.current) { @@ -3074,6 +3169,7 @@ export function WorkplaneViewport({ !transformRef.current && !dragRef.current, modifierActive, placementWorkplaneRef.current, + renderStyleRef.current, ); if (threeRef.current) threeRef.current.needsRender = true; }, [modifierActive, renderSelectionIds]); @@ -3087,10 +3183,46 @@ export function WorkplaneViewport({ !transformRef.current && !dragRef.current, modifierActiveRef.current, placementWorkplaneRef.current, + renderStyleRef.current, ); if (threeRef.current) threeRef.current.needsRender = true; }, [modifierPreviewActive, renderSelectionIds]); + useEffect(() => { + const state = threeRef.current; + if (!state) return; + rebuildShapes( + state, + shapesRef.current, + renderSelectionIds(), + shouldBuildCutPreviews(transformRef.current, dragRef.current), + modifierActiveRef.current, + placementWorkplaneRef.current, + renderStyle, + ); + state.needsRender = true; + }, [renderSelectionIds, renderStyle]); + + useEffect(() => { + const state = threeRef.current; + if (!state) return; + if (cursorToolMode !== "rectangle" && cursorToolMode !== "circle" && cursorToolMode !== "polygon" && drawSessionRef.current) { + drawSessionRef.current = null; + disposeChildren(state.drawPreviewLayer); + state.controls.enabled = true; + } + if (cursorToolMode === "orbit") { + state.controls.mouseButtons.LEFT = THREE.MOUSE.ROTATE; + } else if (cursorToolMode === "pan") { + state.controls.mouseButtons.LEFT = THREE.MOUSE.PAN; + } else if (cursorToolMode === "zoom") { + state.controls.mouseButtons.LEFT = THREE.MOUSE.DOLLY; + } else { + state.controls.mouseButtons.LEFT = null; + } + state.needsRender = true; + }, [cursorToolMode]); + useEffect(() => { if (hoverModifierEdgeId !== null && !modifierEdges.some((edge) => edge.id === hoverModifierEdgeId)) { setHoverModifierEdgeId(null); @@ -3148,6 +3280,7 @@ export function WorkplaneViewport({ shouldBuildCutPreviews(transformRef.current, dragRef.current), modifierActiveRef.current, placementWorkplaneRef.current, + renderStyleRef.current, ); if (state) { syncTransformOverlay( @@ -3189,6 +3322,9 @@ export function WorkplaneViewport({ useLayoutEffect(() => { workspaceRef.current = workspace; rebuildWorkplane(threeRef.current, workspace, resolvedTheme, placementWorkplane); + if (threeRef.current) { + applySceneBackdrop(threeRef.current, renderStyleRef.current, skyGroundEnabledRef.current, workspace); + } rebuildSelectionHelpers(threeRef.current, shapesRef.current, renderSelectionIds(), placementWorkplane); if (threeRef.current) { syncTransformOverlay( @@ -3220,8 +3356,10 @@ export function WorkplaneViewport({ } const state = createThreeScene(host); + state.getCursorToolMode = () => cursorToolModeRef.current; threeRef.current = state; rebuildWorkplane(state, workspaceRef.current, resolvedThemeRef.current, placementWorkplaneRef.current); + applySceneBackdrop(state, renderStyleRef.current, skyGroundEnabledRef.current, workspaceRef.current); window.sketchforgeCaptureCanvas = () => { state.camera.updateMatrixWorld(); state.renderer.render(state.scene, state.camera); @@ -3245,7 +3383,7 @@ export function WorkplaneViewport({ }; perfRef.current.lastSample = performance.now(); resetCamera(state); - rebuildShapes(state, shapesRef.current, renderSelectionIds(), true, false, placementWorkplaneRef.current); + rebuildShapes(state, shapesRef.current, renderSelectionIds(), true, false, placementWorkplaneRef.current, renderStyleRef.current); const animate = () => { state.animationId = window.requestAnimationFrame(animate); @@ -3368,6 +3506,11 @@ export function WorkplaneViewport({ if (state.workplanePreviewLayer) { disposeChildren(state.workplanePreviewLayer); } + disposeChildren(state.drawPreviewLayer); + if (state.skyBackdropTexture) { + state.skyBackdropTexture.dispose(); + state.skyBackdropTexture = null; + } disposeChildren(state.shapeLayer); state.shapeRecords.clear(); disposeChildren(state.helperLayer); @@ -4629,6 +4772,54 @@ export function WorkplaneViewport({ return; } + const activeCursorMode = cursorToolModeRef.current; + if (activeCursorMode === "orbit" || activeCursorMode === "pan" || activeCursorMode === "zoom") { + return; + } + if (activeCursorMode === "eraser") { + event.preventDefault(); + const hitId = pickShape(event.clientX, event.clientY); + if (hitId) { + onEraseShapeRef.current?.(hitId); + } + return; + } + if (activeCursorMode === "rectangle" || activeCursorMode === "circle" || activeCursorMode === "polygon") { + event.preventDefault(); + const activeWorkplane = placementWorkplaneRef.current; + const normal = new THREE.Vector3(activeWorkplane.normal.x, activeWorkplane.normal.y, activeWorkplane.normal.z).normalize(); + const origin = new THREE.Vector3(activeWorkplane.origin.x, activeWorkplane.origin.y, activeWorkplane.origin.z); + const drawPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(normal, origin); + const point = toPlacementWorkplanePoint(event.clientX, event.clientY, activeWorkplane) + ?? toRawPlanePoint(event.clientX, event.clientY, drawPlane); + if (!point) { + return; + } + const startVec = new THREE.Vector3(point.x, point.y, point.z); + drawSessionRef.current = { + kind: activeCursorMode, + pointerId: event.pointerId, + startWorld: startVec.clone(), + currentWorld: startVec.clone(), + workplane: activeWorkplane, + plane: drawPlane, + hasMoved: false, + }; + event.currentTarget.setPointerCapture(event.pointerId); + state.controls.enabled = false; + onInteractionActiveChange?.(true); + onVcbHintUpdateRef.current?.("0.0;0.0"); + return; + } + if (activeCursorMode === "paint" || paintBucketModeRef.current) { + event.preventDefault(); + const hitId = pickShape(event.clientX, event.clientY); + if (hitId) { + onPaintShapeRef.current?.(hitId, Boolean(event.altKey)); + } + return; + } + const handle = pickTransformHandle(event.clientX, event.clientY); if (handle) { const shape = shapesRef.current.find((entry) => entry.id === handle.id); @@ -4815,7 +5006,8 @@ export function WorkplaneViewport({ if (!alreadySelected) { onSelectShape(id); } - if (!canBeginShapeDrag(workspaceRef.current.selectBeforeMove, alreadySelected)) { + const moveToolForcesDrag = cursorToolModeRef.current === "move"; + if (!moveToolForcesDrag && !canBeginShapeDrag(workspaceRef.current.selectBeforeMove, alreadySelected)) { return; } if (shape.locked) { @@ -4942,6 +5134,65 @@ export function WorkplaneViewport({ const snappedDist = step > 0 ? Math.round(rawDist / step) * step : Number(rawDist.toFixed(2)); session.currentDragDist = snappedDist; onPushPullDrag?.(snappedDist); + onVcbHintUpdateRef.current?.(snappedDist.toFixed(workspaceRef.current.accuracy)); + return; + } + + const drawSession = drawSessionRef.current; + if (drawSession) { + const state = threeRef.current; + if (!state) return; + const nextPoint = toPlacementWorkplanePoint(event.clientX, event.clientY, drawSession.workplane) + ?? toRawPlanePoint(event.clientX, event.clientY, drawSession.plane); + if (!nextPoint) return; + drawSession.currentWorld.set(nextPoint.x, nextPoint.y, nextPoint.z); + const spanX = Math.abs(drawSession.currentWorld.x - drawSession.startWorld.x); + const spanZ = Math.abs(drawSession.currentWorld.z - drawSession.startWorld.z); + if (Math.hypot(spanX, spanZ) > 0.5) { + drawSession.hasMoved = true; + } + const width = Math.max(1, Number(spanX.toFixed(2))); + const depth = Math.max(1, Number(spanZ.toFixed(2))); + const centerX = (drawSession.startWorld.x + drawSession.currentWorld.x) / 2; + const centerZ = (drawSession.startWorld.z + drawSession.currentWorld.z) / 2; + const baseElevation = (drawSession.startWorld.y + drawSession.currentWorld.y) / 2; + + disposeChildren(state.drawPreviewLayer); + const previewHeight = 0.4; + let previewGeom: THREE.BufferGeometry; + if (drawSession.kind === "circle") { + previewGeom = new THREE.CylinderGeometry(width / 2, width / 2, previewHeight, 48); + previewGeom.scale(1, 1, depth / Math.max(0.01, width)); + } else if (drawSession.kind === "polygon") { + previewGeom = new THREE.CylinderGeometry(width / 2, width / 2, previewHeight, 6); + previewGeom.scale(1, 1, depth / Math.max(0.01, width)); + } else { + previewGeom = new THREE.BoxGeometry(width, previewHeight, depth); + } + const fillMat = new THREE.MeshBasicMaterial({ + color: "#0ea5e9", + transparent: true, + opacity: 0.28, + depthWrite: false, + side: THREE.DoubleSide, + }); + const previewMesh = new THREE.Mesh(previewGeom, fillMat); + previewMesh.position.set(centerX, baseElevation + previewHeight / 2 + 0.06, centerZ); + const outlineEdges = new THREE.LineSegments( + new THREE.EdgesGeometry(previewGeom, 15), + new THREE.LineBasicMaterial({ color: "#0284c7", depthTest: false }), + ); + outlineEdges.position.copy(previewMesh.position); + setObjectRenderLayer(previewMesh, RENDER_LAYER_PREVIEWS); + setObjectRenderLayer(outlineEdges, RENDER_LAYER_PREVIEWS); + state.drawPreviewLayer.add(previewMesh, outlineEdges); + state.needsRender = true; + const acc = workspaceRef.current.accuracy; + onVcbHintUpdateRef.current?.( + drawSession.kind === "rectangle" + ? `${width.toFixed(acc)};${depth.toFixed(acc)}` + : `${(Math.max(width, depth) / 2).toFixed(acc)} r`, + ); return; } @@ -5075,6 +5326,9 @@ export function WorkplaneViewport({ threeRef.current.lastOverlaySync = performance.now(); threeRef.current.needsRender = true; } + if (Math.abs(deltaX) > 1e-4 || Math.abs(deltaY) > 1e-4 || Math.abs(deltaZ) > 1e-4) { + onVcbHintUpdateRef.current?.(Math.hypot(deltaX, deltaY, deltaZ).toFixed(workspaceRef.current.accuracy)); + } }, [pickPlacementSurface, setMarqueeFromState, toPlacementWorkplanePoint, toRawPlanePoint, updateModifierEdgeHover, updateRulerHover, updateTransform], ); @@ -5088,6 +5342,39 @@ export function WorkplaneViewport({ const finishDrag = useCallback( (event: ReactPointerEvent) => { + if (drawSessionRef.current) { + const session = drawSessionRef.current; + drawSessionRef.current = null; + if (event.currentTarget.hasPointerCapture(session.pointerId)) { + event.currentTarget.releasePointerCapture(session.pointerId); + } + const state = threeRef.current; + if (state) { + disposeChildren(state.drawPreviewLayer); + state.controls.enabled = true; + state.needsRender = true; + } + onInteractionActiveChange?.(false); + const spanX = Math.abs(session.currentWorld.x - session.startWorld.x); + const spanZ = Math.abs(session.currentWorld.z - session.startWorld.z); + const dragged = session.hasMoved && (spanX >= 2 || spanZ >= 2); + const width = dragged ? Math.max(2, Number(spanX.toFixed(2))) : 20; + const depth = dragged ? Math.max(2, Number(spanZ.toFixed(2))) : 20; + const x = dragged ? (session.startWorld.x + session.currentWorld.x) / 2 : session.startWorld.x; + const z = dragged ? (session.startWorld.z + session.currentWorld.z) / 2 : session.startWorld.z; + const elevation = Math.max(0, Number(((session.startWorld.y + session.currentWorld.y) / 2).toFixed(2))); + const kind = session.kind === "rectangle" ? "box" : session.kind === "circle" ? "cylinder" : "polygon"; + onCommitDrawnShapeRef.current?.(kind, { + x, + z, + elevation, + width, + depth, + height: 12, + }); + return; + } + if (pushPullSessionRef.current) { const session = pushPullSessionRef.current; pushPullSessionRef.current = null; @@ -5197,6 +5484,21 @@ export function WorkplaneViewport({ } }); + const primaryItem = drag.items[0]; + if (movedShape && primaryItem) { + const dx = primaryItem.nextX - primaryItem.startX; + const dy = primaryItem.nextElevation - primaryItem.startElevation; + const dz = primaryItem.nextZ - primaryItem.startZ; + onPointerMoveVectorRef.current?.({ + dx, + dy, + dz, + shapeIds: drag.items.map((item) => item.id), + }); + const distance = Math.hypot(dx, dy, dz); + onVcbHintUpdateRef.current?.(distance.toFixed(workspaceRef.current.accuracy)); + } + const moveDimensionSession = moveDimensionSessionRef.current; if (movedShape && moveDimensionSession) { moveDimensionSession.active = false; @@ -5464,7 +5766,8 @@ export function WorkplaneViewport({ const toggleTwoPointMode = useCallback(() => { const state = threeRef.current; if (!state) return; - const next = !twoPointMode; + const next = !twoPointModeRef.current; + twoPointModeRef.current = next; setTwoPointMode(next); if (next) { if (state.camera instanceof THREE.OrthographicCamera) { @@ -5483,7 +5786,7 @@ export function WorkplaneViewport({ state.controls.update(); state.needsRender = true; } - }, [twoPointMode]); + }, []); const setViewCubeFace = useCallback((face: ViewCubeFace) => { const state = threeRef.current; @@ -5751,12 +6054,15 @@ export function WorkplaneViewport({ } else if (shortcutView) { event.preventDefault(); setViewCubeFace(shortcutView); - } else if (key === "w") { + } else if (key === "w" && !event.ctrlKey && !event.metaKey && !event.altKey) { event.preventDefault(); if (!event.shiftKey || !setPlacementWorkplaneAtSelection()) { togglePlacementWorkplane(); } - } else if (key === "f" || event.key === "Home") { + } else if ( + (key === "f" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && keymapProfileRef.current !== "classic-sketchup") || + event.key === "Home" + ) { event.preventDefault(); resetView(); } else if ((event.key === "Z" && event.shiftKey) || (key === "z" && event.shiftKey)) { @@ -5768,7 +6074,10 @@ export function WorkplaneViewport({ } else if (event.altKey && (key === "p" || event.key === "P")) { event.preventDefault(); zoomPrevious(); - } else if (key === "o" && !event.ctrlKey && !event.metaKey && !event.altKey) { + } else if ( + (key === "o" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && keymapProfileRef.current !== "classic-sketchup") || + (key === "v" && event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey) + ) { event.preventDefault(); toggleProjection(); } else if (event.key === "+" || event.key === "=") { @@ -5817,13 +6126,61 @@ export function WorkplaneViewport({ const handleZoomSelection = () => zoomSelection(); const handleZoomPrevious = () => zoomPrevious(); const handleSetVisualStyle = (e: Event) => { - const style = (e as CustomEvent<{ style?: "shaded" | "blueprint" | "cyberpunk" | "clay" }>).detail?.style; - if (style && ["shaded", "blueprint", "cyberpunk", "clay"].includes(style)) { + const style = (e as CustomEvent<{ style?: VisualStyleMode }>).detail?.style; + if ( + style && + ["shaded", "wireframe", "hidden-line", "monochrome", "blueprint", "cyberpunk", "clay"].includes(style) + ) { setVisualStyle(style); soundEngine.playSnap(); } }; + const handleXRayToggle = (e: Event) => { + const enabled = (e as CustomEvent<{ enabled?: boolean }>).detail?.enabled; + setXRayActive((prev) => (typeof enabled === "boolean" ? enabled : !prev)); + }; + const handleSetViewFace = (e: Event) => { + const face = (e as CustomEvent<{ face?: ViewCubeFace }>).detail?.face; + if (face && ["top", "bottom", "front", "back", "right", "left"].includes(face)) { + setViewCubeFace(face); + } + }; + const handleResetView = () => resetView(); + const handleToggleProjection = () => toggleProjection(); + const handleToggleTwoPoint = () => toggleTwoPointMode(); + const handleToggleSection = (e: Event) => { + const enabled = (e as CustomEvent<{ enabled?: boolean }>).detail?.enabled; + setSectionSettings((s) => ({ + ...s, + enabled: typeof enabled === "boolean" ? enabled : !s.enabled, + })); + }; + const handleToggleRuler = () => { + const next = !rulerModeRef.current; + setRulerActive(next); + if (next) { + rulerDeleteModeRef.current = false; + setRulerDeleteMode(false); + rulerMoveModeRef.current = false; + setRulerMoveMode(false); + onWorkplaneModeChange(false); + } + }; + const handleSetLensFov = (e: Event) => { + const fov = (e as CustomEvent<{ fov?: number }>).detail?.fov; + if (typeof fov === "number" && Number.isFinite(fov) && fov >= 15 && fov <= 110) { + setCameraLens(fov); + } + }; window.addEventListener("snapcad:set-visual-style", handleSetVisualStyle); + window.addEventListener("snapcad:xray-toggle", handleXRayToggle); + window.addEventListener("snapcad:set-view-face", handleSetViewFace); + window.addEventListener("snapcad:reset-view", handleResetView); + window.addEventListener("snapcad:toggle-projection", handleToggleProjection); + window.addEventListener("snapcad:toggle-two-point", handleToggleTwoPoint); + window.addEventListener("snapcad:toggle-section", handleToggleSection); + window.addEventListener("snapcad:toggle-ruler", handleToggleRuler); + window.addEventListener("snapcad:set-lens-fov", handleSetLensFov); window.addEventListener("snapcad:toggle-walk-mode", handleToggleWalk); window.addEventListener("snapcad:goto-scene", handleGotoScene); window.addEventListener("snapcad:zoom-extents", handleZoomExtents); @@ -5839,25 +6196,23 @@ export function WorkplaneViewport({ window.removeEventListener("snapcad:zoom-extents", handleZoomExtents); window.removeEventListener("snapcad:goto-scene", handleGotoScene); window.removeEventListener("snapcad:toggle-walk-mode", handleToggleWalk); + window.removeEventListener("snapcad:set-lens-fov", handleSetLensFov); + window.removeEventListener("snapcad:toggle-ruler", handleToggleRuler); + window.removeEventListener("snapcad:toggle-section", handleToggleSection); + window.removeEventListener("snapcad:toggle-two-point", handleToggleTwoPoint); + window.removeEventListener("snapcad:toggle-projection", handleToggleProjection); + window.removeEventListener("snapcad:reset-view", handleResetView); + window.removeEventListener("snapcad:set-view-face", handleSetViewFace); + window.removeEventListener("snapcad:xray-toggle", handleXRayToggle); window.removeEventListener("snapcad:set-visual-style", handleSetVisualStyle); }; - }, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, setViewCubeFace, togglePlacementWorkplane, toggleProjection, toggleWalkMode, zoomCamera, zoomExtents, zoomSelection, zoomPrevious]); + }, [onWorkplaneModeChange, resetView, rulerToolsOpen, setCameraLens, setPlacementWorkplaneAtSelection, setRulerActive, setViewCubeFace, setVisualStyle, togglePlacementWorkplane, toggleProjection, toggleTwoPointMode, toggleWalkMode, zoomCamera, zoomExtents, zoomSelection, zoomPrevious]); useEffect(() => { const state = threeRef.current; if (!state) return; - if (visualStyle === "blueprint") { - state.scene.background = new THREE.Color("#0a2540"); - } else if (visualStyle === "cyberpunk") { - state.scene.background = new THREE.Color("#050914"); - } else if (visualStyle === "clay") { - state.scene.background = new THREE.Color("#e5e1d8"); - } else { - const palette = workplaneThemePalette(resolvedTheme, workspaceRef.current.background, workspaceRef.current.gridColor); - state.scene.background = new THREE.Color(palette.sceneBackground); - } - state.needsRender = true; - }, [visualStyle, resolvedTheme]); + applySceneBackdrop(state, renderStyle, skyGroundEnabled, workspaceRef.current); + }, [renderStyle, skyGroundEnabled]); return (
@@ -6048,61 +6403,35 @@ export function WorkplaneViewport({ {visualStylesMenuOpen && (
- - - - + {( + [ + { id: "shaded", icon: "🎨", label: "Gölgeli Doku (Shaded)", activeClass: "bg-indigo-600 text-white" }, + { id: "wireframe", icon: "🕸️", label: "Tel Kafes (Wireframe)", activeClass: "bg-sky-600 text-white" }, + { id: "hidden-line", icon: "✏️", label: "Gizli Çizgi (Hidden Line)", activeClass: "bg-slate-600 text-white" }, + { id: "monochrome", icon: "⬜", label: "Monokrom (Monochrome)", activeClass: "bg-slate-500 text-white" }, + { id: "blueprint", icon: "📐", label: "Mimari Ozalit (Blueprint)", activeClass: "bg-cyan-600 text-white" }, + { id: "cyberpunk", icon: "🟩", label: "Matrix (Cyberpunk)", activeClass: "bg-emerald-600 text-white" }, + { id: "clay", icon: "🏺", label: "Sıcak Kil (Clay Render)", activeClass: "bg-amber-700 text-white" }, + ] as const + ).map((styleOption) => ( + + ))}
)}
@@ -6336,7 +6665,33 @@ export function WorkplaneViewport({
{ event.preventDefault(); event.dataTransfer.dropEffect = "copy"; @@ -6540,6 +6895,9 @@ function createThreeScene(host: HTMLDivElement): ThreeState { workplanePreviewLayer.name = "WorkplanePreview"; workplanePreviewLayer.layers.set(RENDER_LAYER_PREVIEWS); workplanePreviewLayer.visible = false; + const drawPreviewLayer = new THREE.Group(); + drawPreviewLayer.name = "DrawPreview"; + drawPreviewLayer.layers.set(RENDER_LAYER_PREVIEWS); const shapeLayer = new THREE.Group(); shapeLayer.name = "Shapes"; shapeLayer.layers.set(RENDER_LAYER_SHAPES); @@ -6555,7 +6913,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState { const modifierLayer = new THREE.Group(); modifierLayer.name = "EdgeModifier"; modifierLayer.layers.set(RENDER_LAYER_MODIFIERS); - scene.add(workplaneLayer, workplanePreviewLayer, shapeLayer, helperLayer, transformGuideLayer, moveDimensionLayer, modifierLayer); + scene.add(workplaneLayer, workplanePreviewLayer, drawPreviewLayer, shapeLayer, helperLayer, transformGuideLayer, moveDimensionLayer, modifierLayer); const raycaster = new THREE.Raycaster(); raycaster.params.Line = { threshold: 1.15 }; @@ -6589,6 +6947,7 @@ function createThreeScene(host: HTMLDivElement): ThreeState { controls, workplaneLayer, workplanePreviewLayer, + drawPreviewLayer, shapeLayer, helperLayer, transformGuideLayer, @@ -6606,19 +6965,28 @@ function createThreeScene(host: HTMLDivElement): ThreeState { lastOverlaySync: 0, lastViewCubeSync: 0, rotationHandleSides: null, + skyBackdropTexture: null, disposeInteractionListeners: () => {}, resize, }; const requestRender = () => { state.needsRender = true; }; + const leftButtonForTool = (): THREE.MOUSE | null => { + const mode = state.getCursorToolMode?.() ?? "select"; + if (mode === "orbit") return THREE.MOUSE.ROTATE; + if (mode === "pan") return THREE.MOUSE.PAN; + if (mode === "zoom") return THREE.MOUSE.DOLLY; + return null; + }; const configureSketchForgeMouseButtons = (event: PointerEvent) => { - controls.mouseButtons.LEFT = event.button === 0 && (event.ctrlKey || event.metaKey) ? THREE.MOUSE.PAN : null; + const toolLeft = leftButtonForTool(); + controls.mouseButtons.LEFT = toolLeft ?? (event.button === 0 && (event.ctrlKey || event.metaKey) ? THREE.MOUSE.PAN : null); controls.mouseButtons.MIDDLE = THREE.MOUSE.PAN; controls.mouseButtons.RIGHT = THREE.MOUSE.ROTATE; }; const resetSketchForgeMouseButtons = () => { - controls.mouseButtons.LEFT = null; + controls.mouseButtons.LEFT = leftButtonForTool(); controls.mouseButtons.MIDDLE = THREE.MOUSE.PAN; controls.mouseButtons.RIGHT = THREE.MOUSE.ROTATE; }; @@ -6635,37 +7003,6 @@ function createThreeScene(host: HTMLDivElement): ThreeState { requestRender(); }; window.addEventListener("snapcad:solar-update", onSolarUpdate); - const onXRayToggle = (e: Event) => { - const enabled = Boolean((e as CustomEvent).detail?.enabled); - state.shapeRecords.forEach((record) => { - const applyMat = (mat: THREE.Material) => { - if (mat instanceof THREE.MeshStandardMaterial) { - if (enabled) { - mat.transparent = true; - mat.opacity = 0.38; - mat.depthWrite = false; - } else { - mat.transparent = Boolean(record.shape.hole || record.shape.texture === "glass" || record.shape.imagePlate); - mat.opacity = record.shape.hole ? 0.5 : (record.shape.imagePlate?.opacity ?? 1); - mat.depthWrite = true; - } - mat.needsUpdate = true; - } - }; - record.object.traverse((child) => { - if (child instanceof THREE.Mesh) { - const mat = child.material; - if (Array.isArray(mat)) { - mat.forEach(applyMat); - } else if (mat) { - applyMat(mat); - } - } - }); - }); - requestRender(); - }; - window.addEventListener("snapcad:xray-toggle", onXRayToggle); controls.addEventListener("change", requestRender); renderer.domElement.addEventListener("pointerdown", configureSketchForgeMouseButtons, { capture: true }); renderer.domElement.addEventListener("pointerup", resetSketchForgeMouseButtons); @@ -6675,7 +7012,6 @@ function createThreeScene(host: HTMLDivElement): ThreeState { renderer.domElement.addEventListener("pointerdown", requestRender); state.disposeInteractionListeners = () => { window.removeEventListener("snapcad:solar-update", onSolarUpdate); - window.removeEventListener("snapcad:xray-toggle", onXRayToggle); controls.removeEventListener("change", requestRender); renderer.domElement.removeEventListener("pointerdown", configureSketchForgeMouseButtons, { capture: true }); renderer.domElement.removeEventListener("pointerup", resetSketchForgeMouseButtons); @@ -6833,6 +7169,13 @@ function toggleCameraProjection(state: ThreeState) { state.controls.object = next; state.controls.update(); state.needsRender = true; + if (typeof window !== "undefined") { + window.dispatchEvent( + new CustomEvent("snapcad:projection-changed", { + detail: { isOrthographic: next instanceof THREE.OrthographicCamera }, + }), + ); + } } function setCameraToViewFace(state: ThreeState, face: ViewCubeFace) { @@ -6995,6 +7338,83 @@ function rebuildWorkplane( freezeStaticObjectMatrices(state.workplaneLayer); } +function createSkyGroundBackdropTexture(theme: ResolvedAppTheme): THREE.CanvasTexture | null { + if (typeof document === "undefined") return null; + const canvas = document.createElement("canvas"); + canvas.width = 4; + canvas.height = 256; + const ctx = canvas.getContext("2d"); + if (!ctx) return null; + + const skyGrad = ctx.createLinearGradient(0, 0, 0, 128); + if (theme === "dark") { + skyGrad.addColorStop(0, "#0f1e36"); + skyGrad.addColorStop(1, "#1e3a5f"); + } else { + skyGrad.addColorStop(0, "#b8dcf7"); + skyGrad.addColorStop(1, "#e8f3fc"); + } + ctx.fillStyle = skyGrad; + ctx.fillRect(0, 0, 4, 128); + + const groundGrad = ctx.createLinearGradient(0, 128, 0, 256); + if (theme === "dark") { + groundGrad.addColorStop(0, "#232a33"); + groundGrad.addColorStop(1, "#14181e"); + } else { + groundGrad.addColorStop(0, "#d7ceb9"); + groundGrad.addColorStop(1, "#b8ab92"); + } + ctx.fillStyle = groundGrad; + ctx.fillRect(0, 128, 4, 128); + + const texture = new THREE.CanvasTexture(canvas); + texture.colorSpace = THREE.SRGBColorSpace; + texture.userData.theme = theme; + texture.needsUpdate = true; + return texture; +} + +function applySceneBackdrop( + state: ThreeState, + renderStyle: ViewportRenderStyle, + skyGroundEnabled: boolean, + workspace: WorkspaceSettings, +) { + if (renderStyle.visualStyle === "blueprint") { + state.scene.background = new THREE.Color("#0a2540"); + } else if (renderStyle.visualStyle === "cyberpunk") { + state.scene.background = new THREE.Color("#050914"); + } else if (renderStyle.visualStyle === "hidden-line") { + state.scene.background = new THREE.Color("#ffffff"); + } else if (renderStyle.visualStyle === "clay") { + if (skyGroundEnabled) { + if (!state.skyBackdropTexture || state.skyBackdropTexture.userData.theme !== renderStyle.theme) { + state.skyBackdropTexture?.dispose(); + state.skyBackdropTexture = createSkyGroundBackdropTexture(renderStyle.theme); + } + state.scene.background = state.skyBackdropTexture ?? new THREE.Color("#e5e1d8"); + } else { + state.scene.background = new THREE.Color("#e5e1d8"); + } + } else if (skyGroundEnabled) { + if (!state.skyBackdropTexture || state.skyBackdropTexture.userData.theme !== renderStyle.theme) { + state.skyBackdropTexture?.dispose(); + state.skyBackdropTexture = createSkyGroundBackdropTexture(renderStyle.theme); + } + if (state.skyBackdropTexture) { + state.scene.background = state.skyBackdropTexture; + } else { + const palette = workplaneThemePalette(renderStyle.theme, workspace.background, workspace.gridColor); + state.scene.background = new THREE.Color(palette.sceneBackground); + } + } else { + const palette = workplaneThemePalette(renderStyle.theme, workspace.background, workspace.gridColor); + state.scene.background = new THREE.Color(palette.sceneBackground); + } + state.needsRender = true; +} + function syncWorkplaneHoverPreview( state: ThreeState | null, workplane: PlacementWorkplane | null, @@ -7417,7 +7837,14 @@ function removeShapeDecorations(object: THREE.Group) { }); } -function syncShapeObjectAppearance(object: THREE.Group, shape: WorkplaneShape, selected: boolean, updateSurfaceMaterial: boolean, onTextureReady?: () => void) { +function syncShapeObjectAppearance( + object: THREE.Group, + shape: WorkplaneShape, + selected: boolean, + updateSurfaceMaterial: boolean, + onTextureReady?: () => void, + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, +) { object.userData.showEdges = selected; const groupedContent = object.children.find((child): child is THREE.Group => child instanceof THREE.Group && Boolean(child.userData.groupedShapeContent)); if (groupedContent && shape.groupedShapes?.length && !shape.importedMesh) { @@ -7427,7 +7854,7 @@ function syncShapeObjectAppearance(object: THREE.Group, shape: WorkplaneShape, s const childObject = groupedContent.children.find((entry): entry is THREE.Group => entry instanceof THREE.Group && entry.userData.groupChildId === child.id); if (!childObject) return; const childShape = shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child; - syncShapeObjectAppearance(childObject, childShape, selected, updateSurfaceMaterial, onTextureReady); + syncShapeObjectAppearance(childObject, childShape, selected, updateSurfaceMaterial, onTextureReady, renderStyle); }); object.traverse((child) => { child.userData.shapeId = shape.id; @@ -7440,10 +7867,11 @@ function syncShapeObjectAppearance(object: THREE.Group, shape: WorkplaneShape, s const surface = object.children.find((child): child is THREE.Mesh => child instanceof THREE.Mesh && Boolean(child.userData.shapeSurface)); if (!surface) return; if (updateSurfaceMaterial) { - const material = sharedShapeMaterial(shape); - const nextMaterial = shape.kind === "box" && shape.imagePlate && !shape.hole - ? createImagePlateMaterials(shape, material, onTextureReady) - : material; + const material = sharedShapeMaterial(shape, renderStyle); + const nextMaterial = + shape.kind === "box" && shape.imagePlate && !shape.hole && renderStyle.visualStyle === "shaded" + ? createImagePlateMaterials(shape, material, onTextureReady) + : material; const currentMaterials = Array.isArray(surface.material) ? surface.material : null; const sameMaterial = Array.isArray(nextMaterial) ? Boolean(currentMaterials && nextMaterial.every((entry, index) => currentMaterials[index] === entry)) @@ -7453,7 +7881,7 @@ function syncShapeObjectAppearance(object: THREE.Group, shape: WorkplaneShape, s } } removeShapeDecorations(object); - addShapeEdgeDecorations(object, surface, surface.geometry, shape); + addShapeEdgeDecorations(object, surface, surface.geometry, shape, renderStyle); object.traverse((child) => { child.userData.shapeId = shape.id; }); @@ -7468,6 +7896,7 @@ function rebuildShapes( showCutPreviews = true, useOfficialModifierRendering = false, workplane: PlacementWorkplane = horizontalPlacementWorkplane(), + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, ) { if (!state) { return; @@ -7482,9 +7911,15 @@ function rebuildShapes( state.shapeRecords.clear(); state.officialShapeLayerActive = true; visibleShapes.forEach((shape) => { - const object = createShapeObject(shape, selected.has(shape.id), () => { - state.needsRender = true; - }, false); + const object = createShapeObject( + shape, + selected.has(shape.id), + () => { + state.needsRender = true; + }, + false, + renderStyle, + ); state.shapeLayer.add(object); }); if (showCutPreviews) { @@ -7512,7 +7947,7 @@ function rebuildShapes( visibleShapes.forEach((shape) => { const selectedShape = selected.has(shape.id); const transformSignature = shapeTransformSignature(shape); - const materialSignature = shapeMaterialSignature(shape); + const materialSignature = shapeMaterialSignature(shape, renderStyle); const geometrySignature = shapeGeometrySignature(shape); let record = state.shapeRecords.get(shape.id); if (record && record.geometrySignature !== geometrySignature) { @@ -7523,9 +7958,15 @@ function rebuildShapes( } if (!record) { - const object = createShapeObject(shape, selectedShape, () => { - state.needsRender = true; - }); + const object = createShapeObject( + shape, + selectedShape, + () => { + state.needsRender = true; + }, + true, + renderStyle, + ); state.shapeLayer.add(object); record = { object, @@ -7546,9 +7987,16 @@ function rebuildShapes( syncShapeObjectDimensions(record.object, shape); const materialChanged = record.materialSignature !== materialSignature; if (materialChanged || record.selected !== selectedShape) { - syncShapeObjectAppearance(record.object, shape, selectedShape, materialChanged, () => { - state.needsRender = true; - }); + syncShapeObjectAppearance( + record.object, + shape, + selectedShape, + materialChanged, + () => { + state.needsRender = true; + }, + renderStyle, + ); } record.shape = shape; record.transformSignature = transformSignature; @@ -8579,18 +9027,73 @@ function releaseSharedShapeGeometry(mesh: THREE.Mesh | THREE.LineSegments) { trimSharedShapeGeometryCache(); } -function sharedShapeMaterial(shape: WorkplaneShape) { - const textureId = shape.texture || "none"; +function sharedShapeMaterial(shape: WorkplaneShape, renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE) { + const styleMode = renderStyle.visualStyle; + const textureId = styleMode === "shaded" ? (shape.texture || "none") : "none"; const texDef = getTextureDefinition(textureId); - const isGlass = textureId === "glass"; + const isGlass = styleMode === "shaded" && textureId === "glass"; + const isWireframe = styleMode === "wireframe"; + + let color = shape.hole ? "#b7c0c9" : shape.color; + let roughness = shape.hole ? 0.88 : texDef.roughness; + let metalness = shape.hole ? 0.02 : texDef.metalness; + let emissive = "#000000"; + let emissiveIntensity = 0; + + if (styleMode === "hidden-line") { + color = shape.hole ? "#e2e8f0" : "#ffffff"; + roughness = 0.96; + metalness = 0; + } else if (styleMode === "monochrome") { + color = shape.hole ? "#94a3b8" : "#e2e8f0"; + roughness = 0.78; + metalness = 0.04; + } else if (styleMode === "blueprint") { + color = shape.hole ? "#1e3a5f" : "#154c79"; + roughness = 0.7; + metalness = 0.05; + } else if (styleMode === "cyberpunk") { + color = shape.hole ? "#13293d" : "#0d1b2a"; + roughness = 0.35; + metalness = 0.45; + emissive = shape.hole ? "#064e3b" : "#083344"; + emissiveIntensity = 0.32; + } else if (styleMode === "clay") { + color = shape.hole ? "#b8ad9f" : "#d8cab8"; + roughness = 0.92; + metalness = 0.02; + } + + const transparent = isWireframe || renderStyle.xRay || Boolean(shape.hole || isGlass); + const opacity = isWireframe + ? 0 + : renderStyle.xRay + ? shape.hole + ? 0.25 + : 0.38 + : shape.hole + ? shape.importedMesh + ? 0.34 + : 0.52 + : isGlass + ? 0.45 + : 1; + const depthWrite = !isWireframe && !renderStyle.xRay; + const colorWrite = !isWireframe; const key = JSON.stringify({ - color: shape.hole ? "#b7c0c9" : shape.color, + color, texture: textureId, - transparent: Boolean(shape.hole || isGlass), - opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : (isGlass ? 0.45 : 1), - roughness: shape.hole ? 0.88 : texDef.roughness, - metalness: shape.hole ? 0.02 : texDef.metalness, + visualStyle: styleMode, + xRay: renderStyle.xRay, + transparent, + opacity, + depthWrite, + colorWrite, + roughness, + metalness, + emissive, + emissiveIntensity, side: "double", }); const cached = sharedShapeMaterialCache.get(key); @@ -8601,11 +9104,15 @@ function sharedShapeMaterial(shape: WorkplaneShape) { } const textureMap = !shape.hole && textureId !== "none" ? getArchitecturalTexture(textureId, shape.color) : null; const material = new THREE.MeshStandardMaterial({ - color: shape.hole ? "#b7c0c9" : shape.color, - transparent: Boolean(shape.hole || isGlass), - opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : (isGlass ? 0.45 : 1), - roughness: shape.hole ? 0.88 : texDef.roughness, - metalness: shape.hole ? 0.02 : texDef.metalness, + color, + transparent, + opacity, + depthWrite, + colorWrite, + roughness, + metalness, + emissive, + emissiveIntensity, map: textureMap, side: THREE.DoubleSide, }); @@ -8668,11 +9175,11 @@ function releaseSharedShapeMaterials(mesh: THREE.Mesh | THREE.LineSegments) { }); } -function sharedLineMaterial(color: string, opacity: number, depthWrite = true) { - const key = `${color}|${opacity}|${depthWrite}`; +function sharedLineMaterial(color: string, opacity: number, depthWrite = true, depthTest = true) { + const key = `${color}|${opacity}|${depthWrite}|${depthTest}`; const cached = sharedLineMaterialCache.get(key); if (cached) return cached; - const material = new THREE.LineBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite }); + const material = new THREE.LineBasicMaterial({ color, transparent: opacity < 1, opacity, depthWrite, depthTest }); material.userData.cached = true; sharedLineMaterialCache.set(key, material); return material; @@ -8711,6 +9218,7 @@ function createShapeObject( showEdges = false, onTextureReady?: () => void, acceleratedPicking = true, + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, ) { const group = new THREE.Group(); group.name = shape.name; @@ -8734,7 +9242,7 @@ function createShapeObject( .filter((child) => !child.hidden) .forEach((child) => { const childShape = shape.hole ? { ...child, hole: true, color: "#b8c2cc" } : child; - const childObject = createShapeObject(childShape, showEdges, onTextureReady, acceleratedPicking); + const childObject = createShapeObject(childShape, showEdges, onTextureReady, acceleratedPicking, renderStyle); childObject.userData.groupChildId = child.id; content.add(childObject); }); @@ -8756,7 +9264,7 @@ function createShapeObject( return group; } - const material = sharedShapeMaterial(shape); + const material = sharedShapeMaterial(shape, renderStyle); const width = shapeWidth(shape); const depth = shapeDepth(shape); @@ -8774,19 +9282,22 @@ function createShapeObject( ? new RoundedBoxGeometry(width, height, depth, Math.max(1, shape.steps ?? 10), shape.radius) : new THREE.BoxGeometry(1, 1, 1), ), - shape.imagePlate && !shape.hole ? createImagePlateMaterials(shape, material, onTextureReady) : material, + shape.imagePlate && !shape.hole && renderStyle.visualStyle === "shaded" + ? createImagePlateMaterials(shape, material, onTextureReady) + : material, shape, undefined, undefined, shape.radius && shape.radius > 0 ? undefined : new THREE.Vector3(width, height, depth), + renderStyle, ); break; case "cylinder": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, shape.sides ?? 96, shape.segments ?? 1)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, shape.sides ?? 96, shape.segments ?? 1)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2), renderStyle); break; case "sphere": { const { widthSegments, heightSegments } = sphereTessellation(shape.steps); - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.SphereGeometry(1, widthSegments, heightSegments)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.SphereGeometry(1, widthSegments, heightSegments)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height / 2, depth / 2), renderStyle); break; } case "cone": @@ -8798,28 +9309,29 @@ function createShapeObject( undefined, undefined, new THREE.Vector3(1, 1, depth / Math.max(0.001, width)), + renderStyle, ); break; case "pyramid": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createPyramidGeometry(width, height, depth, shape.sides ?? 4)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createPyramidGeometry(width, height, depth, shape.sides ?? 4)), material, shape, undefined, undefined, undefined, renderStyle); break; case "roof": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoofGeometry(width, height, depth)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoofGeometry(width, height, depth)), material, shape, undefined, undefined, undefined, renderStyle); break; case "roundRoof": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoundRoofGeometry(width, height, depth, shape.sides ?? 64)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createRoundRoofGeometry(width, height, depth, shape.sides ?? 64)), material, shape, undefined, undefined, undefined, renderStyle); break; case "halfSphere": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHalfSphereGeometry(width, height, depth, shape.steps ?? 32)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHalfSphereGeometry(width, height, depth, shape.steps ?? 32)), material, shape, undefined, undefined, undefined, renderStyle); break; case "torus": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createTorusGeometry(width, height, depth)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createTorusGeometry(width, height, depth)), material, shape, undefined, undefined, undefined, renderStyle); break; case "ring": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape, undefined, undefined, undefined, renderStyle); break; case "tube": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createHollowCylinderGeometry(width, height, depth, shape.bevel ?? 4, 144)), material, shape, undefined, undefined, undefined, renderStyle); break; case "gear": addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createGearGeometry({ @@ -8833,19 +9345,19 @@ function createShapeObject( gearType: shape.gearType, helixAngle: shape.helixAngle, helixQuality: shape.helixQuality, - })), material, shape); + })), material, shape, undefined, undefined, undefined, renderStyle); break; case "wedge": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createWedgeGeometry(width, height, depth)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => createWedgeGeometry(width, height, depth)), material, shape, undefined, undefined, undefined, renderStyle); break; case "polygon": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, 6)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2)); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.CylinderGeometry(1, 1, 1, 6)), material, shape, undefined, undefined, new THREE.Vector3(width / 2, height, depth / 2), renderStyle); break; case "icosahedron": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.IcosahedronGeometry(size / 2, 1)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.IcosahedronGeometry(size / 2, 1)), material, shape, undefined, undefined, undefined, renderStyle); break; case "text": - addTextShape(group, material, shape, geometryCacheKey); + addTextShape(group, material, shape, geometryCacheKey, renderStyle); break; case "mesh": if (shape.importedMesh) { @@ -8862,17 +9374,18 @@ function createShapeObject( height / Math.max(0.001, shape.importedMesh.baseHeight), depth / Math.max(0.001, shape.importedMesh.baseDepth), ), + renderStyle, ); } else { - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape, undefined, undefined, undefined, renderStyle); } break; case "scribble": - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.TorusKnotGeometry(size * 0.22, size * 0.055, 120, 12)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.TorusKnotGeometry(size * 0.22, size * 0.055, 120, 12)), material, shape, undefined, undefined, undefined, renderStyle); break; case "sketch": default: - addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape); + addMesh(group, sharedShapeGeometry(geometryCacheKey, () => new THREE.BoxGeometry(size, Math.max(3, height * 0.35), size * 0.72)), material, shape, undefined, undefined, undefined, renderStyle); break; } @@ -9005,6 +9518,7 @@ function addMesh( position?: THREE.Vector3, rotation?: THREE.Euler, scale?: THREE.Vector3, + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, ) { const based = geometry.userData.cached ? geometry : putGeometryOnBase(geometry); const prepared = taperGeometryForShape(based, shape); @@ -9015,7 +9529,7 @@ function addMesh( if (group.userData.acceleratedPicking !== false && !shape.edgeTreatments?.length) { enableAcceleratedMeshPicking(mesh, prepared, Boolean(shape.importedMesh)); } - mesh.castShadow = true; + mesh.castShadow = renderStyle.visualStyle !== "wireframe"; mesh.receiveShadow = false; if (position) { mesh.position.copy(position); @@ -9028,26 +9542,77 @@ function addMesh( mesh.scale.copy(scale); } group.add(mesh); - addShapeEdgeDecorations(group, mesh, prepared, shape); + addShapeEdgeDecorations(group, mesh, prepared, shape, renderStyle); } -function addShapeEdgeDecorations(group: THREE.Group, mesh: THREE.Mesh, prepared: THREE.BufferGeometry, shape: WorkplaneShape) { +function addShapeEdgeDecorations( + group: THREE.Group, + mesh: THREE.Mesh, + prepared: THREE.BufferGeometry, + shape: WorkplaneShape, + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, +) { const complexEdges = shape.kind === "mesh" || Boolean(shape.importedMesh) || ["cone", "pyramid", "roof", "roundRoof", "halfSphere", "torus", "tube", "ring", "gear", "wedge"].includes(shape.kind); const importedTriangleCount = shape.importedMesh?.triangleCount ?? 0; const skipHeavyImportedEdges = Boolean(shape.importedMesh) && importedTriangleCount > IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT; - if ((group.userData.showEdges || complexEdges) && !skipHeavyImportedEdges) { + const forceStyleEdges = + renderStyle.visualStyle !== "shaded" || renderStyle.backEdges || renderStyle.xRay; + if ((group.userData.showEdges || complexEdges || forceStyleEdges) && !skipHeavyImportedEdges) { const selectedOutline = Boolean(group.userData.showEdges); const selectedRoundedBox = selectedOutline && shape.kind === "box" && Boolean(shape.radius && shape.radius > 0); - const edgeColor = selectedOutline ? "#00aeea" : shape.hole ? "#697989" : complexEdges ? "#141b21" : darkenHex(shape.color, 0.34); - const edgeOpacity = selectedRoundedBox ? 0 : selectedOutline ? 0.98 : shape.hole ? 0.44 : complexEdges ? 0.38 : shape.kind === "text" ? 0.86 : 0.2; + let edgeColor = selectedOutline + ? "#00aeea" + : shape.hole + ? "#697989" + : complexEdges + ? "#141b21" + : darkenHex(shape.color, 0.34); + let edgeOpacity = selectedRoundedBox + ? 0 + : selectedOutline + ? 0.98 + : shape.hole + ? 0.44 + : complexEdges + ? 0.38 + : shape.kind === "text" + ? 0.86 + : renderStyle.xRay + ? 0.45 + : 0.28; + + if (!selectedOutline) { + if (renderStyle.visualStyle === "blueprint") { + edgeColor = "#7dd3fc"; + edgeOpacity = 0.86; + } else if (renderStyle.visualStyle === "cyberpunk") { + edgeColor = "#34d399"; + edgeOpacity = 0.9; + } else if (renderStyle.visualStyle === "hidden-line") { + edgeColor = "#0f172a"; + edgeOpacity = 0.94; + } else if (renderStyle.visualStyle === "monochrome") { + edgeColor = "#1e293b"; + edgeOpacity = 0.74; + } else if (renderStyle.visualStyle === "wireframe") { + edgeColor = renderStyle.theme === "dark" ? "#e2e8f0" : "#0f172a"; + edgeOpacity = 0.94; + } else if (renderStyle.visualStyle === "clay") { + edgeColor = "#4a3f35"; + edgeOpacity = 0.46; + } + } + if (selectedOutline && shape.importedMesh && shape.cadDisplayEdgesVersion === 2 && Boolean(shape.cadDisplayEdges?.length)) { addCadDisplayEdges(group, shape, edgeColor, edgeOpacity); } else { const selectedThreshold = shape.importedMesh ? NORMAL_IMPORTED_SELECTION_EDGE_ANGLE : 1; - const edges = new THREE.LineSegments(getEdgesGeometry(shape, prepared, selectedOutline ? selectedThreshold : complexEdges ? 14 : 25), sharedLineMaterial(edgeColor, edgeOpacity)); + const threshold = selectedOutline ? selectedThreshold : complexEdges ? 14 : 25; + const edgesGeometry = getEdgesGeometry(shape, prepared, threshold); + const edges = new THREE.LineSegments(edgesGeometry, sharedLineMaterial(edgeColor, edgeOpacity)); edges.userData.complexEdge = complexEdges; edges.userData.shapeDecoration = true; edges.userData.shapeEdge = true; @@ -9055,6 +9620,29 @@ function addShapeEdgeDecorations(group: THREE.Group, mesh: THREE.Mesh, prepared: edges.rotation.copy(mesh.rotation); edges.scale.copy(mesh.scale); group.add(edges); + + if (renderStyle.backEdges) { + const backColor = + renderStyle.visualStyle === "blueprint" + ? "#38bdf8" + : renderStyle.visualStyle === "cyberpunk" + ? "#10b981" + : renderStyle.theme === "dark" + ? "#94a3b8" + : "#334155"; + const backEdges = new THREE.LineSegments( + edgesGeometry, + sharedLineMaterial(backColor, 0.24, false, false), + ); + backEdges.renderOrder = 900; + backEdges.userData.complexEdge = true; + backEdges.userData.shapeDecoration = true; + backEdges.userData.shapeEdge = true; + backEdges.position.copy(mesh.position); + backEdges.rotation.copy(mesh.rotation); + backEdges.scale.copy(mesh.scale); + group.add(backEdges); + } } } } @@ -9142,7 +9730,13 @@ function setComplexEdgeVisibility(object: THREE.Object3D, visible: boolean) { }); } -function addTextShape(group: THREE.Group, material: THREE.MeshStandardMaterial, shape: WorkplaneShape, geometryCacheKey: string) { +function addTextShape( + group: THREE.Group, + material: THREE.MeshStandardMaterial, + shape: WorkplaneShape, + geometryCacheKey: string, + renderStyle: ViewportRenderStyle = DEFAULT_RENDER_STYLE, +) { const geometry = sharedShapeGeometry(geometryCacheKey, () => { const text = (shape.text ?? "TEXT").trim() || " "; const bevel = clamp(shape.bevel ?? 0, 0, 8); @@ -9179,7 +9773,7 @@ function addTextShape(group: THREE.Group, material: THREE.MeshStandardMaterial, } return next; }); - addMesh(group, geometry, material, shape); + addMesh(group, geometry, material, shape, undefined, undefined, undefined, renderStyle); } function putGeometryOnBase(geometry: THREE.BufferGeometry) { diff --git a/apps/web/src/components/snapcad/AccessibilityCenter.tsx b/apps/web/src/components/snapcad/AccessibilityCenter.tsx index fd364fb..248d799 100644 --- a/apps/web/src/components/snapcad/AccessibilityCenter.tsx +++ b/apps/web/src/components/snapcad/AccessibilityCenter.tsx @@ -351,8 +351,16 @@ export function GlobalAccessibilityToolbar({ setDrawerOpen(false); } }; + const onOpenA11yDrawer = () => { + setDrawerOpen(true); + setPaletteOpen(false); + }; window.addEventListener("keydown", onKeyDown); - return () => window.removeEventListener("keydown", onKeyDown); + window.addEventListener("snapcad:open-a11y-drawer", onOpenA11yDrawer); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("snapcad:open-a11y-drawer", onOpenA11yDrawer); + }; }, []); const update = (patch: Partial, msg?: string) => { diff --git a/apps/web/src/components/snapcad/EnterprisePrecisionBar.tsx b/apps/web/src/components/snapcad/EnterprisePrecisionBar.tsx index 7a231e3..09978c1 100644 --- a/apps/web/src/components/snapcad/EnterprisePrecisionBar.tsx +++ b/apps/web/src/components/snapcad/EnterprisePrecisionBar.tsx @@ -1,7 +1,8 @@ "use client"; -import { Box, Compass, Crosshair, Eye, Grid3X3, Layers, Maximize2, MoveRight, Ruler } from "lucide-react"; -import { useCallback, useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent } from "react"; +import { Box, Compass, Crosshair, Eye, Grid3X3, MoveRight, Ruler } from "lucide-react"; +import { useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent } from "react"; +import { SKETCHUP_TOOLS, type SketchUpToolId } from "@/lib/sketchupInterface"; import type { GridSize } from "@/types/sketchforge"; export type DirectModelingToolMode = "select" | "push-pull" | "face-sketch" | "measure"; @@ -24,6 +25,9 @@ export interface PrecisionBarData { interface EnterprisePrecisionBarProps { data: PrecisionBarData; activeTool: DirectModelingToolMode; + activeSketchUpTool?: SketchUpToolId; + activeHintText?: string; + vcbDisplayText?: string; onToolChange?: (tool: DirectModelingToolMode) => void; snapGrid: GridSize; onSnapGridChange?: (size: GridSize) => void; @@ -32,6 +36,7 @@ interface EnterprisePrecisionBarProps { onResetView?: () => void; onSetCameraView?: (face: "top" | "front" | "right" | "isometric") => void; onCommitValue?: (value: number) => void; + onCommitVcbRaw?: (raw: string) => void; unitLabel?: string; className?: string; axisLock?: "x" | "z" | null; @@ -42,31 +47,38 @@ const SNAP_OPTIONS: GridSize[] = ["0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 export function EnterprisePrecisionBar({ data, activeTool, + activeSketchUpTool = "select", + activeHintText, + vcbDisplayText, onToolChange, snapGrid, onSnapGridChange, isOrthographic = false, onToggleProjection, - onResetView, onSetCameraView, onCommitValue, + onCommitVcbRaw, unitLabel = "mm", className = "", axisLock = null, }: EnterprisePrecisionBarProps) { const [inputValue, setInputValue] = useState(""); const inputRef = useRef(null); + const toolMeta = SKETCHUP_TOOLS[activeSketchUpTool] ?? SKETCHUP_TOOLS.select; + const resolvedLabel = data.valueLabel || toolMeta.vcbLabel || "Ölçü"; + const resolvedHint = activeHintText || toolMeta.hint; - // Sync input value with live distance during dragging if user hasn't focused it + // Sync input value with live distance/dimensions during dragging if user hasn't focused it useEffect(() => { - if (data.currentValue !== undefined && data.currentValue !== null) { - if (document.activeElement !== inputRef.current) { - setInputValue(data.currentValue.toFixed(2)); - } - } else if (!data.isDragging && document.activeElement !== inputRef.current) { + if (document.activeElement === inputRef.current) return; + if (vcbDisplayText) { + setInputValue(vcbDisplayText); + } else if (data.currentValue !== undefined && data.currentValue !== null) { + setInputValue(data.currentValue.toFixed(2)); + } else if (!data.isDragging) { setInputValue(""); } - }, [data.currentValue, data.isDragging]); + }, [data.currentValue, data.isDragging, vcbDisplayText]); const handleInputChange = (e: ChangeEvent) => { setInputValue(e.target.value); @@ -75,14 +87,27 @@ export function EnterprisePrecisionBar({ const handleInputKeyDown = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); - const num = parseFloat(inputValue.replace(",", ".")); + const trimmed = inputValue.trim(); + if (!trimmed) return; + if (onCommitVcbRaw) { + onCommitVcbRaw(trimmed); + inputRef.current?.blur(); + return; + } + const num = parseFloat(trimmed.replace(",", ".")); if (!Number.isNaN(num)) { onCommitValue?.(num); inputRef.current?.blur(); } } else if (e.key === "Escape") { inputRef.current?.blur(); - setInputValue(data.currentValue !== undefined && data.currentValue !== null ? data.currentValue.toFixed(2) : ""); + setInputValue( + vcbDisplayText + ? vcbDisplayText + : data.currentValue !== undefined && data.currentValue !== null + ? data.currentValue.toFixed(2) + : "", + ); } }; @@ -90,9 +115,9 @@ export function EnterprisePrecisionBar({