diff --git a/package-lock.json b/package-lock.json index a935bfb..e39971b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,6 +21,7 @@ "dxf-parser": "^1.1.2", "jspdf": "^4.2.1", "jszip": "^3.10.1", + "lcms-wasm": "^1.0.5", "pdfjs-dist": "^6.2.108", "polygon-clipping": "^0.15.7", "react": "^18.3.1", @@ -866,6 +867,48 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@ljharb/now": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@ljharb/now/-/now-1.0.1.tgz", + "integrity": "sha512-yRQ3B8l2v4vTLQ2l+4kBu6EsXaX7czuLB7fvUz0vkHHziHje75R2t/0Mm/vIo31tlZVCEvCoXHkNKW+ugv3uSA==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/@ljharb/resumer": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@ljharb/resumer/-/resumer-0.1.3.tgz", + "integrity": "sha512-d+tsDgfkj9X5QTriqM4lKesCkMMJC3IrbPKHvayP00ELx2axdXvDfWkqjxrLXIzGcQzmj7VAUT1wopqARTvafw==", + "license": "MIT", + "dependencies": { + "@ljharb/through": "^2.3.13", + "call-bind": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/@ljharb/through": { + "version": "2.3.14", + "resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.14.tgz", + "integrity": "sha512-ajBvlKpWucBB17FuQYUShqpqy8GRgYEpJW0vWJbUu1CV9lWyrDCapy0lScU8T8Z6qn49sSwJB3+M+evYIdGg+A==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/@mlightcad/libredwg-web": { "version": "0.7.7", "resolved": "https://registry.npmjs.org/@mlightcad/libredwg-web/-/libredwg-web-0.7.7.tgz", @@ -2483,6 +2526,80 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.every": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/array.prototype.every/-/array.prototype.every-1.1.7.tgz", + "integrity": "sha512-BIP72rKvrKd08ptbetLb4qvrlGjkv30yOKgKcTtOIbHyQt3shr/jyOzdApiCOh3LPYrpJo5M6i0zmVldOF2pUw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "is-string": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -2493,6 +2610,36 @@ "node": ">=12" } }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, "node_modules/base64-arraybuffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", @@ -2516,6 +2663,16 @@ "node": ">=6.0.0" } }, + "node_modules/brace-expansion": { + "version": "1.1.18", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", + "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/browserslist": { "version": "4.28.4", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.4.tgz", @@ -2550,6 +2707,53 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001799", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001799.tgz", @@ -2643,6 +2847,12 @@ "node": ">=20" } }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2697,6 +2907,57 @@ "dev": true, "license": "MIT" }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2715,6 +2976,87 @@ } } }, + "node_modules/deep-equal": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz", + "integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "call-bind": "^1.0.5", + "es-get-iterator": "^1.1.3", + "get-intrinsic": "^1.2.2", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.2", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.1", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/deep-equal/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/defined": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.1.tgz", + "integrity": "sha512-hsBd2qSVCRE+5PmNdHt1uzyrFu5d3RwmFDKzyNZMFq/EwDNJF7Ee5+D5oEKF0hU6LhtoUF1macFvOe4AskQC1Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/delaunator": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", @@ -2751,6 +3093,32 @@ "@types/trusted-types": "^2.0.7" } }, + "node_modules/dotignore": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/dotignore/-/dotignore-0.1.2.tgz", + "integrity": "sha512-UGGGWfSauusaVJC+8fgV+NVvBXkCTmVv7sk6nojDZZvuOUNGUy0Zk4UpHQD6EDjS0jpBwcACvH4eofvyzBcRDw==", + "license": "MIT", + "dependencies": { + "minimatch": "^3.0.4" + }, + "bin": { + "ignored": "bin/ignored" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/dxf-parser": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/dxf-parser/-/dxf-parser-1.1.2.tgz", @@ -2806,6 +3174,136 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/es-abstract": { + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-abstract-get": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-abstract-get/-/es-abstract-get-1.0.0.tgz", + "integrity": "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.2", + "is-callable": "^1.2.7", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-get-iterator/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/es-module-lexer": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.2.0.tgz", @@ -2813,6 +3311,65 @@ "dev": true, "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.4.tgz", + "integrity": "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==", + "license": "MIT", + "dependencies": { + "es-abstract-get": "^1.0.0", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "is-callable": "^1.2.7", + "is-date-object": "^1.1.0", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/esbuild": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", @@ -2923,6 +3480,27 @@ "integrity": "sha512-l/YiRdBSH/eWv6OF3sLGkwErL+n0MqCICi9mppTZBOCL5vixWGDqCYvRcuxB2h7RGCTzaTKOHT2caHvCXQPRlw==", "license": "MIT" }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2938,6 +3516,56 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.2.0.tgz", + "integrity": "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2", + "hasown": "^2.0.4", + "is-callable": "^1.2.7", + "is-document.all": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -2971,6 +3599,118 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -2978,6 +3718,101 @@ "dev": true, "license": "ISC" }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-dynamic-import": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/has-dynamic-import/-/has-dynamic-import-2.1.1.tgz", + "integrity": "sha512-DuTCn6K/RW8S27npDMumGKsjG6HE7MxzedZka5tJP+9dqfxks+UMqKBmeCijHtIhsBEZPlbMg0qMHi2nKYVtKQ==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/html2canvas": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz", @@ -2998,18 +3833,411 @@ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", "license": "MIT" }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/iobuffer": { "version": "5.4.0", "resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz", "integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==", "license": "MIT" }, + "node_modules/is-arguments": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz", + "integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-document.all": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz", + "integrity": "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -3083,6 +4311,15 @@ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", "license": "(MIT AND Zlib)" }, + "node_modules/lcms-wasm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/lcms-wasm/-/lcms-wasm-1.0.5.tgz", + "integrity": "sha512-bQpBF4BvoHY//Gq7k67VD9l+BEk6dmaROAB+ci83ZajOurOUPAcwfi3z5VzzAf27qccIE867kYc+jk6/wPelcA==", + "license": "MIT", + "dependencies": { + "tape": "^5.9.0" + } + }, "node_modules/lie": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", @@ -3423,6 +4660,15 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/meshoptimizer": { "version": "0.18.1", "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.18.1.tgz", @@ -3430,6 +4676,27 @@ "dev": true, "license": "MIT" }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -3460,6 +4727,34 @@ "dev": true, "license": "MIT" }, + "node_modules/mock-property": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/mock-property/-/mock-property-1.1.2.tgz", + "integrity": "sha512-Rw0vY0wBdNtm3sbANVMDUgO5Htew9xotKoqcdK/a4rW8jf5KEl6MAWGMBhjKng6gpPjX8SmO8f+65ssnxNroTw==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "hasown": "^2.0.4", + "isarray": "^2.0.5", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mock-property/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/modern-tar": { "version": "0.7.6", "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.7.6.tgz", @@ -3496,6 +4791,24 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/node-exports-info": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.2.tgz", + "integrity": "sha512-kXs9Go0cah0qHVV2v389IXQLdLCeE1xfFtjOAF+iobu0OIoG1pje8At2vMHyaPMiPMnG/LWP50twML21eMcAag==", + "license": "MIT", + "dependencies": { + "array.prototype.flatmap": "^1.3.3", + "es-errors": "^1.3.0", + "object.entries": "^1.1.9", + "semver": "^6.3.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/node-releases": { "version": "2.0.50", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.50.tgz", @@ -3506,6 +4819,78 @@ "node": ">=18" } }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz", + "integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", + "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/obug": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz", @@ -3520,6 +4905,33 @@ "node": ">=12.20.0" } }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/own-keys": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz", + "integrity": "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/pako": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", @@ -3536,6 +4948,21 @@ ], "license": "(MIT AND Zlib)" }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -3639,6 +5066,15 @@ "splaytree": "^3.1.0" } }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/postcss": { "version": "8.5.16", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz", @@ -3784,6 +5220,28 @@ "util-deprecate": "~1.0.1" } }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/regenerator-runtime": { "version": "0.13.11", "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", @@ -3791,6 +5249,49 @@ "license": "MIT", "optional": true }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve": { + "version": "2.0.0-next.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.7.tgz", + "integrity": "sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.2", + "node-exports-info": "^1.6.0", + "object-keys": "^1.1.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/rgbcolor": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz", @@ -3893,12 +5394,76 @@ "fsevents": "~2.3.2" } }, + "node_modules/safe-array-concat": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", + "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-array-concat/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "license": "MIT" }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-push-apply/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/scheduler": { "version": "0.23.2", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", @@ -3912,18 +5477,135 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" } }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/setimmediate": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", "license": "MIT" }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -3983,6 +5665,19 @@ "dev": true, "license": "MIT" }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -4010,6 +5705,63 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/string.prototype.trim": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.11.tgz", + "integrity": "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-object-atoms": "^1.1.2", + "has-property-descriptors": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.10.tgz", + "integrity": "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/strip-ansi": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", @@ -4039,6 +5791,18 @@ "node": ">= 8.0" } }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/svg-pathdata": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz", @@ -4073,6 +5837,45 @@ "url": "https://github.com/fontello/svg2ttf?sponsor=1" } }, + "node_modules/tape": { + "version": "5.10.2", + "resolved": "https://registry.npmjs.org/tape/-/tape-5.10.2.tgz", + "integrity": "sha512-MfhVVAWa834kfYL4KgrqHblWfwkjaQvfaQhAX/bBTNQsK8oJ4ztpUe7jiemR2Vegw4pYwpnQMy51MhEmRzbbsg==", + "license": "MIT", + "dependencies": { + "@ljharb/now": "^1.0.1", + "@ljharb/resumer": "^0.1.3", + "@ljharb/through": "^2.3.14", + "array.prototype.every": "^1.1.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "deep-equal": "^2.2.3", + "defined": "^1.0.1", + "dotignore": "^0.1.2", + "es-object-atoms": "^1.1.2", + "for-each": "^0.3.5", + "get-package-type": "^0.1.0", + "glob": "^7.2.3", + "has-dynamic-import": "^2.1.1", + "hasown": "^2.0.4", + "inherits": "^2.0.4", + "is-regex": "^1.2.1", + "minimist": "^1.2.8", + "mock-property": "^1.1.0", + "object-inspect": "^1.13.4", + "object-is": "^1.1.6", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "resolve": "^2.0.0-next.7", + "string.prototype.trim": "^1.2.11" + }, + "bin": { + "tape": "bin/tape" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/tar": { "version": "7.5.19", "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.19.tgz", @@ -4168,6 +5971,80 @@ "license": "0BSD", "optional": true }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.8.tgz", + "integrity": "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "possible-typed-array-names": "^1.1.0", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/typed-query-selector": { "version": "2.12.2", "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz", @@ -4189,6 +6066,24 @@ "node": ">=14.17" } }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/undici": { "version": "7.28.0", "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", @@ -4533,6 +6428,97 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type/node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.22.tgz", + "integrity": "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -4568,6 +6554,12 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/ws": { "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", diff --git a/package.json b/package.json index 9f50d1f..93379ee 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "dxf-parser": "^1.1.2", "jspdf": "^4.2.1", "jszip": "^3.10.1", + "lcms-wasm": "^1.0.5", "pdfjs-dist": "^6.2.108", "polygon-clipping": "^0.15.7", "react": "^18.3.1", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 8684b03..397b74b 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Basis-Permissions + Fenstersteuerung fuer die randlose (decorations:false) Titelleiste: Minimieren/Maximieren/Schliessen + Ziehen der eigenen Titelleiste (data-tauri-drag-region). Menu: fuer die native macOS-Systemmenueleiste (src/native/appMenu.ts). Webview/Event: fuer die nativen Ressourcen-/Einstellungs-/Zeichnungsebenen-/Ebeneneinstellungs-Fenster + ihre Sync-Bruecken (src/native/*Window.ts) - gilt fuer alle Fensterlabels, da jedes Events senden/empfangen muss. Dialog/Fs: nativer Oeffnen- UND Speichern-Dialog fuer Projektdateien (.obp/.json) plus Lesen/Schreiben der gewaehlten Datei (io/projectFile.ts, io/saveFile.ts) - open+read fuer Projekt laden, save+write fuer Projekt/Export speichern. Updater/Process: Selbst-Update-Check beim Start (src/update/checkForUpdate.ts) + Neustart nach Installation. Http: Versionsverlauf (versions.json vom Gitea-Release) ohne Browser-CORS, Scope auf den eigenen Gitea-Host begrenzt. Shell:allow-open: oeffnet den DMG-Download einer aelteren Version im System-Browser (Rollback). allow-set-size/allow-center: kompaktes Splash-/Startbildschirm-Fenster vor dem Editor (App.tsx bootPhase).", + "description": "Basis-Permissions + Fenstersteuerung fuer die randlose (decorations:false) Titelleiste: Minimieren/Maximieren/Schliessen + Ziehen der eigenen Titelleiste (data-tauri-drag-region). Menu: fuer die native macOS-Systemmenueleiste (src/native/appMenu.ts). Webview/Event: fuer die nativen Ressourcen-/Einstellungs-/Zeichnungsebenen-/Ebeneneinstellungs-Fenster + ihre Sync-Bruecken (src/native/*Window.ts) - gilt fuer alle Fensterlabels, da jedes Events senden/empfangen muss. Dialog/Fs: nativer Oeffnen- UND Speichern-Dialog fuer Projektdateien (.obp/.json) plus Lesen/Schreiben der gewaehlten Datei (io/projectFile.ts, io/saveFile.ts) - open+read fuer Projekt laden, save+write fuer Projekt/Export speichern. fs:allow-read-file (eng auf EINEN festen Pfad beschraenkt): liest macOS mitgeliefertes Generic-CMYK-Profil (ColorSync) fuer echtes ICC-Farbmanagement im Farbmischer (model/colorIcc.ts) - bewusst kein gebuendeltes Fremd-Profil, nur diese eine System-Datei zur Laufzeit gelesen. Updater/Process: Selbst-Update-Check beim Start (src/update/checkForUpdate.ts) + Neustart nach Installation. Http: Versionsverlauf (versions.json vom Gitea-Release) ohne Browser-CORS, Scope auf den eigenen Gitea-Host begrenzt. Shell:allow-open: oeffnet den DMG-Download einer aelteren Version im System-Browser (Rollback). allow-set-size/allow-center: kompaktes Splash-/Startbildschirm-Fenster vor dem Editor (App.tsx bootPhase).", "windows": ["main", "resources", "settings", "drawing-levels", "layer-settings", "context-import"], "permissions": [ "core:default", @@ -22,6 +22,10 @@ "dialog:allow-save", "fs:allow-read-text-file", "fs:allow-write-text-file", + { + "identifier": "fs:allow-read-file", + "allow": [{ "path": "/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc" }] + }, "updater:default", "process:allow-restart", { diff --git a/src-tauri/render3d/src/lib.rs b/src-tauri/render3d/src/lib.rs index e3e3967..0ddb1c8 100644 --- a/src-tauri/render3d/src/lib.rs +++ b/src-tauri/render3d/src/lib.rs @@ -933,6 +933,45 @@ mod tests { assert!(saw_up && saw_down, "Vorder- UND Rueckseite (±Y)"); } + #[test] + fn context_mesh_negiert_nord_achse_nur_fuer_terrain_und_imported_nicht_fuer_extrusion() { + // Nutzer-Report 2026-09-27 "gewisse Dinge sind noch gespiegelt im 3D": + // der 2026-09-24-Fix negierte die Nord-Achse PAUSCHAL fuer jeden + // `append_context_mesh`-Aufruf und brach dabei unbemerkt Dach/Treppe/ + // Stuetze/truck-Extrusion/2D-Zeichnungs-Bodenspuren (alle `kind: + // Extrusion`, orientierungserhaltend wie eine Wand) — nur echte Import- + // Rohdaten (Terrain/Imported) duerfen negiert werden. + let mut terrain = Mesh::default(); + append_context_mesh(&mut terrain, &flat_context_tri(2.0, MeshKind::Terrain, None)); + let (tmin, tmax) = terrain.bounds(); + assert!( + tmin[2] < -0.99 && tmax[2].abs() < 1e-5, + "Terrain: Modell-y in [0,1] wird negiert -> world.z in [-1,0], war {:?}..{:?}", + tmin, + tmax + ); + + let mut imported = Mesh::default(); + append_context_mesh(&mut imported, &flat_context_tri(2.0, MeshKind::Imported, None)); + let (imin, imax) = imported.bounds(); + assert!( + imin[2] < -0.99 && imax[2].abs() < 1e-5, + "Imported: Modell-y in [0,1] wird negiert -> world.z in [-1,0], war {:?}..{:?}", + imin, + imax + ); + + let mut extrusion = Mesh::default(); + append_context_mesh(&mut extrusion, &flat_context_tri(2.0, MeshKind::Extrusion, None)); + let (emin, emax) = extrusion.bounds(); + assert!( + emin[2].abs() < 1e-5 && emax[2] > 0.99, + "Extrusion: Modell-y in [0,1] bleibt UNVERAENDERT -> world.z in [0,1], war {:?}..{:?}", + emin, + emax + ); + } + #[test] fn context_mesh_default_farbe_je_kind() { // Ohne explizite Farbe greift die kind-Default-Farbe (three.js mats.*). diff --git a/src-tauri/render3d/src/mesh.rs b/src-tauri/render3d/src/mesh.rs index 84e02e5..f6f0740 100644 --- a/src-tauri/render3d/src/mesh.rs +++ b/src-tauri/render3d/src/mesh.rs @@ -59,8 +59,8 @@ use std::collections::HashMap; use crate::openings::{split_range_by_voids, MIN_SPAN}; use crate::types::{ - Hole, Mesh, MeshInput, Opening, Point2, Rgb, SlabInput, TexturedMesh, WallInput, WallLayer, - FLOATS_PER_VERTEX, TEXTURED_FLOATS_PER_VERTEX, + Hole, Mesh, MeshInput, MeshKind, Opening, Point2, Rgb, SlabInput, TexturedMesh, WallInput, + WallLayer, FLOATS_PER_VERTEX, TEXTURED_FLOATS_PER_VERTEX, }; /// Ein Quader-Mesh besteht aus 6 Seiten (Boden, Deckel, 4 Waende) zu je 2 @@ -1244,7 +1244,12 @@ pub fn build_terrain_mesh(meshes: &[MeshInput]) -> Mesh { /// Quell-Mesh. /// /// Koordinaten: model `(x, y, z)` -> world `(x, z, y)` (Hoehe entlang +Y), exakt -/// wie `extrude_layer_segment`/`extrude_slab` und `Viewport3D.tsx`. +/// wie `extrude_layer_segment`/`extrude_slab` und `Viewport3D.tsx` — GILT NUR +/// fuer `MeshKind::Extrusion` (plan-abgeleitete, orientierungserhaltende +/// Geometrie: Dach/Treppe/Stuetze/truck-Extrusion/2D-Zeichnungs-Bodenspuren, +/// s. u.). `MeshKind::Terrain`/`MeshKind::Imported` (echte, UNABHAENGIGE xyz- +/// Rohdaten aus einem Import) negieren zusaetzlich die Nord-Achse (Modell-y), +/// s. Kommentar an `negate_north` unten. /// /// DOPPELSEITIG: jedes Dreieck wird ZWEIMAL emittiert (Vorderseite `a,b,c` mit /// Normale `+n`, Rueckseite `a,c,b` mit `-n`), weil das Quell-Winding von @@ -1271,10 +1276,29 @@ pub fn append_context_mesh(mesh: &mut Mesh, input: &MeshInput) { color } }; - // world-Position aus Modell (x, y, z=Hoehe): (x, hoehe, y). + // world-Position aus Modell (x, y, z=Hoehe): (x, hoehe, ±y). Die Nord-Achse + // (Modell-y) wird NUR fuer `Terrain`/`Imported` NEGIERT — ein reiner + // Komponenten-Tausch ohne Vorzeichenwechsel ist fuer einen allgemeinen + // (unabhaengigen) xyz-Punktsatz eine Spiegelung (Determinante -1), das + // betrifft NUR echte Import-Rohdaten (swisstopo/OSM: Terrain, Gebaeude). + // `Extrusion` entsteht dagegen IMMER ueber eine orientierungserhaltende + // Extrusions-/Rotationskonstruktion (Dach/Treppe/Stuetze/truck-Extrusion/ + // 2D-Zeichnungs-Bodenspuren) — dort MUSS die Konvention unveraendert + // bleiben, exakt wie bei Wand/Slab. Fund 2026-09-24: "swisstopo-Import im + // 3D komplett gespiegelt" (betraf Kontext-Meshes) — der damalige Fix + // negierte pauschal ALLE `append_context_mesh`-Aufrufer und brach dabei + // unbemerkt Dach/Treppe/Stuetze/truck-Extrusion/2D-Zeichnungs-Bodenspuren + // (Nutzer-Report 2026-09-27: "gewisse Dinge sind noch gespiegelt im 3D", + // beim Durchgehen ALLER `append_context_mesh`-Aufrufer gefunden — s. + // PENDENZEN.md fuer die volle Herleitung). + let negate_north = matches!(input.kind, MeshKind::Terrain | MeshKind::Imported); let vworld = |i: usize| -> [f32; 3] { let b = i * 3; - [pos[b], pos[b + 2], pos[b + 1]] + if negate_north { + [pos[b], pos[b + 2], -pos[b + 1]] + } else { + [pos[b], pos[b + 2], pos[b + 1]] + } }; for t in input.indices.chunks_exact(3) { let (ia, ib, ic) = (t[0] as usize, t[1] as usize, t[2] as usize); @@ -1527,3 +1551,35 @@ pub fn extrude_slab(mesh: &mut Mesh, slab: &SlabInput) { push_tri_oriented(mesh, ba, tb, ta, normal, color); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::MeshKind; + + /// Regression: Nutzer-Report "swisstopo-Import im 3D komplett gespiegelt" + /// (2026-09-24). `append_context_mesh` bildete Modell (x,y,z) OHNE + /// Vorzeichenwechsel auf world (x, z, y) ab — ein reines Achsen-Vertauschen + /// ohne Negierung ist fuer einen allgemeinen (unabhaengigen) xyz-Punktsatz + /// immer eine Spiegelung (Determinante -1), anders als bei Wand/Slab, die + /// ueber eine orientierungserhaltende Extrusion entstehen. Fix: die + /// Nord-Achse (Modell-y) wird jetzt negiert -> world (x, z, -y). + #[test] + fn append_context_mesh_negiert_die_nord_achse() { + let input = MeshInput { + // Ein Dreieck; der dritte Punkt (2,3,4) ist der interessante Fall + // (x=2, y=3=Nord, z=4=Hoehe) -> erwartet world (2, 4, -3). + positions: vec![0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 2.0, 3.0, 4.0], + indices: vec![0, 1, 2], + kind: MeshKind::Imported, + color: None, + material_index: None, + vertex_colors: vec![], + }; + let mut mesh = Mesh::default(); + append_context_mesh(&mut mesh, &input); + // Erstes emittiertes Dreieck (Vorderseite a,b,c) — dritter Vertex (c). + let base = 2 * FLOATS_PER_VERTEX; + assert_eq!(&mesh.verts[base..base + 3], &[2.0, 4.0, -3.0]); + } +} diff --git a/src-tauri/render3d/src/shaders.rs b/src-tauri/render3d/src/shaders.rs index 8b4f76c..26bbae9 100644 --- a/src-tauri/render3d/src/shaders.rs +++ b/src-tauri/render3d/src/shaders.rs @@ -230,6 +230,9 @@ fn fs_main(in : VsOut) -> @location(0) vec4 { /// Layout = das Haupt-Mesh-Layout `[pos, normal, color]` (color wird ignoriert), damit /// derselbe Vertex-Puffer (Terrain-Overlay) ohne Re-Meshing genutzt werden kann. /// Bild-Zeile 0 liegt im NORDEN (+Y) -> die Textur-v-Achse wird gespiegelt (1 - v). +/// world.z entspricht dabei dem NEGIERTEN Modell-y (s. `mesh.rs:: +/// append_context_mesh`) — die v-Berechnung negiert `world_pos.z` daher zurück, +/// bevor sie gegen die (unveränderte, modell-raumige) `bbox` verglichen wird. pub const MESH_AERIAL_WGSL: &str = r#" struct Globals { view_proj : mat4x4, @@ -289,10 +292,15 @@ fn fs_main(in : VsOut) -> @location(0) vec4 { let fill = max(dot(n, fill_l), 0.0) * globals.sun_color.rgb * vec3(0.24, 0.27, 0.30); - // UV aus der Welt-Lage + Bild-Bbox. world.x = Ost, world.z = Nord. + // UV aus der Welt-Lage + Bild-Bbox. world.x = Ost, world.z = -Nord (Modell-y + // wird beim Mesh-Bau negiert, s. `mesh.rs::append_context_mesh` — Fund + // "swisstopo-Import im 3D gespiegelt", 2026-09-24: NACH diesem Fix zeigt + // world.z in die GEGENGESETZTE Richtung von Modell-y, die v-Berechnung + // hier muss das kompensieren, sonst liegt das drapierte Luftbild wieder + // spiegelverkehrt auf dem jetzt korrekt positionierten Terrain-Mesh). let span = vec2(aerial.bbox.z - aerial.bbox.x, aerial.bbox.w - aerial.bbox.y); let u = (in.world_pos.x - aerial.bbox.x) / span.x; - let v = (in.world_pos.z - aerial.bbox.y) / span.y; + let v = (-in.world_pos.z - aerial.bbox.y) / span.y; // Bild-Zeile 0 = Nord (+Y) -> v spiegeln. Ausserhalb [0,1] -> Randpixel (Clamp // uebernimmt der Sampler mit ClampToEdge). let albedo = textureSample(tex, samp, vec2(u, 1.0 - v)).rgb; diff --git a/src-tauri/render3d/src/types.rs b/src-tauri/render3d/src/types.rs index 364b9d7..3ce25a5 100644 --- a/src-tauri/render3d/src/types.rs +++ b/src-tauri/render3d/src/types.rs @@ -355,11 +355,14 @@ impl MeshKind { /// nur noch die Flaechen-Normalen (Flat Shading, wie Wand/Slab) und speist es in /// denselben GPU-Pfad ein. /// -/// KOORDINATEN wie WallInput/SlabInput: die TS-Seite (`projectToModel3d`) liefert -/// `positions` im MODELL-System als flaches `[x, y, z, ...]`-Array (z = Hoehe, in -/// Metern); `mesh.rs` bildet jeden Vertex nach world ab: model `(x, y, z)` -> -/// world `(x, z, y)`, d. h. Grundriss in der XZ-Ebene, Hoehe entlang +Y (exakt wie -/// `Viewport3D.tsx` die rohen positions konsumiert). +/// KOORDINATEN: die TS-Seite (`projectToModel3d`) liefert `positions` im +/// MODELL-System als flaches `[x, y, z, ...]`-Array (z = Hoehe, in Metern); +/// `mesh.rs::append_context_mesh` bildet jeden Vertex nach world ab: model +/// `(x, y, z)` -> world `(x, z, -y)` — die Nord-Achse (Modell-y) wird NEGIERT +/// (anders als bei WallInput/SlabInput, die ueber eine orientierungserhaltende +/// Extrusion entstehen und daher OHNE Vorzeichenwechsel auskommen — reines +/// Achsen-Vertauschen eines allgemeinen xyz-Punktsatzes waere sonst eine +/// Spiegelung, s. `append_context_mesh`-Doc). /// /// DOPPELSEITIG: Terrain-/Import-Meshes tragen KEIN garantiertes Winding (die /// three.js-Sicht rendert sie mit `DoubleSide`, siehe `io/geoContext.ts`). Da der diff --git a/src/App.tsx b/src/App.tsx index 2314738..2bb9b3c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -46,11 +46,24 @@ import { OpeningEditorDialog } from "./ui/OpeningEditorDialog"; import { ExportSaveDialog } from "./ui/ExportSaveDialog"; import { PromptDialog } from "./ui/PromptDialog"; import { LockConflictDialog } from "./ui/LockConflictDialog"; +import { UnsavedChangesDialog } from "./ui/UnsavedChangesDialog"; import { Toast } from "./ui/Toast"; import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./io/projectFile"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./plan/PlanView"; import type { DisplayResolver } from "./viewport/Viewport3D"; +import { + neighbor3dVertex, + bodyMoveAnchor, + hudFromAnchor, + grip3dTargetKey, + grip3dEditPoint, + cycleGrip3dEditState, + nextGrip3dEditState, + grip3dEditFields, + type Grip3dTarget, + type Grip3dEditState, +} from "./viewport/grip3dHud"; import { ResourceManager } from "./ui/ResourceManager"; import type { ResourceManagerHandlers, TabId as ResourceTabId } from "./ui/ResourceManager"; import { LayoutSheetView } from "./ui/LayoutSheet"; @@ -92,6 +105,7 @@ import { computeSnap } from "./tools/snapping"; import { requiredPoints, transformPreview, + rotateGizmoShapes, } from "./tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "./tools/transform"; import type { @@ -118,7 +132,8 @@ import { usePanelHostBase } from "./state/usePanelHostBase"; import { useDockDragState } from "./state/useDockDragState"; import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers"; import { addNewElementsToActiveGroup, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; -import type { GroupMembership } from "./state/groupActions"; +import type { GroupMembership, MemberKind } from "./state/groupActions"; +import { isLocked, setLockedForMembers } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; import { useProjectActions } from "./state/useProjectActions"; import { @@ -138,7 +153,13 @@ import { useThemeModeState } from "./theme/useThemeMode"; import { CommandLine } from "./ui/CommandLine"; import type { CommandLineHandle, CommandLineField, CommandLineOption } from "./ui/CommandLine"; import { CommandEngine } from "./commands/engine"; -import type { EngineHost } from "./commands/engine"; +import { loadAliasOverrides, saveAliasOverrides } from "./state/commandAliasOverrides"; +import { + loadShortcutOverrides, + saveShortcutOverrides, + type ShortcutOverrides, +} from "./state/keyboardShortcuts"; +import type { EngineHost, EngineMods } from "./commands/engine"; import type { CommandContext } from "./commands/types"; import { t, useT } from "./i18n"; import { @@ -155,6 +176,7 @@ import { unionDrawings, } from "./editors/booleanOps"; import type { BooleanResult } from "./editors/booleanOps"; +import { applyDrawingStyle, readDrawingStyle } from "./editors/matchProps"; // Globaler Store (Slices: project/selection/view/layout). import { useStore } from "./state/appStore"; @@ -171,7 +193,7 @@ import { hostWithMode } from "./panels/host"; import { deriveSelection } from "./state/selectionInfo"; import type { Selection } from "./state/selectionInfo"; import { centroid as roomCentroid } from "./geometry/roomArea"; -import { docFromText, plainText } from "./text/richText"; +import { docFromText, plainText, DEFAULT_PRESETS } from "./text/richText"; import type { RichTextDoc } from "./text/richText"; import { revealPanel, saveLayout } from "./panels/layout"; import { listPanels } from "./panels/registry"; @@ -219,6 +241,7 @@ const TOOL_COMMAND: Partial> = { room: "room", line: "line", xline: "xline", + ray: "ray", polyline: "polyline", rect: "rect", circle: "circle", @@ -230,6 +253,11 @@ const TOOL_COMMAND: Partial> = { bezier: "bezier", dimension: "dimension", kote: "kote", + detailref: "detailref", + scalebar: "scalebar", + revcloud: "revcloud", + pointmarker: "pointmarker", + wipeout: "wipeout", text: "text", leader: "leader", textpath: "textpath", @@ -427,6 +455,8 @@ export default function App() { const { layerClipboard, setLayerClipboard, + drawingStyleClipboard, + setDrawingStyleClipboard, menu, setMenu, editor, @@ -622,14 +652,19 @@ export default function App() { // ── Transformation (Bewegen/Spiegeln/Drehen) auf der Auswahl ────────────── // Trägt ALLE von der Transform-Engine unterstützten Elementarten (Wände, 2D- - // Zeichnungen, extrudierte Körper, Stützen) — sonst wirken die Kürzel m/s/d nur - // auf Wände/2D, obwohl `commitTransform` auch Extrude/Stütze bewegt. + // Zeichnungen, extrudierte Körper, Stützen, Decken/Dächer/Treppen/Räume) — + // sonst wirken die Kürzel m/s/d nur auf einen Teil dessen, was + // `commitTransform` tatsächlich bewegt. const transformSel: TransformSelection = { wallIds: selectedWallIds, drawingId: selectedDrawingId, drawingIds: selectedDrawingIds, extrudedSolidId: selectedExtrudedSolidId, columnId: selectedColumnId, + ceilingIds: selectedCeilingIds, + roofIds: selectedRoofIds, + stairIds: selectedStairIds, + roomIds: selectedRoomIds, }; const snapForTransform = (raw: Vec2, pxPerMeter: number, mods: ToolMods, points: Vec2[]) => computeSnap({ @@ -657,7 +692,25 @@ export default function App() { eff.length === need ? transformPreview(project, transformSel, tr.op, eff, tr.copyMode, tr.count) : []; - setDraft({ preview, vertices: tr.points, snap: snapResult }); + // Dreh-Gizmo (Radius-Kreis + Referenz-/Winkel-Strahl) ZUSÄTZLICH zur + // transformierten Vorschau, sobald Zentrum+Referenzpunkt stehen und der + // dritte Punkt (Winkel) noch läuft — Nutzer-Wunsch „bei Drehen auch eine + // Darstellung". Über denselben `preview`-Kanal wie oben → zeichnet sich + // automatisch in 2D UND 3D (s. `tools/transform.ts::rotateGizmoShapes`-Doc). + const gizmo = + tr.op === "rotate" && tr.points.length === 2 + ? rotateGizmoShapes(tr.points[0], tr.points[1], cursor) + : []; + // `hud.at` positioniert die Cursor-HUD-Box (Werte selbst kommen aus + // `transformFields()`/`hudFields`, s. o. — Nutzer-Wunsch „bei Drehen auch + // eine Darstellung"); ohne `hud` bliebe die Box unsichtbar (2D UND 3D), + // auch wenn `hudFields` bereits gültige Felder liefert. + setDraft({ + preview: [...preview, ...gizmo], + vertices: tr.points, + snap: snapResult, + hud: { at: cursor }, + }); }; const transformClick = (raw: Vec2, pxPerMeter: number, mods: ToolMods) => { const tr = activeTransform!; @@ -752,6 +805,10 @@ export default function App() { selectedDrawingIds, selectedExtrudedSolidId, selectedColumnId, + selectedCeilingIds, + selectedRoofIds, + selectedStairIds, + selectedRoomIds, groupPath, setProject, setDraft, @@ -769,6 +826,10 @@ export default function App() { selectedDrawingIds, selectedExtrudedSolidId, selectedColumnId, + selectedCeilingIds, + selectedRoofIds, + selectedStairIds, + selectedRoomIds, groupPath, setProject, setDraft, @@ -794,6 +855,10 @@ export default function App() { drawingIds: c.selectedDrawingIds, extrudedSolidId: c.selectedExtrudedSolidId, columnId: c.selectedColumnId, + ceilingIds: c.selectedCeilingIds, + roofIds: c.selectedRoofIds, + stairIds: c.selectedStairIds, + roomIds: c.selectedRoomIds, }, }; }, @@ -852,6 +917,51 @@ export default function App() { } const engine = engineRef.current; + // Nutzer-Kürzel-Übersteuerungen (Einstellungen → Remap) — aus localStorage + // geladen, bei jeder Änderung sofort an die Engine gereicht (s. `commands/ + // engine.ts::setAliasOverrides`, `state/commandAliasOverrides.ts`). + const [aliasOverrides, setAliasOverridesState] = useState>(() => + loadAliasOverrides(), + ); + useEffect(() => engine.setAliasOverrides(aliasOverrides), [engine, aliasOverrides]); + const setAliasOverrides = (next: Record) => { + setAliasOverridesState(next); + saveAliasOverrides(next); + }; + // Ändert das native Einstellungs-Fenster (separates Tauri-Fenster) die + // Kürzel, landen sie zwar in localStorage, aber das `storage`-Event feuert + // NIE im Fenster, das selbst geschrieben hat — nur in den ANDEREN Fenstern + // (Web-Storage-API-Standardverhalten). Genau der Fall hier: dieses + // (Haupt-)Fenster empfängt die Änderung darüber und zieht sie nach. + useEffect(() => { + const onStorage = (e: StorageEvent) => { + if (e.key === "cad.commandAliasOverrides") setAliasOverridesState(loadAliasOverrides()); + }; + window.addEventListener("storage", onStorage); + return () => window.removeEventListener("storage", onStorage); + }, []); + + // Nutzer-Übersteuerungen der echten Tastatur-Shortcuts (Einstellungen → + // Tastenkürzel) — analoges Muster zu `aliasOverrides` oben, aber für + // `state/keyboardShortcuts.ts` (Ctrl/Cmd+Z usw.) statt der Befehlszeilen- + // Kürzel. Direkt an alle betroffenen Hooks unten durchgereicht. + const [shortcutOverrides, setShortcutOverridesState] = useState(() => + loadShortcutOverrides(), + ); + const setShortcutOverrides = (next: ShortcutOverrides) => { + setShortcutOverridesState(next); + saveShortcutOverrides(next); + }; + useEffect(() => { + const onStorage = (e: StorageEvent) => { + if (e.key === "dossier.keyboardShortcutOverrides") { + setShortcutOverridesState(loadShortcutOverrides()); + } + }; + window.addEventListener("storage", onStorage); + return () => window.removeEventListener("storage", onStorage); + }, []); + // Auf Engine-Zustandsänderungen re-rendern (Prompt/Optionen aktualisieren). const [engineTick, setEngineTick] = useState(0); useEffect( @@ -938,8 +1048,13 @@ export default function App() { const hasSel = selectedWallIds.length > 0 || !!selectedDrawingId || + selectedDrawingIds.length > 0 || !!selectedExtrudedSolidId || - !!selectedColumnId; + !!selectedColumnId || + selectedCeilingIds.length > 0 || + selectedRoofIds.length > 0 || + selectedStairIds.length > 0 || + selectedRoomIds.length > 0; if (!hasSel) { notify(t("transform.needSelection"), "info"); return; @@ -967,19 +1082,41 @@ export default function App() { // ihn in DIESELBE ansichts-agnostische CommandEngine wie PlanView (move/pick). // Snapping/Tab-Felder/Commit laufen unverändert über den EngineHost; die neuen // Elemente landen auf dem aktiven Geschoss (host.context().level). - const onWorkplanePoint = (kind: "move" | "pick", model: Vec2) => { + const onWorkplanePoint = (kind: "move" | "pick", model: Vec2, mods?: EngineMods) => { + // Läuft eine interaktive Transformation (m/s/d — Bewegen/Spiegeln/Drehen + // der Auswahl), hat sie Vorrang — exakt wie `toolHandlers.onToolMove`/ + // `onToolClick` das für den 2D-Plan schon tun (s. o.). Bisher war das hier + // NICHT verdrahtet: ein Klick im 3D-Viewport während m/s/d tat schlicht + // nichts, Drehen/Verschieben/Spiegeln funktionierten im 3D also gar nicht + // (Nutzer-Wunsch „bei Drehen auch eine Darstellung" — die Vorschau kommt + // jetzt über denselben `draft`-Kanal wie das Zeichnen, s. `transformMove`). + // 3D hat kein echtes pxPerMeter (Perspektive) — derselbe feste Näherungs- + // wert wie `snapFor3dVertex` oben. + if (activeTransform) { + const toolMods: ToolMods = { shift: !!mods?.shift, ctrl: !!mods?.ctrl, alt: false }; + if (kind === "move") transformMove(model, 90, toolMods); + else transformClick(model, 90, toolMods); + return; + } const eng = engineRef.current; if (!eng?.isActive()) return; - if (kind === "move") eng.move(model); - else eng.pick(model); + if (kind === "move") eng.move(model, mods); + else eng.pick(model, mods); }; const onWorkplaneConfirm = () => { + // Rechtsklick-ohne-Drag/Doppelklick im 3D während einer Transformation = + // abbrechen — dasselbe Verhalten wie `onToolCommit` im 2D-Plan (§ s. o.). + if (activeTransform) { + setActiveTransform(null); + setDraft(null); + return; + } const eng = engineRef.current; if (eng?.isActive()) eng.confirm(); }; // Globaler Undo/Redo-Shortcut — siehe state/useKeyboardShortcuts.ts. - useUndoRedoShortcut(undo, redo); + useUndoRedoShortcut(undo, redo, shortcutOverrides); // Esc/Enter/Backspace für das aktive Zeichenwerkzeug. Siehe // state/useKeyboardShortcuts.ts. Die Zifferntasten-Werkzeugwahl @@ -1043,15 +1180,21 @@ export default function App() { if (selectedSectionLineIds.length) { for (const id of selectedSectionLineIds) patchLevel(id, { linePoints: undefined }); } - const dids = new Set(selectedDrawingIds); - const wids = new Set(selectedWallIds); - const cids = new Set(selectedCeilingIds); - const oids = new Set(selectedOpeningIds); - const stids = new Set(selectedStairIds); - const rmids = new Set(selectedRoomIds); + // Objekt-Sperre: gesperrte Elemente aus der Löschung ausnehmen (s. + // `moveGrip`/`moveElementBy` in projectSlice.ts für dieselbe Prüfung + // beim Ziehen). ExtrudedSolid/Kontext-Objekte haben kein `locked`-Feld + // (s. deren Typdefinitionen) — bleiben ungefiltert. + const notLocked = (kind: MemberKind, ids: string[]) => + ids.filter((id) => !isLocked(project, kind, id)); + const dids = new Set(notLocked("drawingIds", selectedDrawingIds)); + const wids = new Set(notLocked("wallIds", selectedWallIds)); + const cids = new Set(notLocked("ceilingIds", selectedCeilingIds)); + const oids = new Set(notLocked("openingIds", selectedOpeningIds)); + const stids = new Set(notLocked("stairIds", selectedStairIds)); + const rmids = new Set(notLocked("roomIds", selectedRoomIds)); const exids = new Set(selectedExtrudedSolidIds); - const colids = new Set(selectedColumnIds); - const rfids = new Set(selectedRoofIds); + const colids = new Set(notLocked("columnIds", selectedColumnIds)); + const rfids = new Set(notLocked("roofIds", selectedRoofIds)); const ctxids = new Set(selectedContextObjectIds); setProject((p) => ({ ...p, @@ -1090,6 +1233,7 @@ export default function App() { activeTransform, project, activeLevelId: activeLevel.id, + shortcutOverrides, selectedDrawingIds, selectedWallIds, selectedCeilingIds, @@ -1148,7 +1292,14 @@ export default function App() { // Ctrl/Cmd+S = Split, Ctrl/Cmd+J = Join der selektierten Drawing2D-Elemente — // siehe state/useKeyboardShortcuts.ts. - useSplitJoinShortcut(selectedDrawingIds, engine, runSplit, setSelectedDrawingIds, setSelectedWallIds); + useSplitJoinShortcut( + selectedDrawingIds, + engine, + runSplit, + setSelectedDrawingIds, + setSelectedWallIds, + shortcutOverrides, + ); // Ctrl/Cmd+Shift+U/D/I = Boolean Vereinigung/Subtraktion/Schnitt — siehe // state/useKeyboardShortcuts.ts. (Ctrl/Cmd+C/V-Kopieren/Einfügen folgt weiter @@ -1182,7 +1333,62 @@ export default function App() { setSelectedDrawingIds(result.created.map((d) => d.id)); setSelectedWallIds([]); }; - useBooleanOpsShortcut(selectedDrawingIds, project.drawings2d, applyBoolean); + useBooleanOpsShortcut(selectedDrawingIds, project.drawings2d, applyBoolean, shortcutOverrides); + + // „Eigenschaften übertragen" (2D-Kontextmenü) — dasselbe Zwischenablage- + // Muster wie beim Ebenen-Menü (`layerClipboard`), nur für den vollen + // Aussehen-Stil eines 2D-Elements (s. `editors/matchProps.ts`). + const copyDrawingStyle = () => { + const d = project.drawings2d.find((x) => x.id === selectedDrawingIds[0]); + if (d) setDrawingStyleClipboard(readDrawingStyle(d)); + }; + const pasteDrawingStyle = () => { + if (!drawingStyleClipboard || selectedDrawingIds.length === 0) return; + setProject((p) => applyDrawingStyle(p, selectedDrawingIds, drawingStyleClipboard)); + }; + + // Objekt sperren/entsperren (Kontextmenü) — wirkt auf die GANZE aktuelle + // Auswahl (alle Elementarten, nicht nur 2D-Zeichnungen), ein Undo-Schritt. + // Anders als der Ebenen-/Geschoss-Sperrmodus (`DisplayMode`, session-lokal) + // ist `locked` hier ein persistiertes Feld am Element selbst, s. + // `state/objectLock.ts`. + const selectionLockMembers: Partial> = { + wallIds: selectedWallIds, + drawingIds: selectedDrawingIds, + ceilingIds: selectedCeilingIds, + roomIds: selectedRoomIds, + stairIds: selectedStairIds, + columnIds: selectedColumnIds, + roofIds: selectedRoofIds, + openingIds: selectedOpeningIds, + }; + const selectionLockIds = ( + Object.entries(selectionLockMembers) as [MemberKind, string[]][] + ).flatMap(([kind, ids]) => ids.map((id) => [kind, id] as const)); + const selectionAllLocked = + selectionLockIds.length > 0 && + selectionLockIds.every(([kind, id]) => isLocked(project, kind, id)); + const toggleSelectionLock = () => { + if (selectionLockIds.length === 0) return; + setProject((p) => setLockedForMembers(p, selectionLockMembers, !selectionAllLocked)); + }; + + // „Nicht drucken"/„Drucken" (Kontextmenü) — nur `Drawing2D` kennt + // `noPrint` (Nutzer-Wunsch „Kein 'nicht druckend'-Flag im Modell"), daher + // simpler als die Sperre oben: direkt über `selectedDrawingIds`. + const selectionAllNoPrint = + selectedDrawingIds.length > 0 && + selectedDrawingIds.every((id) => project.drawings2d.find((d) => d.id === id)?.noPrint); + const toggleSelectionNoPrint = () => { + if (selectedDrawingIds.length === 0) return; + const next = !selectionAllNoPrint; + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + selectedDrawingIds.includes(d.id) ? { ...d, noPrint: next } : d, + ), + })); + }; // Ctrl/Cmd+G / Ctrl/Cmd+Shift+G = Gruppieren/Auflösen (Vectorworks-artig, // s. state/groupActions.ts). `applyGroupSelection` setzt nach dem Gruppieren/ @@ -1213,6 +1419,7 @@ export default function App() { }, selectedGroupIds, applyGroupSelection, + shortcutOverrides, ); // Doppelklick auf ein gruppiertes Element → Gruppe betreten (Isolation): @@ -1295,11 +1502,16 @@ export default function App() { selectedDrawingIds, selectedExtrudedSolidId, selectedColumnId, + selectedCeilingIds, + selectedRoofIds, + selectedStairIds, + selectedRoomIds, engine, setDraft, requestCopyCount, onRunCommand, commandLineRef, + shortcutOverrides, ); // ── Projekt-Mutationen (aus dem Store-Slice) ───────────────────────────── @@ -1337,6 +1549,9 @@ export default function App() { patchLineStyle, addLineStyle, deleteLineStyle, + patchTextStyle, + addTextStyle, + deleteTextStyle, addPen, renamePen, deletePen, @@ -1347,6 +1562,15 @@ export default function App() { patchPenSetColor, patchPenSetWeight, seedStandardPenSet, + addCustomPalette, + renameCustomPalette, + deleteCustomPalette, + addColorToCustomPalette, + removeColorFromCustomPalette, + setCustomPaletteVisible, + setBuiltinPaletteVisible, + insertDrawingPoint, + deleteDrawingPoint, patchWallType, setOverrideRules, patchCeilingType, @@ -1441,6 +1665,8 @@ export default function App() { selectedDrawingIds, levelId: activeLevel.id, visibleCodes, + scaleDenominator, + snap, setDraft, snapFor, @@ -1467,34 +1693,11 @@ export default function App() { onSelectTool, activeLevel.kind === "floor", engineRef, + shortcutOverrides, gripDragInfoRef, edgeDragInfoRef, ); - // Feld-Zustand fürs Cursor-HUD (neben der Maus, VW-Stil): läuft ein Punkt- - // ODER Kanten-Griff-Drag, hat er Vorrang (dieselben Felder wie unten in der - // Befehlszeile — Länge/Winkel- bzw. Abstand-Tab-Zyklus), sonst die Befehls- - // Engine-Felder beim Zeichnen. Vorher zeigte das Cursor-HUD beim Griff-Ziehen - // GAR KEINE Länge/Winkel-Werte an (nur die Befehlszeile unten) — Nutzer- - // Wunsch: „du kannst [Länge/Winkel] gleich bei der Maus anzeigen wie beim - // Erstellen". - const hudFields = - gripEdit - ? { fields: gripEditFields(), typed: cmdTyped } - : edgeEdit - ? { fields: edgeEditFields(), typed: cmdTyped } - : commandActive && engineView.fields.length > 0 - ? { - fields: engineView.fields.map((f) => ({ - id: f.id, - value: f.value, - locked: f.locked, - active: f.active, - })), - typed: cmdTyped, - } - : null; - // Ctrl/Cmd+C / Ctrl/Cmd+V = Bauteile kopieren/einfügen (alle 9 Auswahl-Kanäle, // nicht nur 2D-Zeichenelemente) — siehe state/useKeyboardShortcuts.ts. useElementClipboardShortcut( @@ -1525,6 +1728,7 @@ export default function App() { extrudedSolidIds: setSelectedExtrudedSolidIds, columnIds: setSelectedColumnIds, }, + shortcutOverrides, ); // Projektdatei-I/O (Speichern/Öffnen/Lock), Schnellexport (CSV/IFC/OBJ/STL) @@ -1535,6 +1739,8 @@ export default function App() { projectTemplateFileInputRef, lockConflict, setLockConflict, + pendingDiscard, + setPendingDiscard, openImportForFile, onSaveProject, onNewProject, @@ -1722,12 +1928,59 @@ export default function App() { ctrl: false, }); }; + // Cursor-HUD (Länge/Winkel bzw. Δx/Δy) für einen 3D-Griff-Drag — Nutzer- + // Report „beim Verschieben von Elementen zeigt es die Werte nicht an": die + // 3D-Griffe (`onEdit3dVertex`/`onEdit3dBody`) mutierten das Modell bisher + // OHNE je `setDraft(...)` mit einem `hud` zu füllen (anders als die 2D- + // Griff-Bearbeitung, `state/useGripEditing.ts::hudFor`/`edgeHudFor`, die das + // von Anfang an tat) — der Cursor-HUD blieb daher leer, obwohl der Kanal + // (`hudFields`/`draft.hud`, s. `Wasm3DViewport.tsx`) längst bis in den 3D- + // Viewport durchgereicht ist. Die reine Geometrie (Nachbar-/Anker-Auflösung) + // lebt in `viewport/grip3dHud.ts` (eigenständig testbar). + // + // Läuft während eines „move"-Griff-Drags (ganzes Element verschieben): sammelt + // die seit Drag-Beginn angewandten Deltas je Ziel-Element, damit das HUD die + // GESAMTE Verschiebung zeigt statt des winzigen Pro-Event-Deltas. `rawTotal` + // = reine Maus-Summe (auch bei aktivem Feld-Controller weitergeführt, damit + // ein entsperrtes Feld sofort wieder der Maus folgt); `appliedTotal` = was + // TATSÄCHLICH aufs Modell angewandt wurde (kann bei Locks abweichen). Reset + // bei Ziel-Wechsel (neuer Drag) UND in `onEdit3dEnd` (Drag-Ende). + const bodyDragRef = useRef<{ key: string; anchor: Vec2; rawTotal: Vec2; appliedTotal: Vec2 } | null>( + null, + ); + // Feld-Controller (Tab-Zyklus, getippte Werte) für einen laufenden 3D-Griff- + // Drag — Nutzer-Report „man sieht Länge/Winkel, aber man kann nichts + // eingeben". Eigenständiges 3D-Äquivalent zu `useGripEditing.ts`s `gripEdit` + // (s. `viewport/grip3dHud.ts`-Dateikommentar für das „warum eigenständig"). + const [grip3dEdit, setGrip3dEdit] = useState(null); + // Letzter bekannter roh (maus-getriebener, UN-gelockter) Zustand des + // laufenden 3D-Griff-Drags — Grundlage fürs ÖFFNEN des Feld-Controllers + // (Tab friert die AKTUELLE Position ein, s. `cycleGrip3dEditState`). + const last3dDragRef = useRef< + { target: Grip3dTarget; index: number; kind: "vertex" | "move"; anchor: Vec2; raw: Vec2 } | null + >(null); // Ein 3D-Vertex-Griff wurde gezogen. `target` benennt das konkrete Element // (Wand-ID ODER Drawing-ID), `index` den Vertex. Liefert den effektiv // angewandten (gesnappten) Punkt zurück — der 3D-Viewport nutzt ihn, um // koinzidente Endpunkte anderer gewählter Elemente mitzuführen und den // Snap-Marker zu zeigen. `snapped=false` (für mitgeführte Geschwister) wendet // den Punkt direkt an, ohne erneut zu snappen. + // Reine Mutations-Anwender OHNE Lock-/Snap-/HUD-Logik — von `onEdit3dVertex`/ + // `onEdit3dBody` (Maus-Pfad) UND `submitGrip3dEditValue` (Tastatur-Pfad) + // gemeinsam genutzt, damit Letzterer NICHT `onEdit3dVertex`/`onEdit3dBody` + // rekursiv aufruft — das würde `grip3dEdit`/`bodyDragRef` über einen VERALTETEN + // Closure-Wert lesen (React-State ist innerhalb desselben Funktionsaufrufs + // noch nicht aktualisiert) und den gerade getippten Wert wieder verwerfen. + const applyVertexPoint = (target: Grip3dTarget, index: number, pt: Vec2) => { + if (target.roofId) moveRoofGrip(target.roofId, index, pt); + else if (target.ceilingId) moveCeilingGrip(target.ceilingId, index, pt); + else moveGripOf(target.drawingId ?? null, target.wallId ?? null, index, pt); + }; + const applyBodyDelta = (target: Grip3dTarget, delta: Vec2) => { + if (target.roofId) moveRoofBy(target.roofId, delta); + else if (target.ceilingId) moveCeilingBy(target.ceilingId, delta); + else moveElementByOf(target.drawingId ?? null, target.wallId ?? null, delta); + }; const onEdit3dVertex = ( target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string }, index: number, @@ -1735,8 +1988,22 @@ export default function App() { excludeWallIds?: Set, excludeDrawingIds?: Set, ): Vec2 => { + // Nachbarpunkt VOR der Mutation auflösen (Wand/Zeichnung/Decke/Dach ändern + // sich hier nur am gezogenen `index`, der Nachbar bleibt stabil). + const neighbor = neighbor3dVertex(project, target, index); let pt = model; - if (excludeWallIds || excludeDrawingIds) { + const ge = grip3dEdit; + if ( + ge && + ge.kind === "vertex" && + ge.index === index && + grip3dTargetKey(ge.target) === grip3dTargetKey(target) && + (ge.locks.length != null || ge.locks.angle != null) + ) { + // Feld-Controller aktiv: getippte/eingefrorene Werte übersteuern die + // Maus — kein Snap währenddessen (deckungsgleich mit 2D `onGripMove`). + pt = grip3dEditPoint(ge.anchor, ge.locks, model); + } else if (excludeWallIds || excludeDrawingIds) { const snapResult = snapFor3dVertex( model, excludeWallIds ?? new Set(), @@ -1744,18 +2011,101 @@ export default function App() { ); pt = snapResult?.point ?? model; } - if (target.roofId) moveRoofGrip(target.roofId, index, pt); - else if (target.ceilingId) moveCeilingGrip(target.ceilingId, index, pt); - else moveGripOf(target.drawingId ?? null, target.wallId ?? null, index, pt); + applyVertexPoint(target, index, pt); + if (neighbor) last3dDragRef.current = { target, index, kind: "vertex", anchor: neighbor, raw: model }; + setDraft({ + preview: [], + vertices: [], + snap: null, + hud: neighbor ? hudFromAnchor(neighbor, pt) : undefined, + }); return pt; }; const onEdit3dBody = ( target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string }, delta: Vec2, ) => { - if (target.roofId) moveRoofBy(target.roofId, delta); - else if (target.ceilingId) moveCeilingBy(target.ceilingId, delta); - else moveElementByOf(target.drawingId ?? null, target.wallId ?? null, delta); + const key = grip3dTargetKey(target); + if (!bodyDragRef.current || bodyDragRef.current.key !== key) { + bodyDragRef.current = { + key, + anchor: bodyMoveAnchor(project, target) ?? { x: 0, y: 0 }, + rawTotal: { x: 0, y: 0 }, + appliedTotal: { x: 0, y: 0 }, + }; + } + const st = bodyDragRef.current; + st.rawTotal = { x: st.rawTotal.x + delta.x, y: st.rawTotal.y + delta.y }; + const rawPoint: Vec2 = { x: st.anchor.x + st.rawTotal.x, y: st.anchor.y + st.rawTotal.y }; + const ge = grip3dEdit; + const desiredPoint = + ge && ge.kind === "move" && grip3dTargetKey(ge.target) === key && (ge.locks.length != null || ge.locks.angle != null) + ? grip3dEditPoint(ge.anchor, ge.locks, rawPoint) + : rawPoint; + const desiredTotal: Vec2 = { x: desiredPoint.x - st.anchor.x, y: desiredPoint.y - st.anchor.y }; + const appliedDelta: Vec2 = { + x: desiredTotal.x - st.appliedTotal.x, + y: desiredTotal.y - st.appliedTotal.y, + }; + applyBodyDelta(target, appliedDelta); + st.appliedTotal = desiredTotal; + last3dDragRef.current = { target, index: -1, kind: "move", anchor: st.anchor, raw: rawPoint }; + setDraft({ + preview: [], + vertices: [], + snap: null, + hud: { at: desiredPoint, dx: desiredTotal.x, dy: desiredTotal.y }, + }); + }; + // Tab während eines laufenden 3D-Griff-Drags (Endpunkt ODER Verschieben): + // Feld-Controller öffnen/zykeln — analog `useGripEditing.ts:: + // cycleGripEditField`, aber auf `last3dDragRef` als Zustandsquelle statt + // der 2D-Grips-Liste. `Wasm3DViewport.tsx` ruft dies auf einem eigenen + // Tastatur-Listener auf (nur solange EIN 3D-Griff-Drag läuft — s. dort). + const cycleGrip3dEditField = () => { + const info = last3dDragRef.current; + if (!info) return; + setGrip3dEdit((prev) => cycleGrip3dEditState(prev, info)); + requestAnimationFrame(() => commandLineRef.current?.focus()); + }; + // Escape während eines laufenden 3D-Griff-Drags: abbrechen. ALLE fünf + // Griff-Mutationen coalescen ihre Schritte zu GENAU einem Undo-Eintrag pro + // Drag (s. `state/projectSlice.ts::moveGripOf`/`updateWall`/… -Doc), ein + // einzelner `undo()` reicht also, um den GESAMTEN Drag zu verwerfen statt + // nur den letzten Mikro-Schritt. `Wasm3DViewport.tsx` räumt seinen eigenen + // (lokalen) Drag-Zustand danach selbst auf (`endGripDrag`); hier nur der + // Modell-Zustand + der App-seitige Aufräum-Teil (`onEdit3dEnd`). + const cancelGrip3dEdit = () => { + undo(); + onEdit3dEnd(); + }; + // Getippter Zahlenwert im 3D-Feld-Controller — analog `submitGripEditValue`. + // Nutzt `applyVertexPoint`/`applyBodyDelta` (NICHT `onEdit3dVertex`/ + // `onEdit3dBody` selbst, s. deren Dateikommentar oben). + const submitGrip3dEditValue = (value: number) => { + const ge = grip3dEdit; + if (!ge) return; + const next = nextGrip3dEditState(ge, value); + setGrip3dEdit(next); + const raw = last3dDragRef.current?.raw ?? next.anchor; + const pt = grip3dEditPoint(next.anchor, next.locks, raw); + if (next.kind === "vertex") { + applyVertexPoint(next.target, next.index, pt); + last3dDragRef.current = { target: next.target, index: next.index, kind: "vertex", anchor: next.anchor, raw }; + setDraft({ preview: [], vertices: [], snap: null, hud: hudFromAnchor(next.anchor, pt) }); + return; + } + const st = bodyDragRef.current; + if (!st) return; + const desiredTotal: Vec2 = { x: pt.x - st.anchor.x, y: pt.y - st.anchor.y }; + const appliedDelta: Vec2 = { + x: desiredTotal.x - st.appliedTotal.x, + y: desiredTotal.y - st.appliedTotal.y, + }; + applyBodyDelta(next.target, appliedDelta); + st.appliedTotal = desiredTotal; + last3dDragRef.current = { target: next.target, index: -1, kind: "move", anchor: next.anchor, raw }; + setDraft({ preview: [], vertices: [], snap: null, hud: { at: pt, dx: desiredTotal.x, dy: desiredTotal.y } }); }; // First-Griff: neue First-Höhe (world-Y = Modell-Höhe) → Dachneigung. Aus der // aktuellen Neigung die halbe Spannweite ableiten und daraus den neuen Winkel @@ -1771,15 +2121,49 @@ export default function App() { // Halbe Spannweite aus aktueller Geometrie (First/tan(Neigung)). const halfSpan = currentRidge > 1e-4 ? currentRidge / Math.tan(curPitch || 1e-3) : 1; const newPitch = (Math.atan(newRidge / Math.max(0.05, halfSpan)) * 180) / Math.PI; - updateRoof(roofId, { pitchDeg: Math.max(1, Math.min(85, newPitch)) }); + // coalesceKey: EIN First-Drag (viele Maus-Move-Schritte) soll EINEN Undo- + // Schritt erzeugen, s. `state/projectSlice.ts::updateRoof`-Doc. + updateRoof(roofId, { pitchDeg: Math.max(1, Math.min(85, newPitch)) }, `onEdit3dRoofPitch:${roofId}`); + // Cursor-HUD (First-Höhe) — bislang zeigten Höhen-/Kanten-/First-Griff als + // einzige 3D-Griffe GAR KEINEN Wert (Nutzer-Wunsch „generell weiter + // optimieren"). Anker = Dach-Schwerpunkt (`bodyMoveAnchor`, dieselbe + // Formel wie der Verschiebe-Griff). + const at = bodyMoveAnchor(project, { roofId }); + if (at) setDraft({ preview: [], vertices: [], snap: null, hud: { at, text: `First: ${apexHeight.toFixed(3)}m` } }); }; + // Läuft während eines Kanten-Griff-Drags (Decke): sammelt die seit Drag- + // Beginn angewandte Verschiebung fürs Δ-HUD — analog `bodyDragRef`, aber + // ohne Lock-Unterstützung (kein Feld-Controller für Kanten, s. PENDENZEN). + const edgeDragRef = useRef<{ key: string; total: Vec2 } | null>(null); const onEdit3dEdge = (ceilingId: string, aIndex: number, bIndex: number, delta: Vec2) => { moveCeilingEdge(ceilingId, aIndex, bIndex, delta); + const key = `${ceilingId}:${aIndex}:${bIndex}`; + if (!edgeDragRef.current || edgeDragRef.current.key !== key) { + edgeDragRef.current = { key, total: { x: 0, y: 0 } }; + } + const st = edgeDragRef.current; + st.total = { x: st.total.x + delta.x, y: st.total.y + delta.y }; + const c = (project.ceilings ?? []).find((x) => x.id === ceilingId); + const a = c?.outline[aIndex]; + const b = c?.outline[bIndex]; + if (a && b) { + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + const dist = Math.hypot(st.total.x, st.total.y); + setDraft({ preview: [], vertices: [], snap: null, hud: { at: mid, text: `Δ: ${dist.toFixed(3)}m` } }); + } }; const onEdit3dWallTop = (wallId: string, topZ: number) => { - updateWall(wallId, { top: { mode: "custom", z: topZ } }); + // coalesceKey: EIN Höhen-Drag soll EINEN Undo-Schritt erzeugen, s. + // `state/projectSlice.ts::updateWall`-Doc. + updateWall(wallId, { top: { mode: "custom", z: topZ } }, `onEdit3dWallTop:${wallId}`); + const at = bodyMoveAnchor(project, { wallId }); + if (at) setDraft({ preview: [], vertices: [], snap: null, hud: { at, text: `OK: ${topZ.toFixed(3)}m` } }); }; const onEdit3dEnd = () => { + bodyDragRef.current = null; + edgeDragRef.current = null; + last3dDragRef.current = null; + setGrip3dEdit(null); setDraft(null); }; @@ -2037,6 +2421,9 @@ export default function App() { onDeleteLineStyle: deleteLineStyle, onImportLineStyles: importLineStyles, onImportHatches: importHatches, + onPatchTextStyle: patchTextStyle, + onAddTextStyle: addTextStyle, + onDeleteTextStyle: deleteTextStyle, onSetOverrideRules: setOverrideRules, onAddPen: addPen, onRenamePen: renamePen, @@ -2048,6 +2435,13 @@ export default function App() { onPatchPenSetColor: patchPenSetColor, onPatchPenSetWeight: patchPenSetWeight, onSeedStandardPenSet: seedStandardPenSet, + onAddCustomPalette: addCustomPalette, + onRenameCustomPalette: renameCustomPalette, + onDeleteCustomPalette: deleteCustomPalette, + onRemoveColorFromCustomPalette: removeColorFromCustomPalette, + onSetCustomPaletteVisible: setCustomPaletteVisible, + onSetBuiltinPaletteVisible: setBuiltinPaletteVisible, + onAddColorToCustomPalette: addColorToCustomPalette, }; // Ressourcen-Manager als eigenes natives Fenster (Tauri) statt Overlay im @@ -2082,11 +2476,14 @@ export default function App() { activeLayoutId !== null ? (project.layouts ?? []).find((l) => l.id === activeLayoutId) : undefined; - const patchOpenLayout = (id: string, fn: (l: Layout) => Layout) => - setProject((p) => ({ - ...p, - layouts: (p.layouts ?? []).map((l) => (l.id === id ? fn(l) : l)), - })); + const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) => + setProject( + (p) => ({ + ...p, + layouts: (p.layouts ?? []).map((l) => (l.id === id ? fn(l) : l)), + }), + coalesceKey, + ); // ── Effektive Darstellung für die Hauptansicht ──────────────────────────── // 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach @@ -2314,7 +2711,7 @@ export default function App() { // Farb-/Mono-Modus) und schreibt ihn massstäblich als Vektor-PDF. Reines // Modell → SVG → PDF, unabhängig vom Bildschirm-DOM. // PDF-/DXF-Plan-Export — siehe state/useExportHandlers.ts. - const { onExportPdf, onExportDxf } = useExportHandlers({ + const { onExportPdf, onExportSvg, onExportDxf } = useExportHandlers({ project, activeLevelId: activeLevel.id, activeLevelName: activeLevel.name, @@ -2323,6 +2720,7 @@ export default function App() { detail, referenceLines, planColorMode, + selectionMembers: selectionLockMembers, setExportOpen, setExportDxfOpen, }); @@ -2391,6 +2789,41 @@ export default function App() { ]; }; + // Feld-Zustand fürs Cursor-HUD (neben der Maus, VW-Stil): läuft ein Punkt- + // ODER Kanten-Griff-Drag, hat er Vorrang (dieselben Felder wie unten in der + // Befehlszeile — Länge/Winkel- bzw. Abstand-Tab-Zyklus), dann eine laufende + // Transformation (m/s/d — Winkel beim Drehen bzw. Distanz beim Bewegen, + // Nutzer-Wunsch „bei Drehen auch eine Darstellung"), sonst die Befehls- + // Engine-Felder beim Zeichnen. Vorher zeigte das Cursor-HUD beim Griff-Ziehen + // GAR KEINE Länge/Winkel-Werte an (nur die Befehlszeile unten) — Nutzer- + // Wunsch: „du kannst [Länge/Winkel] gleich bei der Maus anzeigen wie beim + // Erstellen". Nach `transformFields` platziert (nicht weiter oben), weil es + // deren Deklaration direkt aufruft (keine Ref/Closure-Indirektion nötig). + const activeTransformFields = activeTransform ? transformFields() : []; + const hudFields = + gripEdit + ? { fields: gripEditFields(), typed: cmdTyped } + : edgeEdit + ? { fields: edgeEditFields(), typed: cmdTyped } + : grip3dEdit + ? { + fields: grip3dEditFields(grip3dEdit, last3dDragRef.current?.raw ?? grip3dEdit.anchor), + typed: cmdTyped, + } + : activeTransformFields.length > 0 + ? { fields: activeTransformFields, typed: cmdTyped } + : commandActive && engineView.fields.length > 0 + ? { + fields: engineView.fields.map((f) => ({ + id: f.id, + value: f.value, + locked: f.locked, + active: f.active, + })), + typed: cmdTyped, + } + : null; + // Getippte Zahl in der Transformation: als Wert des aktiven Feldes deuten und // über denselben Pfad wie transformClick committen. const submitTransformValue = (value: number) => { @@ -2553,6 +2986,9 @@ export default function App() { patchLineStyle, addLineStyle, deleteLineStyle, + patchTextStyle, + addTextStyle, + deleteTextStyle, patchWallType, addWallType, deleteWallType, @@ -2584,6 +3020,7 @@ export default function App() { setCeilingThickness, updateStair, updateRoom, + addColorToCustomPalette, }, selectionState: { updateRoof, @@ -2818,6 +3255,7 @@ export default function App() { deleteDrawingCombo, }} textTarget={textTarget} + textStyles={project.textStyles ?? DEFAULT_PRESETS} /> } /> @@ -2891,9 +3329,11 @@ export default function App() { ); return id; }, - onPatchAnnotation: (annotationId, patch) => - patchOpenLayout(activeLayout.id, (l) => - patchAnnotationInLayout(l, annotationId, patch), + onPatchAnnotation: (annotationId, patch, coalesceKey) => + patchOpenLayout( + activeLayout.id, + (l) => patchAnnotationInLayout(l, annotationId, patch), + coalesceKey, ), onRemoveAnnotation: (annotationId) => patchOpenLayout(activeLayout.id, (l) => @@ -2913,7 +3353,9 @@ export default function App() { visibleCodes={visibleCodes} detail={detail} referenceLines={referenceLines} + scaleDenominator={scaleDenominator} hairline={lineMode === "display"} + showGrid={snap.showGrid} marqueeColor={marqueeColor} snapColor={snapColor} hoverDivideDelayMs={snap.hoverDivideDelayMs} @@ -2971,7 +3413,12 @@ export default function App() { onViewportSelectStair={onViewportSelectStair} onViewportContextMenu={onViewportContextMenu} onViewport3dPick={onViewport3dPick} - commandActive={commandActive} + // Zeichnen-Modus des 3D-Viewports gilt AUCH während einer + // interaktiven Transformation (m/s/d) — sonst würde ein Klick im 3D + // während des Drehens/Verschiebens/Spiegelns weiterhin als Orbit/ + // Auswahl interpretiert statt als Transformations-Punkt (s. + // `onWorkplanePoint`-Doc oben). + commandActive={commandActive || !!activeTransform} draft={draft} onWorkplanePoint={onWorkplanePoint} onWorkplaneConfirm={onWorkplaneConfirm} @@ -2995,6 +3442,8 @@ export default function App() { onEdit3dRoofPitch={onEdit3dRoofPitch} onEdit3dWallTop={onEdit3dWallTop} onEdit3dEnd={onEdit3dEnd} + onGrip3dEditTab={cycleGrip3dEditField} + onGrip3dEditCancel={cancelGrip3dEdit} /> {/* Command-Line (Rhino-artig) UNTER dem Viewport — nur Viewport-breit. Prompt + klickbare Inline-Optionen + Texteingabe + Autocomplete. */} @@ -3005,12 +3454,24 @@ export default function App() { // Auswahl-Transformation (Drehen etc.), belegt sie Prompt + U/I/O/P + // Winkel-/Distanzfeld. Sonst gilt die Engine (Zeichnen/Ruhe). Griff-/ // Kanten-Drag haben Vorrang (schließen sich sonst aus). - active={gripEdit ? true : edgeEdit ? true : activeTransform ? true : engineView.active} + active={ + gripEdit + ? true + : edgeEdit + ? true + : grip3dEdit + ? true + : activeTransform + ? true + : engineView.active + } promptKey={ gripEdit ? "cmd.edit.point" : edgeEdit ? "cmd.edit.edge" + : grip3dEdit + ? "cmd.edit.point" : activeTransform ? `transform.hint.${activeTransform.op}.${Math.min( activeTransform.points.length, @@ -3019,13 +3480,19 @@ export default function App() { : engineView.promptKey } options={ - gripEdit || edgeEdit ? [] : activeTransform ? transformOptions() : engineView.options + gripEdit || edgeEdit || grip3dEdit + ? [] + : activeTransform + ? transformOptions() + : engineView.options } fields={ gripEdit ? gripEditFields() : edgeEdit ? edgeEditFields() + : grip3dEdit + ? grip3dEditFields(grip3dEdit, last3dDragRef.current?.raw ?? grip3dEdit.anchor) : activeTransform ? transformFields() : engineView.fields @@ -3047,6 +3514,15 @@ export default function App() { else planViewRef.current?.confirmEdgeEdit(); return; } + if (grip3dEdit) { + const v = parseFloat(text.replace(",", ".")); + if (isFinite(v)) submitGrip3dEditValue(v); + // Leere Eingabe: Feld-Controller schliessen, Maus steuert den + // laufenden Griff-Drag wieder normal weiter (kein 3D-Äquivalent + // zu `confirmGripEdit` — die Maustaste bleibt physisch gedrückt). + else setGrip3dEdit(null); + return; + } if (activeTransform) { const v = parseFloat(text.replace(",", ".")); if (isFinite(v)) submitTransformValue(v); @@ -3069,6 +3545,8 @@ export default function App() { ? cycleGripEditField() : edgeEdit ? cycleEdgeEditField() + : grip3dEdit + ? cycleGrip3dEditField() : activeTransform ? undefined : engine.cycleField() @@ -3078,6 +3556,8 @@ export default function App() { ? closeGripEditField() : edgeEdit ? closeEdgeEditField() + : grip3dEdit + ? setGrip3dEdit(null) : activeTransform ? cancelTransform() : engine.cancel() @@ -3221,14 +3701,16 @@ export default function App() { /> )} - {/* PDF-Export-Dialog (Grundriss → Vektor-PDF). Nur im Grundriss eines - Geschosses sinnvoll; der Button ist sonst deaktiviert. */} + {/* PDF-/SVG-Export-Dialog (Grundriss → Vektor-PDF oder -SVG). Nur im + Grundriss eines Geschosses sinnvoll; der Button ist sonst deaktiviert. */} {exportOpen && ( setExportOpen(false)} /> )} @@ -3237,6 +3719,7 @@ export default function App() { {exportDxfOpen && ( setExportDxfOpen(false)} /> @@ -3259,6 +3742,8 @@ export default function App() { onRendererModeChange={setRendererMode} layout={layout} onApplyLayout={(l) => setLayout(reconcileLayout(l))} + onAliasOverridesChange={setAliasOverrides} + onShortcutOverridesChange={setShortcutOverrides} onClose={() => setSettingsOpen(false)} /> )} @@ -3292,6 +3777,17 @@ export default function App() { /> )} + {pendingDiscard && ( + setPendingDiscard(null)} + onDiscard={() => { + pendingDiscard(); + setPendingDiscard(null); + }} + onSave={onSaveProject} + /> + )} + {pendingCopyMode && ( applyBoolean(differenceDrawings), intersect: () => applyBoolean(intersectionDrawings), drawingSelectionCount: selectedDrawingIds.length, + hasDrawingStyleClipboard: drawingStyleClipboard !== null, + copyDrawingStyle, + pasteDrawingStyle, + lockableSelectionCount: selectionLockIds.length, + selectionAllLocked, + toggleSelectionLock, + selectionAllNoPrint: !!selectionAllNoPrint, + toggleSelectionNoPrint, bringToFront: () => reorderDrawings(selectedDrawingIds, "front"), bringForward: () => reorderDrawings(selectedDrawingIds, "forward"), sendBackward: () => reorderDrawings(selectedDrawingIds, "backward"), sendToBack: () => reorderDrawings(selectedDrawingIds, "back"), + // Stützpunkt-Einträge nur bei GENAU EINER selektierten Polylinie + // (mehrere gleichzeitig hätten keinen eindeutigen Klick-Bezug). + selectedPolyline: (() => { + if (selectedDrawingIds.length !== 1) return null; + const d = project.drawings2d.find((x) => x.id === selectedDrawingIds[0]); + return d && d.geom.shape === "polyline" + ? { id: d.id, pts: d.geom.pts, closed: d.geom.closed } + : null; + })(), + insertPolylinePoint: insertDrawingPoint, + deletePolylinePoint: deleteDrawingPoint, reorderLevel: (id, op) => reorderDrawingLevels([id], op), })} onClose={() => setMenu(null)} @@ -3427,6 +3942,9 @@ export default function App() { penId={cat.colorPenId} pens={project.pens ?? []} activeStyles={activePenSet(project)?.pens} + customPalettes={project.customPalettes} + builtinBanks={project.builtinPaletteBanks} + onSaveColor={addColorToCustomPalette} showWeight onColorChange={(color) => patchCategory(cat.code, { color, colorPenId: undefined })} onPenChange={(colorPenId) => diff --git a/src/commands/cmds/align.ts b/src/commands/cmds/align.ts new file mode 100644 index 0000000..c124e14 --- /dev/null +++ b/src/commands/cmds/align.ts @@ -0,0 +1,78 @@ +// Align / Distribute — richtet die 2D-Auswahl an einer gemeinsamen Kante aus +// bzw. verteilt sie mit gleichen Abständen. Sofort-Befehle ohne Punkt-Eingabe +// (wie Join/Split/Explode): sie wirken auf die bestehende Auswahl, die +// gewünschte Kante/Achse wählt man in der Optionszeile. +// +// Die Modell-Logik liegt in `editors/align.ts`. + +import { alignDrawings, distributeDrawings } from "../../editors/align"; +import type { AlignMode, DistributeAxis } from "../../editors/align"; +import type { + CmdOption, + Command, + CommandResult, + CommandSelection, + CommandState, +} from "../types"; + +function selectedDrawingIds(sel: CommandSelection): string[] { + if (sel.drawingIds && sel.drawingIds.length) return sel.drawingIds; + return sel.drawingId ? [sel.drawingId] : []; +} + +interface AlignState extends CommandState { + phase: "pick"; +} + +const ALIGN_OPTIONS: { id: AlignMode; labelKey: CmdOption["labelKey"] }[] = [ + { id: "left", labelKey: "cmd.align.left" }, + { id: "centerX", labelKey: "cmd.align.centerX" }, + { id: "right", labelKey: "cmd.align.right" }, + { id: "top", labelKey: "cmd.align.top" }, + { id: "centerY", labelKey: "cmd.align.centerY" }, + { id: "bottom", labelKey: "cmd.align.bottom" }, +]; +const DIST_OPTIONS: { id: DistributeAxis; labelKey: CmdOption["labelKey"] }[] = [ + { id: "x", labelKey: "cmd.align.distX" }, + { id: "y", labelKey: "cmd.align.distY" }, +]; + +const done = (): [CommandState, CommandResult] => [ + { phase: "pick", lastPoint: null } as AlignState, + { draft: null, done: true }, +]; + +export const alignCommand: Command = { + name: "align", + labelKey: "cmd.align.label", + prompt: () => "cmd.align.prompt", + accepts: () => ["option"], + options: () => [ + ...ALIGN_OPTIONS.map((o) => ({ id: o.id, labelKey: o.labelKey })), + ...DIST_OPTIONS.map((o) => ({ id: `dist-${o.id}`, labelKey: o.labelKey })), + ], + init: (): AlignState => ({ phase: "pick", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind !== "option") return [state, { draft: null }]; + const ids = selectedDrawingIds(ctx.selection); + if (ids.length === 0) return done(); + + if (input.id.startsWith("dist-")) { + const axis = input.id.slice(5) as DistributeAxis; + return [ + { phase: "pick", lastPoint: null } as AlignState, + { draft: null, done: true, commit: (p) => distributeDrawings(p, ids, axis) }, + ]; + } + const mode = input.id as AlignMode; + return [ + { phase: "pick", lastPoint: null } as AlignState, + { draft: null, done: true, commit: (p) => alignDrawings(p, ids, mode) }, + ]; + }, + + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: (): [CommandState, CommandResult] => done(), + onCancel: (): [CommandState, CommandResult] => done(), +}; diff --git a/src/commands/cmds/arc.test.ts b/src/commands/cmds/arc.test.ts new file mode 100644 index 0000000..c48014d --- /dev/null +++ b/src/commands/cmds/arc.test.ts @@ -0,0 +1,231 @@ +/** + * `arcCommand` — zwei Konstruktionsmethoden: Mittelpunkt+Start+Ende (Default, + * unverändert) und NEU 3-Punkt (Start+Durchgangspunkt+Ende), Nutzer-Wunsch + * „Architekten kennen fast nie den Bogen-Mittelpunkt". + */ + +import { describe, it, expect } from "vitest"; +import { arcCommand } from "./arc"; +import type { CommandContext, CommandState, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const pt = (x: number, y: number) => ({ x, y }); + +describe("arcCommand — Methode Mittelpunkt (Default, unverändert)", () => { + it("Mittelpunkt → Startpunkt (Radius+a0) → Endpunkt (a1) committet den Bogen", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = arcCommand.init(); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); // center + [state] = arcCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); // start (r=1, a0=0) + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(0, 1) }, ctx); // end (a1=90°) + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d).toHaveLength(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("arc"); + if (g.shape === "arc") { + expect(g.center).toEqual({ x: 0, y: 0 }); + expect(g.r).toBeCloseTo(1, 9); + expect(g.a0).toBeCloseTo(0, 9); + expect(g.a1).toBeCloseTo(Math.PI / 2, 9); + } + }); + + it("Default-Methode ist \"center\" ohne Options-Umschalten", () => { + expect(arcCommand.options(arcCommand.init())[0].value).toBe("center"); + }); +}); + +describe("arcCommand — Methode 3-Punkt", () => { + it("Options-Umschalten (\"m\") wechselt von \"center\" auf \"3pt\" (voller Zyklus s. eigener Test unten)", () => { + const p = project(); + const ctx = makeCtx(p); + let state = arcCommand.init(); + expect(arcCommand.options(state)[0].value).toBe("center"); + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); + expect(arcCommand.options(state)[0].value).toBe("3pt"); + }); + + it("Start → Durchgangspunkt → Ende committet einen Bogen durch alle drei Punkte", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = arcCommand.init(); + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 3pt + [state] = arcCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); // Start + [state] = arcCommand.onInput( + state, + { kind: "point", point: pt(Math.SQRT1_2, Math.SQRT1_2) }, // Durchgangspunkt (45°) + ctx, + ); + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(0, 1) }, ctx); // Ende + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d).toHaveLength(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("arc"); + if (g.shape === "arc") { + expect(g.center.x).toBeCloseTo(0, 6); + expect(g.center.y).toBeCloseTo(0, 6); + expect(g.r).toBeCloseTo(1, 6); + expect(g.a0).toBeCloseTo(0, 6); + expect(g.a1).toBeCloseTo(Math.PI / 2, 6); + } + }); + + it("kollinearer Endpunkt-Versuch committet nichts (bleibt in Phase 3, wartet auf einen gültigen Punkt)", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = arcCommand.init(); + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(2, 0) }, ctx); // Durchgangspunkt auf der Geraden + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); // Ende ebenfalls kollinear + expect(result.commit).toBeUndefined(); + expect(result.done).toBeUndefined(); + }); + + it("Methodenwechsel verwirft eine laufende Konstruktion (kein halbfertiger Bogen)", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = arcCommand.init(); + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 3pt + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); // Start gesetzt + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); // weiter → radius + // Nach dem Wechsel muss der Befehl wieder ganz am Anfang der NEUEN Methode + // stehen (kein übernommener Start-Punkt aus der vorherigen Konstruktion). + expect(arcCommand.prompt(state)).toBe("cmd.arc.serStart"); + }); +}); + +/** Wechselt zyklisch auf die Ziel-Methode ("m" so oft wie nötig). */ +function switchTo(state: CommandState, ctx: CommandContext, target: string): CommandState { + let s = state; + while (arcCommand.options(s)[0].value !== target) { + [s] = arcCommand.onInput(s, { kind: "option", id: "method" }, ctx); + } + return s; +} + +describe("arcCommand — Methode Start-Ende-Radius (\"ser\")", () => { + it("Options-Zyklus deckt center→3pt→radius→direction→center ab", () => { + const p = project(); + const ctx = makeCtx(p); + let state = arcCommand.init(); + const seen: string[] = [arcCommand.options(state)[0].value!]; + for (let i = 0; i < 4; i++) { + [state] = arcCommand.onInput(state, { kind: "option", id: "method" }, ctx); + seen.push(arcCommand.options(state)[0].value!); + } + expect(seen).toEqual(["center", "3pt", "radius", "direction", "center"]); + }); + + it("Start → Ende → Radius-Punkt committet den KLEINEREN Bogen zur Cursor-Seite", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = switchTo(arcCommand.init(), ctx, "radius"); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); // Start + [state] = arcCommand.onInput(state, { kind: "point", point: pt(4, 0) }, ctx); // Ende + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(2, 5) }, ctx); // Radius-Punkt oberhalb + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("arc"); + if (g.shape === "arc") { + expect(Math.hypot(0 - g.center.x, 0 - g.center.y)).toBeCloseTo(g.r, 6); + expect(Math.hypot(4 - g.center.x, 0 - g.center.y)).toBeCloseTo(g.r, 6); + expect(g.center.y).toBeLessThan(0); // Zentrum unterhalb → Bogen wölbt sich nach oben + } + }); + + it("getippter Radius nutzt den zuletzt bekannten Cursor als Seiten-Referenz", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = switchTo(arcCommand.init(), ctx, "radius"); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(4, 0) }, ctx); + [state] = arcCommand.onMove(state, pt(2, -5), null, ctx); + const [, result] = arcCommand.onInput(state, { kind: "number", value: 3 }, ctx); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "arc") { + expect(g.r).toBeCloseTo(3, 6); + expect(g.center.y).toBeGreaterThan(0); // Cursor war unterhalb → Zentrum oberhalb + } + }); + + it("Radius kleiner als die halbe Sehnenlänge committet nichts (bleibt aktiv)", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = switchTo(arcCommand.init(), ctx, "radius"); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(4, 0) }, ctx); + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(2, 0.1) }, ctx); // r≈0.1 < 2 + expect(result.commit).toBeUndefined(); + }); +}); + +describe("arcCommand — Methode Start-Ende-Richtung (\"sed\")", () => { + it("Start → Ende → Richtungspunkt committet einen Bogen tangential zur Richtung bei Start", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = switchTo(arcCommand.init(), ctx, "direction"); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); // Start + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 1) }, ctx); // Ende + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(1, 1) }, ctx); // Richtung +y bei Start + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("arc"); + if (g.shape === "arc") { + expect(g.center.x).toBeCloseTo(0, 6); + expect(g.center.y).toBeCloseTo(0, 6); + expect(g.r).toBeCloseTo(1, 6); + } + }); + + it("entartete Richtung (Klick auf den Startpunkt) committet nichts (bleibt aktiv)", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = switchTo(arcCommand.init(), ctx, "direction"); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); + [state] = arcCommand.onInput(state, { kind: "point", point: pt(0, 1) }, ctx); + const [, result] = arcCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); // = Start + expect(result.commit).toBeUndefined(); + }); +}); diff --git a/src/commands/cmds/arc.ts b/src/commands/cmds/arc.ts index 77337b3..1ab8331 100644 --- a/src/commands/cmds/arc.ts +++ b/src/commands/cmds/arc.ts @@ -1,47 +1,163 @@ -// Arc — Mittelpunkt + Startpunkt + Endpunkt. Schritte: -// 1) „Mittelpunkt:" → Punkt -// 2) „Startpunkt:" → Punkt (setzt Radius r = |P1−Center| UND Startwinkel a0) -// 3) „Endpunkt:" → Punkt (setzt Endwinkel a1; Radius bleibt) → commit +// Arc — vier Konstruktionsmethoden (Nutzer-Wunsch: „Architekten kennen fast +// nie den Bogen-Mittelpunkt, sondern zwei Endpunkte + einen Durchgangspunkt/ +// Radius/Richtung"). Wählbar über die Option „Methode" (klickbar im +// Feld-Row, tippbar als „m", zyklisch — dasselbe Muster wie bei `rect.ts`). +// +// • Mittelpunkt (Default, unverändert): Mittelpunkt + Startpunkt + Endpunkt. +// 1) „Mittelpunkt:" → Punkt +// 2) „Startpunkt:" → Punkt (setzt Radius r = |P1−Center| UND Startwinkel a0) +// 3) „Endpunkt:" → Punkt (setzt Endwinkel a1; Radius bleibt) → commit +// • 3-Punkt: Start + Durchgangspunkt + Ende (derselbe Klick-Ablauf wie der +// Bogen-Modus beim Polylinien-Zeichnen, s. `polyline.ts` `pendingThrough`). +// 1) „Startpunkt:" → Punkt +// 2) „Durchgangspunkt:" → Punkt (nur Vorschau-Linie, noch kein Bogen) +// 3) „Endpunkt:" → Punkt → commit (Kreis durch alle drei Punkte, +// s. `geometry/bulge.ts` `arcThroughPoints`) +// • Start-Ende-Radius: Start + Ende + Radius (getippt ODER als Punkt — Abstand +// von der Sehnen-Mitte, wie bei `fillet.ts`s Radius-Schritt). Der Bogen +// wölbt sich zur Seite, auf der der Cursor/Radius-Punkt steht (immer der +// kleinere der beiden möglichen Bögen, s. `arcFromStartEndRadius`). +// 1) „Startpunkt:" → Punkt +// 2) „Endpunkt:" → Punkt +// 3) „Radius:" → Punkt ODER Zahl → commit +// • Start-Ende-Richtung: Start + Ende + Tangentenrichtung bei Start (klassische +// dritte AutoCAD-ARC-Methode). Eindeutig bestimmt (kein Seiten-Wahl nötig), +// s. `arcFromStartEndDirection`. +// 1) „Startpunkt:" → Punkt +// 2) „Endpunkt:" → Punkt +// 3) „Richtung:" → Punkt (Tangentenrichtung bei Start) → commit // // Der Bogen läuft CCW von a0 nach a1 (wie DXF-ARC und das `{shape:"arc"}`- -// Rendering in PlanView). Der Endpunkt wird nur für seinen WINKEL genutzt (auf -// den Kreis mit Radius r projiziert). In generatePlan/PlanView als glatter -// SVG-Bogen (`drawingArc`) gerendert. +// Rendering in PlanView). In generatePlan/PlanView als glatter SVG-Bogen +// (`drawingArc`) gerendert. import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; +import { + arcFromStartEndDirection, + arcFromStartEndRadius, + arcThroughPoints, +} from "../../geometry/bulge"; import type { Command, CommandContext, + CommandField, CommandResult, CommandState, + CmdOption, DraftShape, Project, ToolDraft, Vec2, } from "../types"; +import type { TranslationKey } from "../../i18n"; const EPS = 1e-6; -interface ArcCenter extends CommandState { +/** Konstruktionsmethode. */ +type ArcMethod = "center" | "three" | "ser" | "sed"; +const METHOD_ORDER: ArcMethod[] = ["center", "three", "ser", "sed"]; +const nextMethod = (m: ArcMethod): ArcMethod => + METHOD_ORDER[(METHOD_ORDER.indexOf(m) + 1) % METHOD_ORDER.length]; +const methodValue = (m: ArcMethod): string => + m === "center" ? "center" : m === "three" ? "3pt" : m === "ser" ? "radius" : "direction"; +const RADIUS_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }]; + +/** Umschalt-Option für die Methode (im Feld-Row sichtbar, tippbar als „m"). */ +const methodOption = (m: ArcMethod): CmdOption => ({ + id: "method", + labelKey: "cmd.arc.method", + value: methodValue(m), +}); + +// ── Zustand ────────────────────────────────────────────────────────────────── + +interface ArcCenterPhase1 extends CommandState { phase: "center"; + method: "center"; } -interface ArcStart extends CommandState { +interface ArcCenterPhase2 extends CommandState { phase: "start"; + method: "center"; center: Vec2; cursor: Vec2 | null; } -interface ArcEnd extends CommandState { +interface ArcCenterPhase3 extends CommandState { phase: "end"; + method: "center"; center: Vec2; r: number; a0: number; cursor: Vec2 | null; } -type ArcState = ArcCenter | ArcStart | ArcEnd; +interface ArcThreePhase1 extends CommandState { + phase: "p1"; + method: "three"; +} +interface ArcThreePhase2 extends CommandState { + phase: "p2"; + method: "three"; + a: Vec2; + cursor: Vec2 | null; +} +interface ArcThreePhase3 extends CommandState { + phase: "p3"; + method: "three"; + a: Vec2; + through: Vec2; + cursor: Vec2 | null; +} +interface ArcSerPhase1 extends CommandState { + phase: "p1"; + method: "ser"; +} +interface ArcSerPhase2 extends CommandState { + phase: "p2"; + method: "ser"; + a: Vec2; + cursor: Vec2 | null; +} +interface ArcSerPhase3 extends CommandState { + phase: "radius"; + method: "ser"; + a: Vec2; + b: Vec2; + cursor: Vec2 | null; +} +interface ArcSedPhase1 extends CommandState { + phase: "p1"; + method: "sed"; +} +interface ArcSedPhase2 extends CommandState { + phase: "p2"; + method: "sed"; + a: Vec2; + cursor: Vec2 | null; +} +interface ArcSedPhase3 extends CommandState { + phase: "direction"; + method: "sed"; + a: Vec2; + b: Vec2; + cursor: Vec2 | null; +} +type ArcState = + | ArcCenterPhase1 + | ArcCenterPhase2 + | ArcCenterPhase3 + | ArcSerPhase1 + | ArcSerPhase2 + | ArcSerPhase3 + | ArcSedPhase1 + | ArcSedPhase2 + | ArcSedPhase3 + | ArcThreePhase1 + | ArcThreePhase2 + | ArcThreePhase3; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const angle = (c: Vec2, p: Vec2): number => Math.atan2(p.y - c.y, p.x - c.x); +const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); /** CCW-Spanne von a0 nach a1, normiert auf (0, 2π]. */ function sweepOf(a0: number, a1: number): number { @@ -85,6 +201,11 @@ function arcDraft(center: Vec2, r: number, a0: number, a1: number, at: Vec2 | nu return draft; } +/** Platzhalter-Vorschau (gerade Linie) für Zwischenschritte ohne vollständigen Bogen. */ +function lineDraft(a: Vec2, b: Vec2): ToolDraft { + return { preview: [{ kind: "line", a, b }], vertices: [a] }; +} + function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): Project { if (r < EPS) return p; const d: Drawing2D = { @@ -97,70 +218,216 @@ function appendArc(p: Project, center: Vec2, r: number, a0: number, a1: number, return { ...p, drawings2d: [...p.drawings2d, d] }; } -const idle = (): [CommandState, CommandResult] => [ - { phase: "center", lastPoint: null }, +const idle = (method: ArcMethod): [CommandState, CommandResult] => [ + (method === "center" ? { phase: "center", method } : { phase: "p1", method }) as ArcState, { draft: null, done: true }, ]; +function promptKey(s: ArcState): TranslationKey { + if (s.method === "center") { + return s.phase === "start" ? "cmd.arc.start" : s.phase === "end" ? "cmd.arc.end" : "cmd.arc.center"; + } + if (s.method === "ser") { + return s.phase === "p2" ? "cmd.arc.serEnd" : s.phase === "radius" ? "cmd.arc.radius" : "cmd.arc.serStart"; + } + if (s.method === "sed") { + return s.phase === "p2" ? "cmd.arc.sedEnd" : s.phase === "direction" ? "cmd.arc.direction" : "cmd.arc.sedStart"; + } + return s.phase === "p2" ? "cmd.arc.through" : s.phase === "p3" ? "cmd.arc.threeEnd" : "cmd.arc.threeStart"; +} + export const arcCommand: Command = { name: "arc", labelKey: "cmd.arc.label", - prompt: (s) => { - const phase = (s as ArcState).phase; - return phase === "start" ? "cmd.arc.start" : phase === "end" ? "cmd.arc.end" : "cmd.arc.center"; + prompt: (s) => promptKey(s as ArcState), + accepts: (s) => { + const st = s as ArcState; + return st.method === "ser" && st.phase === "radius" ? ["point", "option", "number"] : ["point", "option"]; }, - accepts: () => ["point"], - options: () => [], - init: (): ArcCenter => ({ phase: "center", lastPoint: null }), + options: (s) => [methodOption((s as ArcState).method)], + fields: (s) => { + const st = s as ArcState; + return st.method === "ser" && st.phase === "radius" ? RADIUS_FIELDS : []; + }, + init: (): ArcCenterPhase1 => ({ phase: "center", method: "center", lastPoint: null }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as ArcState; + + if (input.kind === "option") { + if (input.id === "method") { + // Methode zyklisch umschalten; laufende Konstruktion verwerfen und den + // Befehl AKTIV lassen (kein done) — nur zum ersten Schritt zurück. + const m = nextMethod(s.method); + const [ns] = idle(m); + return [ns, { draft: null }]; + } + return [s, { draft: null }]; + } + // Getippter Radius (Methode „ser", Schritt „radius"): Seite kommt vom + // zuletzt bekannten Cursor (wie beim Tab-Feld-Controller sonst auch). + if (input.kind === "number" && s.method === "ser" && s.phase === "radius") { + const near = s.cursor ?? { x: s.b.x, y: s.b.y }; + const arc = arcFromStartEndRadius(s.a, s.b, input.value, near); + if (!arc) return [s, { draft: null }]; + return [ + idle("ser")[0], + { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + ]; + } if (input.kind !== "point") return [s, { draft: null }]; const pt = input.point; - if (s.phase === "center") { - const ns: ArcStart = { phase: "start", center: pt, cursor: pt, lastPoint: pt }; + + if (s.method === "center") { + if (s.phase === "center") { + const ns: ArcCenterPhase2 = { phase: "start", method: "center", center: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + if (s.phase === "start") { + const r = dist(s.center, pt); + if (r < EPS) return [s, { draft: null }]; + const a0 = angle(s.center, pt); + const ns: ArcCenterPhase3 = { phase: "end", method: "center", center: s.center, r, a0, cursor: pt, lastPoint: pt }; + return [ns, { draft: arcDraft(s.center, r, a0, a0, pt) }]; + } + // Endpunkt: Endwinkel setzen, Bogen committen. + const a1 = angle(s.center, pt); + const { center, r, a0 } = s; + return [ + idle("center")[0], + { draft: null, done: true, commit: (p) => appendArc(p, center, r, a0, a1, ctx) }, + ]; + } + + // Methode „three". + if (s.method === "three") { + if (s.phase === "p1") { + const ns: ArcThreePhase2 = { phase: "p2", method: "three", a: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + if (s.phase === "p2") { + if (dist(s.a, pt) < EPS) return [s, { draft: null }]; + const ns: ArcThreePhase3 = { phase: "p3", method: "three", a: s.a, through: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: lineDraft(s.a, pt) }]; + } + // phase "p3": Endpunkt → Kreis durch alle drei Punkte, committen. + const arc = arcThroughPoints(s.a, s.through, pt); + if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten + return [ + idle("three")[0], + { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + ]; + } + + // Methode „ser" (Start-Ende-Radius). + if (s.method === "ser") { + if (s.phase === "p1") { + const ns: ArcSerPhase2 = { phase: "p2", method: "ser", a: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + if (s.phase === "p2") { + if (dist(s.a, pt) < EPS) return [s, { draft: null }]; + const ns: ArcSerPhase3 = { phase: "radius", method: "ser", a: s.a, b: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: lineDraft(s.a, pt) }]; + } + // phase "radius": Radius-Punkt → committen (Seite = dieser Punkt). + const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), pt), pt); + if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten + return [ + idle("ser")[0], + { draft: null, done: true, commit: (p) => appendArc(p, arc.center, arc.r, arc.a0, arc.a1, ctx) }, + ]; + } + + // Methode „sed" (Start-Ende-Richtung). + if (s.phase === "p1") { + const ns: ArcSedPhase2 = { phase: "p2", method: "sed", a: pt, cursor: pt, lastPoint: pt }; return [ns, { draft: { preview: [], vertices: [pt] } }]; } - if (s.phase === "start") { - const r = dist(s.center, pt); - if (r < EPS) return [s, { draft: null }]; - const a0 = angle(s.center, pt); - const ns: ArcEnd = { phase: "end", center: s.center, r, a0, cursor: pt, lastPoint: pt }; - return [ns, { draft: arcDraft(s.center, r, a0, a0, pt) }]; + if (s.phase === "p2") { + if (dist(s.a, pt) < EPS) return [s, { draft: null }]; + const ns: ArcSedPhase3 = { phase: "direction", method: "sed", a: s.a, b: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: lineDraft(s.a, pt) }]; } - // Endpunkt: Endwinkel setzen, Bogen committen. - const a1 = angle(s.center, pt); - const { center, r, a0 } = s; + // phase "direction": Richtungspunkt → committen. + const sedArc = arcFromStartEndDirection(s.a, s.b, pt); + if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten return [ - { phase: "center", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendArc(p, center, r, a0, a1, ctx) }, + idle("sed")[0], + { draft: null, done: true, commit: (p) => appendArc(p, sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx) }, ]; }, onMove: (state, point): [CommandState, CommandResult] => { const s = state as ArcState; - if (s.phase === "start") { - const r = dist(s.center, point); - const ns: ArcStart = { ...s, cursor: point }; - return [ - ns, - { - draft: { - preview: [{ kind: "poly", pts: circlePts(s.center, r), closed: true }], - vertices: [s.center], - hud: { at: point, text: `R: ${r.toFixed(3)}m` }, + if (s.method === "center") { + if (s.phase === "start") { + const r = dist(s.center, point); + const ns: ArcCenterPhase2 = { ...s, cursor: point }; + return [ + ns, + { + draft: { + preview: [{ kind: "poly", pts: circlePts(s.center, r), closed: true }], + vertices: [s.center], + hud: { at: point, text: `R: ${r.toFixed(3)}m` }, + }, }, - }, - ]; + ]; + } + if (s.phase === "end") { + const a1 = angle(s.center, point); + const ns: ArcCenterPhase3 = { ...s, cursor: point }; + return [ns, { draft: arcDraft(s.center, s.r, s.a0, a1, point) }]; + } + return [s, { draft: null }]; } - if (s.phase === "end") { - const a1 = angle(s.center, point); - const ns: ArcEnd = { ...s, cursor: point }; - return [ns, { draft: arcDraft(s.center, s.r, s.a0, a1, point) }]; + if (s.phase === "p2") { + // Erster Punkt gesetzt, zweiter folgt dem Cursor — identisch für alle + // drei Zwei-Endpunkt-Methoden (three/ser/sed). + const ns = { ...s, cursor: point } as ArcState; + return [ns, { draft: lineDraft(s.a, point) }]; + } + if (s.phase === "p3") { + const ns: ArcThreePhase3 = { ...s, cursor: point }; + const arc = arcThroughPoints(s.a, s.through, point); + return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, point) }]; + } + if (s.phase === "radius") { + const ns: ArcSerPhase3 = { ...s, cursor: point }; + const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), point), point); + return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }]; + } + if (s.phase === "direction") { + const ns: ArcSedPhase3 = { ...s, cursor: point }; + const arc = arcFromStartEndDirection(s.a, s.b, point); + return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }]; } return [s, { draft: null }]; }, - onConfirm: (): [CommandState, CommandResult] => idle(), - onCancel: (): [CommandState, CommandResult] => idle(), + onConfirm: (state): [CommandState, CommandResult] => idle((state as ArcState).method), + onCancel: (state): [CommandState, CommandResult] => idle((state as ArcState).method), + + // Tab-Feld-Zyklus nur im „radius"-Schritt der „ser"-Methode (ein + // Radius-Feld), analog `fillet.ts`: der gelockte Wert bestimmt den Punkt + // auf dem Strahl Sehnenmitte→Cursor (bzw. →+X ohne Cursor). + fieldValues: (state, _locks, cursor): Record => { + const s = state as ArcState; + if (s.method !== "ser" || s.phase !== "radius" || !cursor) return {}; + return { radius: dist(mid(s.a, s.b), cursor) }; + }, + pointFromFields: (state, locks, cursor) => { + const s = state as ArcState; + if (s.method !== "ser" || s.phase !== "radius") return null; + const m = mid(s.a, s.b); + const r = "radius" in locks ? Math.max(0, locks.radius) : cursor ? dist(m, cursor) : 0; + if (cursor) { + const d = dist(m, cursor); + if (d > EPS) { + return { x: m.x + ((cursor.x - m.x) / d) * r, y: m.y + ((cursor.y - m.y) / d) * r }; + } + } + return { x: m.x + r, y: m.y }; + }, }; diff --git a/src/commands/cmds/array.test.ts b/src/commands/cmds/array.test.ts index 4a19ad4..8412932 100644 --- a/src/commands/cmds/array.test.ts +++ b/src/commands/cmds/array.test.ts @@ -95,3 +95,94 @@ describe("arrayCommand", () => { expect(result.commit).toBeUndefined(); }); }); + +// ── Polar-Array (Nutzer-Wunsch: „Array kennt nur linear, kein Polar-Modus") ── + +const offCenter: Drawing2D = { + id: "src2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "circle", center: { x: 2, y: 0 }, r: 0.5 }, +}; + +/** Zyklt die "kind"-Option, bis der gewünschte Wert erreicht ist (höchstens 2 Versuche nötig). */ +function setKind(state: ReturnType, ctx: CommandContext, target: "lin" | "polar") { + let s = state; + for (let i = 0; i < 2; i++) { + if (arrayCommand.options(s)[0].value === target) return s; + [s] = arrayCommand.onInput(s, { kind: "option", id: "kind" }, ctx); + } + return s; +} + +/** Zyklt die "count"-Option, bis der gewünschte Wert erreicht ist. */ +function setCount(state: ReturnType, ctx: CommandContext, target: number) { + let s = state; + for (let i = 0; i < 12; i++) { + const opts = arrayCommand.options(s); + if (opts[opts.length - 1].value === String(target)) return s; + [s] = arrayCommand.onInput(s, { kind: "option", id: "count" }, ctx); + } + return s; +} + +describe("arrayCommand — Polar-Modus", () => { + it("\"kind\"-Option zyklt linear → polar → linear", () => { + const state0 = arrayCommand.init(); + expect(arrayCommand.options(state0)[0].value).toBe("lin"); + const p = project(); + const ctx = makeCtx(p, null); + const [s1] = arrayCommand.onInput(state0, { kind: "option", id: "kind" }, ctx); + expect(arrayCommand.options(s1)[0].value).toBe("polar"); + const [s2] = arrayCommand.onInput(s1, { kind: "option", id: "kind" }, ctx); + expect(arrayCommand.options(s2)[0].value).toBe("lin"); + }); + + it("Zentrum + getippter Winkel (Zahl) verteilt 3 Kopien gleichmässig um das Zentrum", () => { + const p = project([offCenter]); + const ctx = makeCtx(p, "src2"); + let state = setKind(arrayCommand.init(), ctx, "polar"); + [state] = arrayCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Zentrum + state = setCount(state, ctx, 3); + const [, result] = arrayCommand.onInput(state, { kind: "number", value: 90 }, ctx); // 90° je Kopie + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d).toHaveLength(4); // Original + 3 Kopien + const centers = next.drawings2d + .map((d) => d.geom) + .filter((g) => g.shape === "circle") + .map((g) => (g as { center: { x: number; y: number } }).center); + const has = (x: number, y: number) => + centers.some((c) => Math.abs(c.x - x) < 1e-6 && Math.abs(c.y - y) < 1e-6); + expect(has(2, 0)).toBe(true); // Original unverändert + expect(has(0, 2)).toBe(true); // 90° + expect(has(-2, 0)).toBe(true); // 180° + expect(has(0, -2)).toBe(true); // 270° + }); + + it("Zentrum + Klick auf einen Punkt (statt getippter Zahl) bestimmt den Winkel je Kopie ebenso", () => { + const p = project([offCenter]); + const ctx = makeCtx(p, "src2"); + let state = setKind(arrayCommand.init(), ctx, "polar"); + [state] = arrayCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + state = setCount(state, ctx, 3); + // Klick bei (0,5) liegt exakt bei 90° relativ zum Zentrum. + const [, result] = arrayCommand.onInput(state, { kind: "point", point: { x: 0, y: 5 } }, ctx); + const next = result.commit!(p); + const centers = next.drawings2d + .map((d) => d.geom) + .filter((g) => g.shape === "circle") + .map((g) => (g as { center: { x: number; y: number } }).center); + expect(centers.some((c) => Math.abs(c.x - 0) < 1e-6 && Math.abs(c.y - 2) < 1e-6)).toBe(true); + }); + + it("leere Auswahl committet nichts (polar)", () => { + const p = project(); + const ctx = makeCtx(p, null); + let state = setKind(arrayCommand.init(), ctx, "polar"); + [state] = arrayCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = arrayCommand.onInput(state, { kind: "number", value: 90 }, ctx); + expect(result.commit).toBeUndefined(); + }); +}); diff --git a/src/commands/cmds/array.ts b/src/commands/cmds/array.ts index c3a8aa9..e112cba 100644 --- a/src/commands/cmds/array.ts +++ b/src/commands/cmds/array.ts @@ -1,17 +1,33 @@ -// Array (Feld) — dupliziert die AKTUELLE Auswahl `count`-mal entlang eines -// Vektors, in EINER Geste (baut auf dem bestehenden Transform-Modus -// `"array"` auf, der bisher nie über einen Befehl erreichbar war — s. -// `tools/transform.ts::copyTs`). Schritte: -// 1) „Basispunkt:" → Punkt -// 2) „Zielpunkt ( Anzahl ):" → Punkt/Zahl (Tab length/angle) → committet -// ALLE `count` Kopien auf einmal (Original bleibt). „Anzahl" (Option, -// persistent über Aufrufe wie bei Multiline) zyklt 2..12. +// Array (Feld) — dupliziert die AKTUELLE Auswahl `count`-mal, in EINER Geste +// (baut auf dem bestehenden Transform-Modus `"array"` auf, der bisher nie +// über einen Befehl erreichbar war — s. `tools/transform.ts::copyTs`). Zwei +// Konstruktionsarten, wählbar über die Option „Art" (klickbar im Feld-Row, +// tippbar als „t" — Buchstabe „a" ist bereits Angebot für den Winkel- +// Tab-Feld-Zyklus belegt, zyklisch wie bei `rect.ts`/`arc.ts`): +// +// • Linear (Default, unverändert): Basispunkt → Zielpunkt (Vektor + Länge), +// `count` Kopien in gleichem Abstand entlang dieses Vektors. +// 1) „Basispunkt:" → Punkt +// 2) „Zielpunkt ( Anzahl ):" → Punkt/Zahl (Tab length/angle) → commit +// • Polar (Nutzer-Wunsch: „Array kennt nur linear, kein Polar-/Pfad- +// Modus"): Zentrum → Winkel PRO Kopie (Punkt-Richtung relativ zum +// Zentrum ODER getippter Winkel), `count` Kopien gleichmässig um das +// Zentrum verteilt (op:"rotate" statt op:"move" im selben `mode:"array"` +// — braucht KEINE Änderung an `tools/transform.ts`, dessen `transformFn`/ +// `copyTs` das für op:"rotate" bereits als „Kopie k um k·Winkel drehen" +// abbilden, exakt der Polar-Array-Mechanismus). +// 1) „Zentrum:" → Punkt +// 2) „Winkel je Kopie ( Anzahl ):" → Punkt/Zahl (Tab angle) → commit // // Die Auswahl kommt vorab über ctx.selection (erst selektieren, dann Befehl, // wie move/copy). Leere Auswahl → No-op. -import { commitTransform, transformPreview } from "../../tools/transform"; -import type { TransformSelection } from "../../tools/transform"; +import { + commitTransform, + hasTransformSelection, + toTransformSel, + transformPreview, +} from "../../tools/transform"; import type { CmdOption, Command, @@ -23,6 +39,7 @@ import type { ToolDraft, Vec2, } from "../types"; +import type { TranslationKey } from "../../i18n"; const DEG = Math.PI / 180; const MIN_COUNT = 2; @@ -31,14 +48,26 @@ const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; -/** Persistente Anzahl über Aufrufe hinweg (wie `lastCount` bei Multiline). */ +/** Konstruktionsart. */ +type ArrayKind = "linear" | "polar"; +const KIND_ORDER: ArrayKind[] = ["linear", "polar"]; +const nextKind = (k: ArrayKind): ArrayKind => KIND_ORDER[(KIND_ORDER.indexOf(k) + 1) % KIND_ORDER.length]; + +/** Persistente Anzahl/Art über Aufrufe hinweg (wie `lastCount` bei Multiline). */ let lastCount = 3; +let lastKind: ArrayKind = "linear"; const ARRAY_FIELDS: CommandField[] = [ { id: "length", labelKey: "cmd.field.length" }, { id: "angle", labelKey: "cmd.field.angle" }, ]; +const POLAR_FIELDS: CommandField[] = [{ id: "angle", labelKey: "cmd.field.angle" }]; const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.array.count" }; +const KIND_OPTION = (k: ArrayKind): CmdOption => ({ + id: "kind", + labelKey: "cmd.array.kind", + value: k === "linear" ? "lin" : "polar", +}); function targetFromFields(base: Vec2, locks: Record, cursor: Vec2 | null): Vec2 { const ref = cursor ?? base; @@ -48,71 +77,106 @@ function targetFromFields(base: Vec2, locks: Record, cursor: Vec return { x: base.x + Math.cos(ang) * length, y: base.y + Math.sin(ang) * length }; } -function hasSelection(sel: CommandSelection): boolean { - return ( - sel.wallIds.length > 0 || - sel.drawingId !== null || - (sel.drawingIds?.length ?? 0) > 0 || - !!sel.extrudedSolidId || - !!sel.columnId - ); -} -function toTransformSel(sel: CommandSelection): TransformSelection { - return { - wallIds: sel.wallIds, - drawingId: sel.drawingId, - drawingIds: sel.drawingIds, - extrudedSolidId: sel.extrudedSolidId, - columnId: sel.columnId, - }; +/** + * Referenz-/Zielpunkte für `transformFn("rotate", …)` aus Zentrum + Winkel + * PRO KOPIE (Grad): Referenz = synthetische +X-Achse (dieselbe Konvention wie + * `rotate.ts` `rotatePts` bei getipptem Winkel), Ziel = Zentrum + dieser + * Winkel — `copyTs`/`transformFn` drehen Kopie k dann um k·Winkel. + */ +function polarPts(center: Vec2, degPerCopy: number): Vec2[] { + const a = degPerCopy * DEG; + return [ + center, + { x: center.x + 1, y: center.y }, + { x: center.x + Math.cos(a), y: center.y + Math.sin(a) }, + ]; } interface ArrBase extends CommandState { phase: "base"; + kind: ArrayKind; } interface ArrTarget extends CommandState { phase: "target"; + kind: ArrayKind; sel: CommandSelection; base: Vec2; cursor: Vec2 | null; } type ArrState = ArrBase | ArrTarget; -/** Vorschau ALLER `lastCount` Kopien bei der aktuellen Cursor-Lage. */ -function arrayDraft(project: Project, sel: CommandSelection, base: Vec2, target: Vec2): ToolDraft { +/** Vorschau ALLER `lastCount` Kopien bei der aktuellen Cursor-Lage (linear). */ +function linearDraft(project: Project, sel: CommandSelection, base: Vec2, target: Vec2): ToolDraft { const preview = transformPreview(project, toTransformSel(sel), "move", [base, target], "array", lastCount); return { preview, vertices: [base], - hud: { - at: target, - text: `${segLen(base, target).toFixed(2)} m × ${lastCount}`, - }, + hud: { at: target, text: `${segLen(base, target).toFixed(2)} m × ${lastCount}` }, }; } -const idle = (): [CommandState, CommandResult] => [ - { phase: "base", lastPoint: null } as ArrBase, +/** Vorschau ALLER `lastCount` Kopien bei der aktuellen Cursor-Lage (polar). */ +function polarDraft(project: Project, sel: CommandSelection, center: Vec2, cursor: Vec2): ToolDraft { + const degPerCopy = segAngleDeg(center, cursor); + const pts = polarPts(center, degPerCopy); + const preview = transformPreview(project, toTransformSel(sel), "rotate", pts, "array", lastCount); + const total = Math.abs(degPerCopy * (lastCount - 1)); + return { + preview, + vertices: [center], + hud: { at: cursor, text: `${degPerCopy.toFixed(1)}° × ${lastCount} (${total.toFixed(1)}° total)` }, + }; +} + +const idle = (kind: ArrayKind): [CommandState, CommandResult] => [ + { phase: "base", lastPoint: null, kind } as ArrBase, { draft: null, done: true }, ]; +function promptKey(s: ArrState): TranslationKey { + if (s.phase !== "target") return s.kind === "polar" ? "cmd.array.center" : "cmd.array.base"; + return s.kind === "polar" ? "cmd.array.polarAngle" : "cmd.array.target"; +} + export const arrayCommand: Command = { name: "array", labelKey: "cmd.array.label", - prompt: (s) => ((s as ArrState).phase === "target" ? "cmd.array.target" : "cmd.array.base"), - accepts: (s) => ((s as ArrState).phase === "target" ? ["point", "number", "option"] : ["point"]), - options: (s) => - (s as ArrState).phase === "target" ? [{ ...COUNT_OPTION, value: String(lastCount) }] : [], - init: (): ArrBase => ({ phase: "base", lastPoint: null }), + prompt: (s) => promptKey(s as ArrState), + accepts: (s) => ((s as ArrState).phase === "target" ? ["point", "number", "option"] : ["point", "option"]), + options: (s) => { + const st = s as ArrState; + const base = [KIND_OPTION(st.kind)]; + return st.phase === "target" ? [...base, { ...COUNT_OPTION, value: String(lastCount) }] : base; + }, + init: (): ArrBase => ({ phase: "base", lastPoint: null, kind: lastKind }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as ArrState; - if (!hasSelection(ctx.selection)) return idle(); + + if (input.kind === "option") { + if (input.id === "kind") { + lastKind = nextKind(s.kind); + return idle(lastKind); + } + if (input.id === "count" && s.phase === "target") { + lastCount = lastCount >= MAX_COUNT ? MIN_COUNT : lastCount + 1; + const draft = s.cursor + ? s.kind === "polar" + ? polarDraft(ctx.project, s.sel, s.base, s.cursor) + : linearDraft(ctx.project, s.sel, s.base, s.cursor) + : null; + return [s, { draft }]; + } + return [s, { draft: null }]; + } + + if (!hasTransformSelection(ctx.selection)) return idle(s.kind); if (s.phase !== "target") { if (input.kind !== "point") return [s, { draft: null }]; const next: ArrTarget = { phase: "target", + kind: s.kind, sel: ctx.selection, base: input.point, cursor: input.point, @@ -121,23 +185,22 @@ export const arrayCommand: Command = { return [next, { draft: { preview: [], vertices: [input.point] } }]; } - if (input.kind === "option") { - if (input.id === "count") { - lastCount = lastCount >= MAX_COUNT ? MIN_COUNT : lastCount + 1; - return [s, { draft: s.cursor ? arrayDraft(ctx.project, s.sel, s.base, s.cursor) : null }]; - } - return [s, { draft: null }]; - } - let target: Vec2 | null = null; if (input.kind === "point") target = input.point; - else if (input.kind === "number") target = { x: s.base.x + input.value, y: s.base.y }; - if (!target || segLen(s.base, target) < 1e-6) return idle(); + else if (input.kind === "number") { + target = + s.kind === "polar" + ? { x: s.base.x + Math.cos(input.value * DEG), y: s.base.y + Math.sin(input.value * DEG) } + : { x: s.base.x + input.value, y: s.base.y }; + } + if (!target || segLen(s.base, target) < 1e-6) return idle(s.kind); - const { base, sel } = s; + const { base, sel, kind } = s; + const op = kind === "polar" ? "rotate" : "move"; + const pts = kind === "polar" ? polarPts(base, segAngleDeg(base, target)) : [base, target]; return [ - idle()[0], - { draft: null, done: true, commit: (p) => commitTransform(p, toTransformSel(sel), "move", [base, target!], "array", lastCount) }, + idle(kind)[0], + { draft: null, done: true, commit: (p) => commitTransform(p, toTransformSel(sel), op, pts, "array", lastCount) }, ]; }, @@ -145,21 +208,33 @@ export const arrayCommand: Command = { const s = state as ArrState; if (s.phase !== "target") return [s, { draft: null }]; const ns: ArrTarget = { ...s, cursor: point }; - return [ns, { draft: arrayDraft(ctx.project, s.sel, s.base, point) }]; + return [ns, { draft: s.kind === "polar" ? polarDraft(ctx.project, s.sel, s.base, point) : linearDraft(ctx.project, s.sel, s.base, point) }]; }, - onConfirm: (): [CommandState, CommandResult] => idle(), - onCancel: (): [CommandState, CommandResult] => idle(), + onConfirm: (state): [CommandState, CommandResult] => idle((state as ArrState).kind), + onCancel: (state): [CommandState, CommandResult] => idle((state as ArrState).kind), - fields: (state) => ((state as ArrState).phase === "target" ? ARRAY_FIELDS : []), + fields: (state) => { + const s = state as ArrState; + if (s.phase !== "target") return []; + return s.kind === "polar" ? POLAR_FIELDS : ARRAY_FIELDS; + }, pointFromFields: (state, locks, cursor) => { const s = state as ArrState; if (s.phase !== "target") return null; + if (s.kind === "polar") { + const deg = "angle" in locks ? locks.angle : cursor ? segAngleDeg(s.base, cursor) : 0; + const a = deg * DEG; + return { x: s.base.x + Math.cos(a), y: s.base.y + Math.sin(a) }; + } return targetFromFields(s.base, locks, cursor); }, fieldValues: (state, _locks, cursor): Record => { const s = state as ArrState; if (s.phase !== "target" || !cursor) return {}; + if (s.kind === "polar") { + return { angle: ((segAngleDeg(s.base, cursor) % 360) + 360) % 360 }; + } return { length: segLen(s.base, cursor), angle: ((segAngleDeg(s.base, cursor) % 360) + 360) % 360, diff --git a/src/commands/cmds/block.test.ts b/src/commands/cmds/block.test.ts index 0dc8117..7d60a71 100644 --- a/src/commands/cmds/block.test.ts +++ b/src/commands/cmds/block.test.ts @@ -1,6 +1,10 @@ /** - * `blockCommand` — Einfügepunkt → neue `{shape:"block"}`-Instanz, die auf - * die aktuell per Option gewählte `BlockDef` zeigt. Ohne Definitionen: No-Op. + * `blockCommand` — Einfügepunkt → Drehwinkel+Grösse (EIN Punkt bestimmt + * beide: Winkel UND Abstand-als-Skalierungsfaktor) → neue `{shape:"block"}`- + * Instanz, die auf die aktuell per Option gewählte `BlockDef` zeigt. Ohne + * Definitionen: No-Op. Nutzer-Wunsch: „Block-Einfügung ohne Rotation/ + * Skalierung" — v1 setzte `rotation` immer fest auf 0 und kannte gar kein + * `scale`-Feld. */ import { describe, it, expect } from "vitest"; @@ -57,7 +61,7 @@ describe("blockCommand", () => { expect(result.done).toBe(true); }); - it("mit einer Definition: Klick platziert eine Instanz an der Klickposition, rotation 0", () => { + it("mit einer Definition: erster Klick setzt NUR den Einfügepunkt (noch kein Commit)", () => { const def: BlockDef = { id: "blk1", name: "Stuhl", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }; const p = project([def]); const ctx = makeCtx(p); @@ -66,6 +70,16 @@ describe("blockCommand", () => { { kind: "point", point: { x: 3, y: 4 } }, ctx, ); + expect(result.commit).toBeUndefined(); + expect(result.done).toBeUndefined(); + }); + + it("Klick auf denselben Punkt im Dreh-Schritt committet mit rotation 0 (Rückwärtskompatibilität)", () => { + const def: BlockDef = { id: "blk1", name: "Stuhl", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }; + const p = project([def]); + const ctx = makeCtx(p); + let [state] = blockCommand.onInput(blockCommand.init(), { kind: "point", point: { x: 3, y: 4 } }, ctx); + const [, result] = blockCommand.onInput(state, { kind: "point", point: { x: 3, y: 4 } }, ctx); expect(result.commit).toBeDefined(); const next = result.commit!(p); expect(next.drawings2d.length).toBe(1); @@ -75,6 +89,35 @@ describe("blockCommand", () => { expect(g.blockDefId).toBe("blk1"); expect(g.at).toEqual({ x: 3, y: 4 }); expect(g.rotation).toBe(0); + expect(g.scale).toBe(1); } }); + + it("zweiter Klick in eine Richtung setzt rotation auf den Winkel UND scale auf den Abstand", () => { + const def: BlockDef = { id: "blk1", name: "Stuhl", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }; + const p = project([def]); + const ctx = makeCtx(p); + let [state] = blockCommand.onInput(blockCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + // Richtung (0,1) relativ zum Einfügepunkt → 90°, Abstand 5 → scale 5. + const [, result] = blockCommand.onInput(state, { kind: "point", point: { x: 0, y: 5 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "block") { + expect(g.rotation).toBeCloseTo(Math.PI / 2, 9); + expect(g.scale).toBeCloseTo(5, 9); + } + }); + + it("Symbol-Option bleibt über den Dreh-Schritt hinweg erhalten (nicht auf das erste Symbol zurückgesetzt)", () => { + const defA: BlockDef = { id: "blk-a", name: "A", geom2d: [] }; + const defB: BlockDef = { id: "blk-b", name: "B", geom2d: [] }; + const p = project([defA, defB]); + const ctx = makeCtx(p); + let [state] = blockCommand.onInput(blockCommand.init(), { kind: "option", id: "def" }, ctx); // → B + [state] = blockCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Einfügepunkt + const [, result] = blockCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // 0° + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "block") expect(g.blockDefId).toBe("blk-b"); + }); }); diff --git a/src/commands/cmds/block.ts b/src/commands/cmds/block.ts index 22bd997..4b5e2da 100644 --- a/src/commands/cmds/block.ts +++ b/src/commands/cmds/block.ts @@ -1,12 +1,21 @@ // Block einfügen — platziert eine Instanz einer vorhandenen Block-Definition // (`Project.blockDefs`, s. `defblock`). Welche Definition aktiv ist, zyklt // über eine Inline-Option (persistent über Aufrufe, wie `count` bei -// Multiline); Rotation läuft NICHT über dieses Werkzeug, sondern über den -// bestehenden `rotate`-Transform (v1 bewusst nur Position). Schritte: -// 1) „Einfügepunkt:" → Punkt → commit. Ohne definierte Blöcke: No-Op. +// Multiline). Schritte: +// 1) „Einfügepunkt:" → Punkt +// 2) „Drehwinkel/Grösse:" → Punkt (Richtung + Abstand vom Einfügepunkt; +// Klick auf denselben Punkt = 0°/Grösse 1) → commit. Ohne definierte +// Blöcke: No-Op. +// +// EIN Punkt bestimmt beide Werte gleichzeitig (Winkel UND Abstand) — dieselbe +// Zieh-Geste, die die Live-Vorschau ohnehin schon als HUD anzeigt (L/W-Box, +// s. `segmentHud`): `L` (Länge) war bisher rein kosmetisch (nur `W`/Winkel +// wirkte), jetzt wird sie zum Skalierungsfaktor (Abstand in Metern = Faktor, +// wie bei `circle.ts`s Radius-Punkt). Kein separater dritter Klick-Schritt +// nötig — Nutzer-Wunsch „Skalierung beim Einfügen" bei minimaler UX-Änderung. import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; +import { segmentHud, uniqueId } from "../../tools/types"; import type { CmdOption, Command, @@ -17,13 +26,23 @@ import type { Vec2, } from "../types"; +const EPS = 1e-6; + let lastDefIndex = 0; -interface BlockState extends CommandState { +interface BlockPoint extends CommandState { phase: "point"; defIds: string[]; defNames: string[]; } +interface BlockRotate extends CommandState { + phase: "rotate"; + defIds: string[]; + defNames: string[]; + at: Vec2; + cursor: Vec2 | null; +} +type BlockState = BlockPoint | BlockRotate; const DEF_OPTION: CmdOption = { id: "def", labelKey: "cmd.block.def" }; @@ -32,54 +51,88 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } { return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) }; } -function appendInstance(p: Project, blockDefId: string, at: Vec2, ctx: CommandContext): Project { +function appendInstance( + p: Project, + blockDefId: string, + at: Vec2, + rotation: number, + scale: number, + ctx: CommandContext, +): Project { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "block", blockDefId, at, rotation: 0 }, + geom: { shape: "block", blockDefId, at, rotation, scale }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } +/** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */ +function rotationAndScaleFrom(at: Vec2, pt: Vec2): { rotation: number; scale: number } { + const d = Math.hypot(pt.x - at.x, pt.y - at.y); + if (d < EPS) return { rotation: 0, scale: 1 }; + return { rotation: Math.atan2(pt.y - at.y, pt.x - at.x), scale: d }; +} + const idle = (): [CommandState, CommandResult] => [ - { phase: "point", lastPoint: null, defIds: [], defNames: [] } as BlockState, + { phase: "point", lastPoint: null, defIds: [], defNames: [] } as BlockPoint, { draft: null, done: true }, ]; export const blockCommand: Command = { name: "block", labelKey: "cmd.block.label", - prompt: () => "cmd.block.point", + prompt: (s) => ((s as BlockState).phase === "rotate" ? "cmd.block.rotate" : "cmd.block.point"), accepts: () => ["point", "option"], options: (state) => { const s = state as BlockState; const i = s.defIds.length ? lastDefIndex % s.defIds.length : 0; return s.defIds.length ? [{ ...DEF_OPTION, value: s.defNames[i] }] : []; }, - init: (): BlockState => ({ phase: "point", lastPoint: null, defIds: [], defNames: [] }), + init: (): BlockPoint => ({ phase: "point", lastPoint: null, defIds: [], defNames: [] }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as BlockState; const { ids, names } = readDefs(ctx); - const ns: BlockState = { ...s, defIds: ids, defNames: names }; + if (input.kind === "option") { if (input.id === "def" && ids.length) lastDefIndex = (lastDefIndex + 1) % ids.length; - return [ns, { draft: null }]; + return [{ ...s, defIds: ids, defNames: names } as BlockState, { draft: null }]; } - if (input.kind !== "point") return [ns, { draft: null }]; - if (ids.length === 0) return idle(); - const blockDefId = ids[lastDefIndex % ids.length]; - const at = input.point; - return [idle()[0], { draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, ctx) }]; + if (input.kind !== "point") return [{ ...s, defIds: ids, defNames: names } as BlockState, { draft: null }]; + + if (s.phase === "point") { + if (ids.length === 0) return idle(); + const ns: BlockRotate = { phase: "rotate", defIds: ids, defNames: names, at: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: { preview: [], vertices: [input.point] } }]; + } + + // phase "rotate": Klick auf denselben Punkt = 0°/Grösse 1 (kein Rückschritt + // zum bisherigen Verhalten für alle, denen Richtung/Grösse egal ist). + const blockDefId = s.defIds[lastDefIndex % s.defIds.length]; + const { at } = s; + const pt = input.point; + const { rotation, scale } = rotationAndScaleFrom(at, pt); + return [ + idle()[0], + { draft: null, done: true, commit: (p) => appendInstance(p, blockDefId, at, rotation, scale, ctx) }, + ]; }, - onMove: (state, _point, _snap, ctx): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as BlockState; const { ids, names } = readDefs(ctx); - const ns: BlockState = { ...s, defIds: ids, defNames: names }; - return [ns, { draft: null }]; + if (s.phase === "rotate") { + const ns: BlockRotate = { ...s, defIds: ids, defNames: names, cursor: point }; + const preview = + Math.hypot(point.x - s.at.x, point.y - s.at.y) < EPS + ? [] + : [{ kind: "line" as const, a: s.at, b: point }]; + return [ns, { draft: { preview, vertices: [s.at], hud: segmentHud(s.at, point) } }]; + } + return [{ ...s, defIds: ids, defNames: names } as BlockState, { draft: null }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), diff --git a/src/commands/cmds/break.test.ts b/src/commands/cmds/break.test.ts new file mode 100644 index 0000000..fc46999 --- /dev/null +++ b/src/commands/cmds/break.test.ts @@ -0,0 +1,127 @@ +/** + * `breakCommand` — zwei Klicks auf eine Linie/offene Polylinie entfernen den + * dazwischenliegenden Abschnitt (AutoCADs BREAK). + */ + +import { describe, it, expect } from "vitest"; +import { breakCommand } from "./break"; +import type { CommandContext, Project } from "../types"; +import type { Drawing2D } from "../../model/types"; + +function project(drawings: Drawing2D[]): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + } as unknown as Project; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const line: Drawing2D = { + id: "L1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }, +}; + +describe("breakCommand", () => { + it("zwei Klicks auf eine Linie ersetzen sie durch zwei kürzere Linien", () => { + const p = project([line]); + const ctx = makeCtx(p); + let [state] = breakCommand.onInput(breakCommand.init(), { kind: "point", point: { x: 3, y: 0 } }, ctx); + const [, result] = breakCommand.onInput(state, { kind: "point", point: { x: 7, y: 0 } }, ctx); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(2); + const geoms = next.drawings2d.map((d) => d.geom); + expect(geoms.every((g) => g.shape === "line")).toBe(true); + const asLines = geoms as Extract[]; + const spans = asLines.map((g) => [g.a.x, g.b.x].sort((a, b) => a - b)); + expect(spans).toContainEqual([0, 3]); + expect(spans).toContainEqual([7, 10]); + }); + + it("Klick daneben (kein Treffer) bleibt im ersten Schritt, kein Commit", () => { + const p = project([line]); + const ctx = makeCtx(p); + const [after, result] = breakCommand.onInput(breakCommand.init(), { kind: "point", point: { x: 3, y: 5 } }, ctx); + expect(result.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("p1"); + }); + + it("Klick auf eine GESCHLOSSENE Polylinie wird abgelehnt (bewusst nicht unterstützt)", () => { + const closedPoly: Drawing2D = { + id: "P1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], + closed: true, + }, + }; + const p = project([closedPoly]); + const ctx = makeCtx(p); + const [after, result] = breakCommand.onInput(breakCommand.init(), { kind: "point", point: { x: 2, y: 0 } }, ctx); + expect(result.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("p1"); + }); + + it("Klick auf ein Bogen-Segment (bulge) wird abgelehnt (bewusst nicht unterstützt)", () => { + const arcPoly: Drawing2D = { + id: "P2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], + closed: false, + bulge: [1], + }, + }; + const p = project([arcPoly]); + const ctx = makeCtx(p); + const [after, result] = breakCommand.onInput(breakCommand.init(), { kind: "point", point: { x: 2, y: 1 } }, ctx); + expect(result.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("p1"); + }); + + it("onConfirm/onCancel kehren in den Ruhezustand zurück", () => { + const ctx = makeCtx(project([])); + const [, res1] = breakCommand.onConfirm(breakCommand.init(), ctx); + expect(res1.done).toBe(true); + expect(res1.commit).toBeUndefined(); + const [, res2] = breakCommand.onCancel(breakCommand.init()); + expect(res2.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/break.ts b/src/commands/cmds/break.ts new file mode 100644 index 0000000..82f9489 --- /dev/null +++ b/src/commands/cmds/break.ts @@ -0,0 +1,120 @@ +// Break — entfernt den Abschnitt ZWISCHEN zwei geklickten Punkten auf einer +// Kurve (line/offene, NICHT gebogene polyline), AutoCADs BREAK-Befehl. +// Nutzer-Wunsch: „Stretch/Break fehlen als Befehle — der Kernel hätte mit +// splitAtIntersections/removeSegment das meiste für Break schon fertig." +// (Tatsächlich reichte eine neue, direktere Kernel-Funktion — `breakCurve` — +// eher als die genannten; s. Kopfkommentar dort.) +// +// Schritte: +// 1) „Erster Punkt:" → Punkt (bestimmt die Kurve + Startposition) +// 2) „Zweiter Punkt:" → Punkt (Position auf DERSELBEN Kurve) → commit: +// der Abschnitt zwischen beiden Positionen (Klick-Reihenfolge egal) +// fällt weg, bis zu zwei Reststücke bleiben. +// +// Bewusst NICHT unterstützt (Klick auf eine geschlossene Kurve oder eine mit +// Bogen-Segmenten bricht NICHT ab, sondern bleibt im ersten Schritt — sonst +// säße der Nutzer nach einem Fehlklick im zweiten Schritt fest, ohne zu +// wissen warum): geschlossene Polylinien/Rechtecke (welcher der beiden +// Ring-Bögen übrig bleibt, ist klick-reihenfolge-abhängig — eigener, +// grösserer Scope) und Bogen-Segmente (bulge) — beide s. PENDENZEN.md. + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import { breakCurve, nearestOnPolyline } from "../../geometry/kernel2d"; +import { hasRealBulge } from "../../geometry/bulge"; +import { chainToGeom, geomToCurve, isTrimmable, pickCurveAt } from "./trim"; +import type { + Command, + CommandResult, + CommandState, + DraftShape, + Project, + Vec2, +} from "../types"; + +/** Trifft der Klick eine offene, bogen-freie Kurve (line/gerade polyline)? */ +function pickBreakable(project: Project, levelId: string, pt: Vec2): Drawing2D | null { + const d = pickCurveAt(project, levelId, pt); + if (!d || !isTrimmable(d)) return null; + const curve = geomToCurve(d.geom); + if (!curve || curve.closed || hasRealBulge(curve.bulge)) return null; + return d; +} + +function applyBreak(p: Project, target: Drawing2D, p1: Vec2, p2: Vec2): Project { + const curve = geomToCurve(target.geom); + if (!curve) return p; + const hit1 = nearestOnPolyline(curve.pts, false, p1); + const hit2 = nearestOnPolyline(curve.pts, false, p2); + if (!hit1 || !hit2) return p; + const pieces = breakCurve(curve.pts, hit1, hit2); + const replacements: Drawing2D[] = pieces.map((pts) => ({ + ...target, + id: uniqueId("dr2d"), + geom: chainToGeom({ pts, closed: false }), + })); + const others = p.drawings2d.filter((d) => d.id !== target.id); + return { ...p, drawings2d: [...others, ...replacements] }; +} + +/** Vorschau der Reststücke (für den Draft). */ +function breakPreview(target: Drawing2D, p1: Vec2, p2: Vec2): DraftShape[] { + const curve = geomToCurve(target.geom); + if (!curve) return []; + const hit1 = nearestOnPolyline(curve.pts, false, p1); + const hit2 = nearestOnPolyline(curve.pts, false, p2); + if (!hit1 || !hit2) return []; + return breakCurve(curve.pts, hit1, hit2) + .filter((pts) => pts.length >= 2) + .map((pts) => (pts.length === 2 ? { kind: "line" as const, a: pts[0], b: pts[1] } : { kind: "poly" as const, pts, closed: false })); +} + +interface BreakP1 extends CommandState { + phase: "p1"; +} +interface BreakP2 extends CommandState { + phase: "p2"; + target: Drawing2D; + p1: Vec2; + cursor: Vec2 | null; +} +type BreakState = BreakP1 | BreakP2; + +const idle = (): [CommandState, CommandResult] => [ + { phase: "p1", lastPoint: null } as BreakP1, + { draft: null, done: true }, +]; + +export const breakCommand: Command = { + name: "break", + labelKey: "cmd.break.label", + prompt: (s) => ((s as BreakState).phase === "p2" ? "cmd.break.p2" : "cmd.break.p1"), + accepts: () => ["point"], + options: () => [], + init: (): BreakP1 => ({ phase: "p1", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as BreakState; + if (input.kind !== "point") return [s, { draft: null }]; + if (s.phase === "p1") { + const target = pickBreakable(ctx.project, ctx.level.id, input.point); + if (!target) return [s, { draft: null }]; // daneben/ungeeignet → bleibt im ersten Schritt + const ns: BreakP2 = { phase: "p2", target, p1: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: null }]; + } + // phase "p2" + const { target, p1 } = s; + return [idle()[0], { draft: null, done: true, commit: (p) => applyBreak(p, target, p1, input.point) }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as BreakState; + if (s.phase !== "p2") return [s, { draft: null }]; + const ns: BreakP2 = { ...s, cursor: point }; + const preview = breakPreview(s.target, s.p1, point); + return [ns, { draft: { preview, vertices: [s.p1] } }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/circle.test.ts b/src/commands/cmds/circle.test.ts new file mode 100644 index 0000000..a87a0ba --- /dev/null +++ b/src/commands/cmds/circle.test.ts @@ -0,0 +1,254 @@ +/** + * `circleCommand` — drei Konstruktionsmethoden: Mittelpunkt+Radius (Default, + * unverändert), NEU 2-Punkt (Durchmesser-Enden) und 3-Punkt (Umkreis), + * Nutzer-Wunsch „Kreis durch zwei/drei bekannte Punkte". + */ + +import { describe, it, expect } from "vitest"; +import { circleCommand } from "./circle"; +import type { CommandContext, CommandState, Project, Vec2 } from "../types"; +import type { Drawing2D } from "../../model/types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const pt = (x: number, y: number) => ({ x, y }); + +function lineDraw(id: string, a: Vec2, b: Vec2): Drawing2D { + return { id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a, b } }; +} +function circleDraw(id: string, center: Vec2, r: number): Drawing2D { + return { id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center, r } }; +} +/** Zyklt die Methode-Option, bis `options[0].value === target` erreicht ist. */ +function switchTo(state: CommandState, ctx: CommandContext, target: string): CommandState { + let s = state; + while (circleCommand.options(s)[0].value !== target) { + [s] = circleCommand.onInput(s, { kind: "option", id: "method" }, ctx); + } + return s; +} + +describe("circleCommand — Methode Mittelpunkt (Default, unverändert)", () => { + it("Mittelpunkt → Radius-Punkt committet den Kreis", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("circle"); + if (g.shape === "circle") { + expect(g.center).toEqual({ x: 0, y: 0 }); + expect(g.r).toBeCloseTo(5, 9); + } + }); + + it("Mittelpunkt → getippte Zahl (Radius) committet ebenso", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "number", value: 3 }, ctx); + const g = result.commit!(p).drawings2d[0].geom; + if (g.shape === "circle") expect(g.r).toBeCloseTo(3, 9); + }); +}); + +describe("circleCommand — Methode 2-Punkt (Durchmesser)", () => { + it("zwei Punkte sind die Enden eines Durchmessers", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 2pt + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "point", point: pt(4, 0) }, ctx); + const g = result.commit!(p).drawings2d[0].geom; + expect(g.shape).toBe("circle"); + if (g.shape === "circle") { + expect(g.center).toEqual({ x: 2, y: 0 }); + expect(g.r).toBeCloseTo(2, 9); + } + }); +}); + +describe("circleCommand — Methode 3-Punkt (Umkreis)", () => { + it("drei Punkte auf dem Kreis ergeben den korrekten Umkreis", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 3pt + [state] = circleCommand.onInput(state, { kind: "point", point: pt(1, 0) }, ctx); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 1) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "point", point: pt(-1, 0) }, ctx); + const g = result.commit!(p).drawings2d[0].geom; + expect(g.shape).toBe("circle"); + if (g.shape === "circle") { + expect(g.center.x).toBeCloseTo(0, 6); + expect(g.center.y).toBeCloseTo(0, 6); + expect(g.r).toBeCloseTo(1, 6); + } + }); + + it("kollinearer dritter Punkt wird ignoriert (kein Commit, bleibt in Phase 3)", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(2, 0) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); + expect(result.commit).toBeUndefined(); + }); +}); + +describe("circleCommand — Methodenwechsel", () => { + it("zyklt center → 2pt → 3pt → ttr → center", () => { + let state: CommandState = circleCommand.init(); + const p = project(); + const ctx = makeCtx(p); + expect(circleCommand.options(state)[0].value).toBe("center"); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + expect(circleCommand.options(state)[0].value).toBe("2pt"); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + expect(circleCommand.options(state)[0].value).toBe("3pt"); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + expect(circleCommand.options(state)[0].value).toBe("ttr"); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); + expect(circleCommand.options(state)[0].value).toBe("center"); + }); + + it("Methodenwechsel verwirft eine laufende Konstruktion", () => { + const p = project(); + const ctx = makeCtx(p); + let state: CommandState = circleCommand.init(); + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 2pt + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 0) }, ctx); // erster Punkt gesetzt + [state] = circleCommand.onInput(state, { kind: "option", id: "method" }, ctx); // → 3pt, verwirft + expect(circleCommand.prompt(state)).toBe("cmd.circle.threeFirst"); + }); +}); + +describe("circleCommand — Methode TTR (Tangente-Tangente-Radius)", () => { + it("Radius per getippter Zahl (2) → Kreis bei (2,2), tangential an beide Achsen-Segmente", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0)), lineDraw("l2", pt(0, -10), pt(0, 10))]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); // near1 auf l1 + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 5) }, ctx); // near2 auf l2 + const [, result] = circleCommand.onInput(state, { kind: "number", value: 2 }, ctx); + expect(result.commit).toBeDefined(); + const g = result.commit!(p).drawings2d.at(-1)!.geom; + expect(g.shape).toBe("circle"); + if (g.shape === "circle") { + expect(g.center.x).toBeCloseTo(2, 9); + expect(g.center.y).toBeCloseTo(2, 9); + expect(g.r).toBeCloseTo(2, 9); + } + }); + + it("Radius per Klickpunkt (Abstand zum ERSTEN Klickpunkt) → derselbe Kreis wie bei getippter Zahl", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0)), lineDraw("l2", pt(0, -10), pt(0, 10))]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); // near1=(5,0) + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 5) }, ctx); // near2=(0,5) + // Klickpunkt (7,0): Abstand zu near1(5,0) ist genau 2 → identischer Radius wie oben. + const [, result] = circleCommand.onInput(state, { kind: "point", point: pt(7, 0) }, ctx); + expect(result.commit).toBeDefined(); + const g = result.commit!(p).drawings2d.at(-1)!.geom; + if (g.shape === "circle") { + expect(g.center.x).toBeCloseTo(2, 9); + expect(g.center.y).toBeCloseTo(2, 9); + expect(g.r).toBeCloseTo(2, 9); + } + }); + + it("Linie + Kreis: Zielkreis in der Lücke, tangential an beide", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0)), circleDraw("c1", pt(0, 6), 3)]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(3, 0) }, ctx); // near1 auf der Linie + // near2 auf dem Kreis, nahe dem erwarteten Kandidaten (3,2): Punkt auf dem + // Kreis in Richtung (3,-4) von (0,6) aus, normiert*3 = (1.8, 3.6). + [state] = circleCommand.onInput(state, { kind: "point", point: pt(1.8, 3.6) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "number", value: 2 }, ctx); + expect(result.commit).toBeDefined(); + const g = result.commit!(p).drawings2d.at(-1)!.geom; + if (g.shape === "circle") { + expect(g.center.x).toBeCloseTo(3, 6); + expect(g.center.y).toBeCloseTo(2, 6); + expect(g.r).toBeCloseTo(2, 9); + } + }); + + it("Klick trifft keine Linie/Kreis → wird ignoriert, Schritt bleibt in Phase 1", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0))]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + const [ns, result] = circleCommand.onInput(state, { kind: "point", point: pt(100, 100) }, ctx); + expect(result.commit).toBeUndefined(); + expect(circleCommand.prompt(ns)).toBe("cmd.circle.ttrFirst"); + }); + + it("zweiter Klick trifft dasselbe Element wie der erste → wird ignoriert, Schritt bleibt in Phase 2", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0))]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); // trifft l1 + const [ns, result] = circleCommand.onInput(state, { kind: "point", point: pt(-5, 0) }, ctx); // trifft l1 nochmal + expect(result.commit).toBeUndefined(); + expect(circleCommand.prompt(ns)).toBe("cmd.circle.ttrSecond"); + }); + + it("geometrisch unlösbarer Radius (z. B. 0) → kein Commit, Schritt bleibt in Phase 3", () => { + const p = project(); + p.drawings2d = [lineDraw("l1", pt(-10, 0), pt(10, 0)), lineDraw("l2", pt(0, -10), pt(0, 10))]; + const ctx = makeCtx(p); + let state: CommandState = switchTo(circleCommand.init(), ctx, "ttr"); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(5, 0) }, ctx); + [state] = circleCommand.onInput(state, { kind: "point", point: pt(0, 5) }, ctx); + const [, result] = circleCommand.onInput(state, { kind: "number", value: 0 }, ctx); + expect(result.commit).toBeUndefined(); + }); +}); diff --git a/src/commands/cmds/circle.ts b/src/commands/cmds/circle.ts index 6e83325..c893270 100644 --- a/src/commands/cmds/circle.ts +++ b/src/commands/cmds/circle.ts @@ -1,14 +1,51 @@ -// Circle — Mittelpunkt + Radius. Schritte: -// 1) „Mittelpunkt:" → Punkt -// 2) „Radius:" → Punkt (Abstand) ODER getippte Zahl (Radius) → commit +// Circle — vier Konstruktionsmethoden (Nutzer-Wunsch: „Kreis durch zwei/drei +// bekannte Punkte" bzw. „tangential an zwei Wände" lässt sich über reines +// Mittelpunkt+Radius nicht direkt lösen). Wählbar über die Option „Methode" +// (klickbar im Feld-Row, tippbar als „m", zyklisch — dasselbe Muster wie bei +// `rect.ts`/`arc.ts`). // -// Radius akzeptiert sowohl einen Maus-Punkt (Abstand zum Mittelpunkt) als auch -// eine getippte nackte Zahl. Der Kreis wird in generatePlan als geschlossene -// Polygon-Approximation gerendert. +// • Mittelpunkt (Default, unverändert): Mittelpunkt + Radius. +// 1) „Mittelpunkt:" → Punkt +// 2) „Radius:" → Punkt (Abstand) ODER getippte Zahl (Radius) → commit +// • 2-Punkt: die zwei Punkte sind die Enden EINES Durchmessers. +// 1) „Erster Punkt (Durchmesser):" → Punkt +// 2) „Zweiter Punkt (Durchmesser):" → Punkt → commit +// • 3-Punkt: Kreis durch alle drei Punkte (Umkreis). +// 1) „Erster Punkt:" → Punkt +// 2) „Zweiter Punkt:" → Punkt +// 3) „Dritter Punkt:" → Punkt → commit (kollinear ⇒ Punkt wird ignoriert) +// • TTR (Tangente-Tangente-Radius): Kreis tangential an zwei bestehende +// Linien/Kreise/Bögen (gerade Kanten von line/polyline/rect ODER volle +// circle/arc-Kreise), mit vorgegebenem Radius. +// 1) „Erstes Tangentenobjekt wählen:" → Punkt (Hit-Test, kein Treffer +// ⇒ Klick wird ignoriert, Schritt bleibt aktiv) +// 2) „Zweites Tangentenobjekt wählen:" → Punkt (Hit-Test; Treffer auf +// dasselbe Element wie Schritt 1 wird ignoriert) +// 3) „Radius:" → Punkt (Abstand zum ERSTEN Klickpunkt aus Schritt 1) +// ODER getippte Zahl → commit. Die eigentliche Geometrie steckt in +// `geometry/kernel2d.ts::tangentCircleCenters` (Apollonius- +// Spezialfall mit bekanntem Radius): pro Tangentialobjekt wird der +// geometrische Ort aller passenden Mittelpunkte gebildet (Gerade: +// zwei Parallelen im Abstand r; Kreis: äussere/innere Berührung), +// die Örter werden geschnitten, und aus den 0-8 Kandidaten wird der +// zu den beiden ANKLICKPUNKTEN nächstgelegene gewählt (dieselbe +// „near"-Disambiguierung wie bei `bulgeFromSagittaPoint` &Co.). +// +// Radius akzeptiert bei der Mittelpunkt- UND der TTR-Methode sowohl einen +// Maus-Punkt (Abstand) als auch eine getippte nackte Zahl. Der Kreis wird in +// generatePlan als geschlossene Polygon-Approximation gerendert. -import type { Drawing2D } from "../../model/types"; +import type { Drawing2D, Drawing2DGeom } from "../../model/types"; import { uniqueId } from "../../tools/types"; +import { arcThroughPoints } from "../../geometry/bulge"; +import { + pointSegmentDistance, + polylineEdges, + tangentCircleCenters, + type TangentTarget, +} from "../../geometry/kernel2d"; import type { + CmdOption, Command, CommandContext, CommandField, @@ -19,22 +56,178 @@ import type { ToolDraft, Vec2, } from "../types"; +import type { TranslationKey } from "../../i18n"; const EPS = 1e-6; -interface CircleIdle extends CommandState { +/** Konstruktionsmethode. */ +type CircleMethod = "center" | "twoPoint" | "threePoint" | "ttr"; +const METHOD_ORDER: CircleMethod[] = ["center", "twoPoint", "threePoint", "ttr"]; +const nextMethod = (m: CircleMethod): CircleMethod => + METHOD_ORDER[(METHOD_ORDER.indexOf(m) + 1) % METHOD_ORDER.length]; +const methodValue = (m: CircleMethod): string => + m === "center" ? "center" : m === "twoPoint" ? "2pt" : m === "threePoint" ? "3pt" : "ttr"; + +const methodOption = (m: CircleMethod): CmdOption => ({ + id: "method", + labelKey: "cmd.circle.method", + value: methodValue(m), +}); + +interface CircleCenterP1 extends CommandState { phase: "center"; + method: "center"; } -interface CircleDrawing extends CommandState { +interface CircleCenterP2 extends CommandState { phase: "radius"; + method: "center"; center: Vec2; cursor: Vec2 | null; } -type CircleState = CircleIdle | CircleDrawing; +interface CircleTwoP1 extends CommandState { + phase: "p1"; + method: "twoPoint"; +} +interface CircleTwoP2 extends CommandState { + phase: "p2"; + method: "twoPoint"; + a: Vec2; + cursor: Vec2 | null; +} +interface CircleThreeP1 extends CommandState { + phase: "p1"; + method: "threePoint"; +} +interface CircleThreeP2 extends CommandState { + phase: "p2"; + method: "threePoint"; + a: Vec2; + cursor: Vec2 | null; +} +interface CircleThreeP3 extends CommandState { + phase: "p3"; + method: "threePoint"; + a: Vec2; + b: Vec2; + cursor: Vec2 | null; +} +interface CircleTtrT1 extends CommandState { + phase: "t1"; + method: "ttr"; +} +interface CircleTtrT2 extends CommandState { + phase: "t2"; + method: "ttr"; + t1: TangentTarget; + near1: Vec2; + t1DrawingId: string; +} +interface CircleTtrRadius extends CommandState { + phase: "radius"; + method: "ttr"; + t1: TangentTarget; + near1: Vec2; + t2: TangentTarget; + near2: Vec2; + cursor: Vec2 | null; +} +type CircleState = + | CircleCenterP1 + | CircleCenterP2 + | CircleTwoP1 + | CircleTwoP2 + | CircleThreeP1 + | CircleThreeP2 + | CircleThreeP3 + | CircleTtrT1 + | CircleTtrT2 + | CircleTtrRadius; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); -/** Tab-Feld des Radius-Schritts: der Radius selbst. */ +// ── TTR: Hit-Testing auf bestehende Linien/Kreise ─────────────────────────── + +const TTR_HIT_TOL = 0.3; // Modell-Meter: Pick-Toleranz für die Tangentenobjekt-Wahl + +interface TangentPick { + target: TangentTarget; + near: Vec2; + drawingId: string; +} + +/** Winkel `ang` (rad) liegt innerhalb des Bogenspanns [a0, a1) (CCW, mit Wraparound). */ +function inArcSpan(a0: number, a1: number, ang: number): boolean { + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const sweep = norm(a1 - a0) || TAU; + return norm(ang - a0) <= sweep + 1e-6; +} + +/** Gerade Kanten einer Form (line/polyline ohne Bogen-Segmente/rect) für den TTR-Hit-Test. */ +function straightEdgesOf(g: Drawing2DGeom): [Vec2, Vec2][] { + if (g.shape === "line") return [[g.a, g.b]]; + if (g.shape === "rect") { + const pts = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; + return polylineEdges(pts, true); + } + if (g.shape === "polyline") { + const edges = polylineEdges(g.pts, g.closed); + // Bogen-Segmente (bulge) sind hier keine Geraden — von der Tangenten-Wahl + // ausgenommen (dieselbe Vereinfachung wie bei fillet.ts::geomToCurve). + return edges.filter((_, i) => Math.abs(g.bulge?.[i] ?? 0) <= EPS); + } + return []; +} + +/** Nächstes tangentenfähiges Element (Gerade ODER Kreis/Bogen) zum Klickpunkt, oder null. */ +function pickTangentTarget(project: Project, levelId: string, pt: Vec2): TangentPick | null { + let best: TangentPick | null = null; + let bestD = TTR_HIT_TOL; + for (const d of project.drawings2d) { + if (d.levelId !== levelId) continue; + const g = d.geom; + if (g.shape === "circle") { + const dd = Math.abs(dist(pt, g.center) - g.r); + if (dd < bestD) { + bestD = dd; + best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id }; + } + } else if (g.shape === "arc") { + const dd = Math.abs(dist(pt, g.center) - g.r); + const ang = Math.atan2(pt.y - g.center.y, pt.x - g.center.x); + if (dd < bestD && inArcSpan(g.a0, g.a1, ang)) { + bestD = dd; + best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id }; + } + } else { + for (const [a, b] of straightEdgesOf(g)) { + const dd = pointSegmentDistance(pt, a, b); + if (dd < bestD) { + bestD = dd; + best = { target: { kind: "line", a, b }, near: pt, drawingId: d.id }; + } + } + } + } + return best; +} + +/** Von mehreren Mittelpunkt-Kandidaten den zu (near1, near2) nächstgelegenen wählen. */ +function nearestCandidate(cands: Vec2[], near1: Vec2, near2: Vec2): Vec2 | null { + let best: Vec2 | null = null; + let bestD = Infinity; + for (const c of cands) { + const dd = dist(c, near1) + dist(c, near2); + if (dd < bestD) { + bestD = dd; + best = c; + } + } + return best; +} + +/** Tab-Feld des Radius-Schritts (nur Methode „center"): der Radius selbst. */ const CIRCLE_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }]; /** @@ -72,6 +265,11 @@ function circleDraft(center: Vec2, r: number, at: Vec2 | null): ToolDraft { return draft; } +/** Platzhalter-Vorschau (gerade Linie) für Zwischenschritte ohne vollständigen Kreis. */ +function lineDraft(a: Vec2, b: Vec2): ToolDraft { + return { preview: [{ kind: "line", a, b }], vertices: [a] }; +} + function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): Project { if (r < EPS) return p; const d: Drawing2D = { @@ -84,63 +282,192 @@ function appendCircle(p: Project, center: Vec2, r: number, ctx: CommandContext): return { ...p, drawings2d: [...p.drawings2d, d] }; } -const idle = (): [CommandState, CommandResult] => [ - { phase: "center", lastPoint: null }, +const idle = (method: CircleMethod): [CommandState, CommandResult] => [ + (method === "center" + ? { phase: "center", method } + : method === "ttr" + ? { phase: "t1", method } + : { phase: "p1", method }) as CircleState, { draft: null, done: true }, ]; +function promptKey(s: CircleState): TranslationKey { + if (s.method === "center") return s.phase === "radius" ? "cmd.circle.radius" : "cmd.circle.center"; + if (s.method === "twoPoint") return s.phase === "p2" ? "cmd.circle.diameterEnd" : "cmd.circle.diameterStart"; + if (s.method === "ttr") { + if (s.phase === "radius") return "cmd.circle.radius"; + return s.phase === "t2" ? "cmd.circle.ttrSecond" : "cmd.circle.ttrFirst"; + } + // threePoint + if (s.phase === "p2") return "cmd.circle.threeSecond"; + if (s.phase === "p3") return "cmd.circle.threeThird"; + return "cmd.circle.threeFirst"; +} + export const circleCommand: Command = { name: "circle", labelKey: "cmd.circle.label", - prompt: (s) => ((s as CircleState).phase === "radius" ? "cmd.circle.radius" : "cmd.circle.center"), - accepts: (s) => ((s as CircleState).phase === "radius" ? ["point", "number"] : ["point"]), - options: () => [], - init: (): CircleIdle => ({ phase: "center", lastPoint: null }), + prompt: (s) => promptKey(s as CircleState), + accepts: (s) => { + const st = s as CircleState; + if (st.phase === "radius" && (st.method === "center" || st.method === "ttr")) return ["point", "number", "option"]; + return ["point", "option"]; + }, + options: (s) => [methodOption((s as CircleState).method)], + init: (): CircleCenterP1 => ({ phase: "center", method: "center", lastPoint: null }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as CircleState; - if (s.phase !== "radius") { + + if (input.kind === "option") { + if (input.id === "method") return idle(nextMethod(s.method)); + return [s, { draft: null }]; + } + // Nur die Mittelpunkt- und die TTR-Methode akzeptieren im Radius-Schritt + // eine getippte Zahl; alle anderen Schritte/Methoden brauchen einen Punkt. + const acceptsNumber = s.phase === "radius" && (s.method === "center" || s.method === "ttr"); + if (input.kind !== "point" && !(acceptsNumber && input.kind === "number")) { + return [s, { draft: null }]; + } + + if (s.method === "center") { + if (s.phase !== "radius") { + if (input.kind !== "point") return [s, { draft: null }]; + const ns: CircleCenterP2 = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: circleDraft(input.point, 0, null) }]; + } + let r: number; + if (input.kind === "number") r = input.value; + else r = dist(s.center, input.point); + const center = s.center; + return [idle("center")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + } + + if (s.method === "ttr") { + if (s.phase === "radius") { + let r: number; + if (input.kind === "number") r = input.value; + else r = dist(s.near1, input.point); + const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null; + // Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten. + if (!center) return [s, { draft: null }]; + return [idle("ttr")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; + } if (input.kind !== "point") return [s, { draft: null }]; - const ns: CircleDrawing = { phase: "radius", center: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: circleDraft(input.point, 0, null) }]; + const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point); + if (!pick) return [s, { draft: null }]; // kein Treffer auf Linie/Kreis — ignorieren, weiter warten + if (s.phase === "t1") { + const ns: CircleTtrT2 = { + phase: "t2", + method: "ttr", + t1: pick.target, + near1: pick.near, + t1DrawingId: pick.drawingId, + lastPoint: input.point, + }; + return [ns, { draft: { preview: [], vertices: [pick.near] } }]; + } + // phase t2 + if (pick.drawingId === s.t1DrawingId) return [s, { draft: null }]; // dasselbe Element — ignorieren + const ns: CircleTtrRadius = { + phase: "radius", + method: "ttr", + t1: s.t1, + near1: s.near1, + t2: pick.target, + near2: pick.near, + cursor: input.point, + lastPoint: input.point, + }; + return [ns, { draft: lineDraft(s.near1, pick.near) }]; } - // Radius-Schritt: Zahl = Radius, Punkt = Abstand zum Mittelpunkt. - let r: number; - if (input.kind === "number") r = input.value; - else if (input.kind === "point") r = dist(s.center, input.point); - else { - const rr = s.cursor ? dist(s.center, s.cursor) : 0; - return [s, { draft: circleDraft(s.center, rr, s.cursor) }]; + + if (input.kind !== "point") return [s, { draft: null }]; + const pt = input.point; + + if (s.method === "twoPoint") { + if (s.phase === "p1") { + const ns: CircleTwoP2 = { phase: "p2", method: "twoPoint", a: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + const center = mid(s.a, pt); + const r = dist(s.a, pt) / 2; + return [idle("twoPoint")[0], { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }]; } - const center = s.center; + + // threePoint + if (s.phase === "p1") { + const ns: CircleThreeP2 = { phase: "p2", method: "threePoint", a: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + if (s.phase === "p2") { + if (dist(s.a, pt) < EPS) return [s, { draft: null }]; + const ns: CircleThreeP3 = { phase: "p3", method: "threePoint", a: s.a, b: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: lineDraft(s.a, pt) }]; + } + // phase p3: dritter Punkt → Umkreis, committen. + const circ = arcThroughPoints(s.a, s.b, pt); // a0/a1 hier irrelevant, nur center+r zählen + if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten return [ - { phase: "center", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendCircle(p, center, r, ctx) }, + idle("threePoint")[0], + { draft: null, done: true, commit: (p) => appendCircle(p, circ.center, circ.r, ctx) }, ]; }, onMove: (state, point): [CommandState, CommandResult] => { const s = state as CircleState; - if (s.phase !== "radius") return [s, { draft: null }]; - const r = dist(s.center, point); - const ns: CircleDrawing = { ...s, cursor: point }; - return [ns, { draft: circleDraft(s.center, r, point) }]; + if (s.method === "center") { + if (s.phase !== "radius") return [s, { draft: null }]; + const r = dist(s.center, point); + const ns: CircleCenterP2 = { ...s, cursor: point }; + return [ns, { draft: circleDraft(s.center, r, point) }]; + } + if (s.method === "twoPoint") { + if (s.phase !== "p2") return [s, { draft: null }]; + const ns: CircleTwoP2 = { ...s, cursor: point }; + return [ns, { draft: circleDraft(mid(s.a, point), dist(s.a, point) / 2, point) }]; + } + // threePoint + if (s.phase === "p2") { + const ns: CircleThreeP2 = { ...s, cursor: point }; + return [ns, { draft: lineDraft(s.a, point) }]; + } + if (s.phase === "p3") { + const ns: CircleThreeP3 = { ...s, cursor: point }; + const circ = arcThroughPoints(s.a, s.b, point); + return [ns, { draft: circ ? circleDraft(circ.center, circ.r, point) : lineDraft(s.a, point) }]; + } + if (s.method === "ttr" && s.phase === "radius") { + const r = dist(s.near1, point); + const ns: CircleTtrRadius = { ...s, cursor: point }; + if (r < EPS) return [ns, { draft: null }]; + const center = nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2); + return [ns, { draft: center ? circleDraft(center, r, point) : lineDraft(s.near1, s.near2) }]; + } + return [s, { draft: null }]; }, - onConfirm: (): [CommandState, CommandResult] => idle(), - onCancel: (): [CommandState, CommandResult] => idle(), + onConfirm: (state): [CommandState, CommandResult] => idle((state as CircleState).method), + onCancel: (state): [CommandState, CommandResult] => idle((state as CircleState).method), - // Tab-Feld-Zyklus nur im „radius"-Schritt: ein Radius-Feld; der gelockte Wert - // committet direkt (Punkt liegt auf dem Kreis, dist(center,point)=radius). - fields: (state) => ((state as CircleState).phase === "radius" ? CIRCLE_FIELDS : []), + // Tab-Feld-Zyklus nur im „radius"-Schritt der Mittelpunkt-Methode; der + // gelockte Wert committet direkt (Punkt liegt auf dem Kreis). + fields: (state) => { + const s = state as CircleState; + return s.phase === "radius" && (s.method === "center" || s.method === "ttr") ? CIRCLE_FIELDS : []; + }, fieldValues: (state, _locks, cursor): Record => { const s = state as CircleState; if (s.phase !== "radius" || !cursor) return {}; - return { radius: dist(s.center, cursor) }; + if (s.method === "center") return { radius: dist(s.center, cursor) }; + if (s.method === "ttr") return { radius: dist(s.near1, cursor) }; + return {}; }, pointFromFields: (state, locks, cursor) => { const s = state as CircleState; if (s.phase !== "radius") return null; - return circlePointFromFields(s.center, locks, cursor); + if (s.method === "center") return circlePointFromFields(s.center, locks, cursor); + if (s.method === "ttr") return circlePointFromFields(s.near1, locks, cursor); + return null; }, }; diff --git a/src/commands/cmds/copy.ts b/src/commands/cmds/copy.ts index 2545534..e49e66b 100644 --- a/src/commands/cmds/copy.ts +++ b/src/commands/cmds/copy.ts @@ -8,9 +8,12 @@ // Der Commit nutzt `commitTransform` (op:"move", mode:"copy") — eine Kopie der // Auswahl an die Endlage, Original unverändert; neue IDs via uniqueId (dort). -import { commitTransform } from "../../tools/transform"; -import type { TransformSelection } from "../../tools/transform"; -import { transformPreview } from "../../tools/transform"; +import { + commitTransform, + hasTransformSelection, + toTransformSel, + transformPreview, +} from "../../tools/transform"; import type { Command, CommandField, @@ -41,25 +44,6 @@ function targetFromFields(base: Vec2, locks: Record, cursor: Vec return { x: base.x + Math.cos(ang) * length, y: base.y + Math.sin(ang) * length }; } -function hasSelection(sel: CommandSelection): boolean { - return ( - sel.wallIds.length > 0 || - sel.drawingId !== null || - (sel.drawingIds?.length ?? 0) > 0 || - !!sel.extrudedSolidId || - !!sel.columnId - ); -} -function toTransformSel(sel: CommandSelection): TransformSelection { - return { - wallIds: sel.wallIds, - drawingId: sel.drawingId, - drawingIds: sel.drawingIds, - extrudedSolidId: sel.extrudedSolidId, - columnId: sel.columnId, - }; -} - interface CopyBase extends CommandState { phase: "base"; } @@ -122,7 +106,7 @@ export const copyCommand: Command = { onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as CopyState; if (s.phase === "done") return finish(); - if (!hasSelection(ctx.selection)) { + if (!hasTransformSelection(ctx.selection)) { return [{ phase: "done", lastPoint: null } as CopyDone, { draft: null, done: true }]; } if (input.kind !== "point") { diff --git a/src/commands/cmds/detailref.test.ts b/src/commands/cmds/detailref.test.ts new file mode 100644 index 0000000..6bf72a9 --- /dev/null +++ b/src/commands/cmds/detailref.test.ts @@ -0,0 +1,89 @@ +/** + * `detailrefCommand` — ein Klick → `shape:"detailref"` mit Default-Label + * "A", ohne Blattverknüpfung (Label/Verknüpfung werden danach im + * Attribute-Panel gesetzt, s. Kopfkommentar in `detailref.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { detailrefCommand } from "./detailref"; +import type { CommandContext, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("detailrefCommand", () => { + it("ein Klick committet shape:'detailref' mit Default-Label 'A', ohne Blattverknüpfung", () => { + const p = project(); + const ctx = makeCtx(p); + const [, result] = detailrefCommand.onInput( + detailrefCommand.init(), + { kind: "point", point: { x: 4, y: 2 } }, + ctx, + ); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("detailref"); + if (g.shape === "detailref") { + expect(g.at).toEqual({ x: 4, y: 2 }); + expect(g.label).toBe("A"); + expect(g.sheetLayoutId).toBeUndefined(); + expect(g.sheetLabel).toBeUndefined(); + } + }); + + it("jeder weitere Klick platziert ein WEITERES, unabhängiges Symbol", () => { + const p = project(); + const ctx = makeCtx(p); + const [, r1] = detailrefCommand.onInput(detailrefCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + let next = r1.commit!(p); + const [, r2] = detailrefCommand.onInput(detailrefCommand.init(), { kind: "point", point: { x: 5, y: 5 } }, ctx); + next = r2.commit!(next); + expect(next.drawings2d.length).toBe(2); + expect(next.drawings2d[0].id).not.toBe(next.drawings2d[1].id); + }); + + it("onConfirm/onCancel kehren in den Ruhezustand zurück (kein Commit)", () => { + const ctx = makeCtx(project()); + const [, res1] = detailrefCommand.onConfirm(detailrefCommand.init(), ctx); + expect(res1.commit).toBeUndefined(); + expect(res1.done).toBe(true); + const [, res2] = detailrefCommand.onCancel(detailrefCommand.init()); + expect(res2.commit).toBeUndefined(); + expect(res2.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/detailref.ts b/src/commands/cmds/detailref.ts new file mode 100644 index 0000000..55b96f5 --- /dev/null +++ b/src/commands/cmds/detailref.ts @@ -0,0 +1,78 @@ +// Detail-/Schnitt-Verweis-Symbol (Nutzer-Wunsch: „Kein zweiteiliges Verweis- +// Symbol, das eine Sheet/Layout-ID trägt"). Schritte: +// 1) „Punkt:" → Punkt (Kreis-Zentrum) → commit mit Default-Label „A", +// OHNE Blattverknüpfung. Label/Blattverknüpfung werden DANACH im +// Attribute-Panel gesetzt (wie beim Platzieren eines Blocks: erst +// Position, Feinheiten hinterher) — kein Tipp-Schritt beim Platzieren +// nötig, das Symbol landet sofort selektiert-editierbar im Plan. + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (drawing2d.ts) +const DEFAULT_LABEL = "A"; + +interface DetailRefIdle extends CommandState { + phase: "point"; +} +type DetailRefState = DetailRefIdle; + +/** Kreis-Vorschau (Vollkreis-Approximation, wie andere Symbol-Vorschauen). */ +function pointDraft(at: Vec2): ToolDraft { + const N = 32; + const pts: Vec2[] = []; + for (let i = 0; i < N; i++) { + const t = (i / N) * Math.PI * 2; + pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) }); + } + const preview: DraftShape[] = [{ kind: "poly", pts, closed: true }]; + return { preview, vertices: [at] }; +} + +function appendDetailRef(p: Project, at: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "detailref", at, label: DEFAULT_LABEL }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "point", lastPoint: null } as DetailRefIdle, + { draft: null, done: true }, +]; + +export const detailrefCommand: Command = { + name: "detailref", + labelKey: "cmd.detailref.label", + prompt: () => "cmd.detailref.point", + accepts: () => ["point"], + options: () => [], + init: (): DetailRefIdle => ({ phase: "point", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as DetailRefState; + if (input.kind !== "point") return [s, { draft: null }]; + return [ + { phase: "point", lastPoint: null } as DetailRefIdle, + { draft: null, done: true, commit: (p) => appendDetailRef(p, input.point, ctx) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/ellipse.test.ts b/src/commands/cmds/ellipse.test.ts index 712d39e..af45fda 100644 --- a/src/commands/cmds/ellipse.test.ts +++ b/src/commands/cmds/ellipse.test.ts @@ -1,11 +1,12 @@ /** - * `ellipseCommand` — zwei Bounding-Box-Ecken → achsparallele Ellipse - * (shape:"ellipse", rotation 0). + * `ellipseCommand` — zwei Konstruktionsmethoden: Box (Default, zwei + * Bounding-Box-Ecken, rotation 0) und NEU Achse (Zentrum + Hauptachse + + * Nebenachse, beliebig gedreht). */ import { describe, it, expect } from "vitest"; import { ellipseCommand } from "./ellipse"; -import type { CommandContext, Project } from "../types"; +import type { CommandContext, CommandState, Project } from "../types"; function project(): Project { return { @@ -86,3 +87,64 @@ describe("ellipseCommand", () => { expect(next.drawings2d.length).toBe(0); }); }); + +describe("ellipseCommand — Methode Achse (gedreht)", () => { + function toAxis(): CommandState { + const [state] = ellipseCommand.onInput(ellipseCommand.init(), { kind: "option", id: "method" }, makeCtx(project())); + return state; + } + + it("Zentrum + Hauptachse (0,0)→(4,0) + Nebenachse-Punkt (0,2) → rx=4, ry=2, rotation=0", () => { + const p = project(); + const ctx = makeCtx(p); + let state = toAxis(); + [state] = ellipseCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Zentrum + [state] = ellipseCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); // Hauptachse + const [, result] = ellipseCommand.onInput(state, { kind: "point", point: { x: 0, y: 2 } }, ctx); // Nebenachse + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("ellipse"); + if (g.shape === "ellipse") { + expect(g.center).toEqual({ x: 0, y: 0 }); + expect(g.rx).toBeCloseTo(4, 6); + expect(g.ry).toBeCloseTo(2, 6); + expect(g.rotation).toBeCloseTo(0, 6); + } + }); + + it("gedrehte Hauptachse (0,0)→(0,4) (90°) + Nebenachse-Punkt → rotation=90°, ry aus senkrechtem Abstand", () => { + const p = project(); + const ctx = makeCtx(p); + let state = toAxis(); + [state] = ellipseCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = ellipseCommand.onInput(state, { kind: "point", point: { x: 0, y: 4 } }, ctx); // Achse nach oben (90°) + const [, result] = ellipseCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "ellipse") { + expect(g.rx).toBeCloseTo(4, 6); + expect(g.ry).toBeCloseTo(3, 6); + expect(g.rotation).toBeCloseTo(Math.PI / 2, 6); + } + }); + + it("degenerierte Hauptachse (Zentrum=Punkt) wird ignoriert, bleibt in Phase 'major'", () => { + const p = project(); + const ctx = makeCtx(p); + let state = toAxis(); + [state] = ellipseCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + const [after, result] = ellipseCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + expect(result.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("major"); + }); + + it("Methode zyklisch: box → axis → box", () => { + let state = ellipseCommand.init() as CommandState; + expect(ellipseCommand.options(state)[0].value).toBe("box"); + [state] = ellipseCommand.onInput(state, { kind: "option", id: "method" }, makeCtx(project())); + expect(ellipseCommand.options(state)[0].value).toBe("axis"); + [state] = ellipseCommand.onInput(state, { kind: "option", id: "method" }, makeCtx(project())); + expect(ellipseCommand.options(state)[0].value).toBe("box"); + }); +}); diff --git a/src/commands/cmds/ellipse.ts b/src/commands/cmds/ellipse.ts index 119b284..b9a5431 100644 --- a/src/commands/cmds/ellipse.ts +++ b/src/commands/cmds/ellipse.ts @@ -1,17 +1,32 @@ -// Ellipse — zwei gegenüberliegende Ecken einer Bounding-Box (achsparallel, -// wie das 2-Punkt-Rechteck). Schritte: -// 1) „Erste Ecke:" → Punkt -// 2) „Gegenüberliegende Ecke:" → Punkt → commit (shape:"ellipse", rotation 0) +// Ellipse — zwei Konstruktionsmethoden. Wählbar über die Option „Methode" +// (klickbar im Feld-Row, tippbar als „m", zyklisch — dasselbe Muster wie bei +// `rect.ts`/`circle.ts`/`arc.ts`). // -// Bewusst nur die einfache Bounding-Box-Methode (kein Dreh-Winkel über das -// Werkzeug) — `rotation` bleibt 0, das Feld existiert im Modell für spätere -// Dreh-Bearbeitung/andere Quellen (s. `model/types.ts`). +// • Box (Default, unverändert): zwei gegenüberliegende Ecken einer +// Bounding-Box, achsparallel (`rotation` bleibt 0). +// 1) „Erste Ecke:" → Punkt +// 2) „Gegenüberliegende Ecke:" → Punkt → commit +// • Achse (gedreht): Zentrum + Hauptachse + Nebenachse — beliebig gedrehte +// Ellipse. `rotation` existiert im Modell seit Langem (Rendering + +// Griff-Editieren lesen es bereits, s. `plan/generatePlan/drawing2d.ts` +// Z. 448 bzw. `projectSlice.ts` `drawingVertices`), nur die Erzeugung +// setzte es bisher immer auf 0. +// 1) „Zentrum:" → Punkt +// 2) „Hauptachse:" → Punkt (Richtung + rx = Abstand zum Zentrum) +// 3) „Nebenachse:" → Punkt (senkrechter Abstand zur Hauptachse = ry) → commit +// +// Teil-/Ellipsenbogen (a0/a1) bewusst NICHT umgesetzt — das Modell kennt +// dafür keine Felder (separate, grössere Erweiterung, analog wie circle/arc +// getrennte Shapes sind statt einer gemeinsamen mit optionaler Spanne). import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; +import { segmentHud, uniqueId } from "../../tools/types"; +import { ellipsePts } from "../../tools/curves"; import type { + CmdOption, Command, CommandContext, + CommandField, CommandResult, CommandState, DraftShape, @@ -19,19 +34,70 @@ import type { ToolDraft, Vec2, } from "../types"; -import { ellipsePts } from "../../tools/curves"; +import type { TranslationKey } from "../../i18n"; const EPS = 1e-6; -interface EllipseIdle extends CommandState { - phase: "corner1"; +/** Konstruktionsmethode. */ +type EllipseMethod = "box" | "axis"; +const METHOD_ORDER: EllipseMethod[] = ["box", "axis"]; +const nextMethod = (m: EllipseMethod): EllipseMethod => + METHOD_ORDER[(METHOD_ORDER.indexOf(m) + 1) % METHOD_ORDER.length]; +const methodOption = (m: EllipseMethod): CmdOption => ({ + id: "method", + labelKey: "cmd.ellipse.method", + value: m, +}); + +const DEG = Math.PI / 180; +const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const angleOf = (a: Vec2, b: Vec2): number => Math.atan2(b.y - a.y, b.x - a.x); +const segAngleDeg = (a: Vec2, b: Vec2): number => (angleOf(a, b) * 180) / Math.PI; + +/** Senkrechter (signierter) Abstand eines Punktes zur Achse a→b. */ +function perpDist(a: Vec2, b: Vec2, p: Vec2): number { + const len = dist(a, b); + if (len < EPS) return 0; + const dx = (b.x - a.x) / len; + const dy = (b.y - a.y) / len; + return (p.x - a.x) * -dy + (p.y - a.y) * dx; } -interface EllipseDrawing extends CommandState { + +// ── Zustand ────────────────────────────────────────────────────────────────── + +interface EllipseBoxP1 extends CommandState { + phase: "corner1"; + method: "box"; +} +interface EllipseBoxP2 extends CommandState { phase: "corner2"; + method: "box"; p0: Vec2; cursor: Vec2 | null; } -type EllipseState = EllipseIdle | EllipseDrawing; +interface EllipseAxisCenter extends CommandState { + phase: "center"; + method: "axis"; +} +interface EllipseAxisMajor extends CommandState { + phase: "major"; + method: "axis"; + center: Vec2; + cursor: Vec2 | null; +} +interface EllipseAxisMinor extends CommandState { + phase: "minor"; + method: "axis"; + center: Vec2; + major: Vec2; + cursor: Vec2 | null; +} +type EllipseState = + | EllipseBoxP1 + | EllipseBoxP2 + | EllipseAxisCenter + | EllipseAxisMajor + | EllipseAxisMinor; /** Zentrum + Halbachsen aus zwei gegenüberliegenden Bounding-Box-Ecken. */ function ellipseFromCorners(p0: Vec2, p1: Vec2): { center: Vec2; rx: number; ry: number } { @@ -42,65 +108,182 @@ function ellipseFromCorners(p0: Vec2, p1: Vec2): { center: Vec2; rx: number; ry: }; } -/** Vorschau (tessellierte Ellipse) + HUD (Breite×Höhe). */ -function ellipseDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft { - if (!cursor) return { preview: [], vertices: [p0] }; - const { center, rx, ry } = ellipseFromCorners(p0, cursor); - if (rx < EPS || ry < EPS) return { preview: [], vertices: [p0] }; - const preview: DraftShape[] = [{ kind: "poly", pts: ellipsePts(center, rx, ry, 0), closed: true }]; - return { - preview, - vertices: [p0], - hud: { at: cursor, text: `${(rx * 2).toFixed(3)}×${(ry * 2).toFixed(3)}m` }, - }; +// ── Vorschau ───────────────────────────────────────────────────────────────── + +function ellipseDraft(center: Vec2, rx: number, ry: number, rotation: number, at: Vec2 | null): ToolDraft { + if (rx < EPS || ry < EPS) return { preview: [], vertices: [center] }; + const preview: DraftShape[] = [{ kind: "poly", pts: ellipsePts(center, rx, ry, rotation), closed: true }]; + const draft: ToolDraft = { preview, vertices: [center] }; + if (at) draft.hud = { at, text: `${(rx * 2).toFixed(3)}×${(ry * 2).toFixed(3)}m` }; + return draft; } -function appendEllipse(p: Project, center: Vec2, rx: number, ry: number, ctx: CommandContext): Project { +function boxDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft { + if (!cursor) return { preview: [], vertices: [p0] }; + const { center, rx, ry } = ellipseFromCorners(p0, cursor); + return ellipseDraft(center, rx, ry, 0, cursor); +} + +function axisMajorDraft(center: Vec2, cursor: Vec2 | null): ToolDraft { + if (!cursor || dist(center, cursor) < EPS) return { preview: [], vertices: [center] }; + return { preview: [{ kind: "line", a: center, b: cursor }], vertices: [center], hud: segmentHud(center, cursor) }; +} + +function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDraft { + const rx = dist(center, major); + if (!cursor) return ellipseDraft(center, rx, 0, angleOf(center, major), null); + const ry = Math.abs(perpDist(center, major, cursor)); + return ellipseDraft(center, rx, ry, angleOf(center, major), cursor); +} + +// ── Commit ─────────────────────────────────────────────────────────────────── + +function appendEllipse( + p: Project, + center: Vec2, + rx: number, + ry: number, + rotation: number, + ctx: CommandContext, +): Project { if (rx < EPS || ry < EPS) return p; const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "ellipse", center, rx, ry, rotation: 0 }, + geom: { shape: "ellipse", center, rx, ry, rotation }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } -const idle = (): [CommandState, CommandResult] => [ - { phase: "corner1", lastPoint: null }, +const idle = (method: EllipseMethod): [CommandState, CommandResult] => [ + (method === "box" ? { phase: "corner1", method } : { phase: "center", method }) as EllipseState, { draft: null, done: true }, ]; +function promptKey(s: EllipseState): TranslationKey { + if (s.method === "box") return s.phase === "corner2" ? "cmd.ellipse.corner2" : "cmd.ellipse.corner1"; + if (s.phase === "center") return "cmd.ellipse.axisCenter"; + if (s.phase === "major") return "cmd.ellipse.major"; + return "cmd.ellipse.minor"; +} + +/** Tab-Feld des Hauptachsen-Schritts: Länge (rx) + Winkel der Achse. */ +const MAJOR_FIELDS: CommandField[] = [ + { id: "length", labelKey: "cmd.field.length" }, + { id: "angle", labelKey: "cmd.field.angle" }, +]; +/** Tab-Feld des Nebenachsen-Schritts: senkrechter Abstand (ry). */ +const MINOR_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }]; + export const ellipseCommand: Command = { name: "ellipse", labelKey: "cmd.ellipse.label", - prompt: (s) => ((s as EllipseState).phase === "corner2" ? "cmd.ellipse.corner2" : "cmd.ellipse.corner1"), - accepts: () => ["point"], - options: () => [], - init: (): EllipseIdle => ({ phase: "corner1", lastPoint: null }), + prompt: (s) => promptKey(s as EllipseState), + accepts: () => ["point", "option"], + options: (s) => [methodOption((s as EllipseState).method)], + init: (): EllipseBoxP1 => ({ phase: "corner1", method: "box", lastPoint: null }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as EllipseState; - if (input.kind !== "point") return [s, { draft: null }]; - if (s.phase !== "corner2") { - const ns: EllipseDrawing = { phase: "corner2", p0: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: ellipseDraft(input.point, null) }]; + + if (input.kind === "option") { + if (input.id === "method") return idle(nextMethod(s.method)); + return [s, { draft: null }]; } - const { center, rx, ry } = ellipseFromCorners(s.p0, input.point); + if (input.kind !== "point") return [s, { draft: null }]; + const pt = input.point; + + if (s.method === "box") { + if (s.phase !== "corner2") { + const ns: EllipseBoxP2 = { phase: "corner2", method: "box", p0: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: boxDraft(pt, pt) }]; + } + const { center, rx, ry } = ellipseFromCorners(s.p0, pt); + return [idle("box")[0], { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, 0, ctx) }]; + } + + // axis + if (s.phase === "center") { + const ns: EllipseAxisMajor = { phase: "major", method: "axis", center: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: { preview: [], vertices: [pt] } }]; + } + if (s.phase === "major") { + if (dist(s.center, pt) < EPS) return [s, { draft: null }]; + const ns: EllipseAxisMinor = { phase: "minor", method: "axis", center: s.center, major: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: axisMinorDraft(s.center, pt, null) }]; + } + // phase "minor" → committen. + const { center, major } = s; + const rx = dist(center, major); + const ry = Math.abs(perpDist(center, major, pt)); + const rotation = angleOf(center, major); return [ - { phase: "corner1", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, ctx) }, + idle("axis")[0], + { draft: null, done: true, commit: (p) => appendEllipse(p, center, rx, ry, rotation, ctx) }, ]; }, onMove: (state, point): [CommandState, CommandResult] => { const s = state as EllipseState; - if (s.phase !== "corner2") return [s, { draft: null }]; - const ns: EllipseDrawing = { ...s, cursor: point }; - return [ns, { draft: ellipseDraft(s.p0, point) }]; + if (s.method === "box") { + if (s.phase !== "corner2") return [s, { draft: null }]; + const ns: EllipseBoxP2 = { ...s, cursor: point }; + return [ns, { draft: boxDraft(s.p0, point) }]; + } + if (s.phase === "major") { + const ns: EllipseAxisMajor = { ...s, cursor: point }; + return [ns, { draft: axisMajorDraft(s.center, point) }]; + } + if (s.phase === "minor") { + const ns: EllipseAxisMinor = { ...s, cursor: point }; + return [ns, { draft: axisMinorDraft(s.center, s.major, point) }]; + } + return [s, { draft: null }]; }, - onConfirm: (): [CommandState, CommandResult] => idle(), - onCancel: (): [CommandState, CommandResult] => idle(), + onConfirm: (state): [CommandState, CommandResult] => idle((state as EllipseState).method), + onCancel: (state): [CommandState, CommandResult] => idle((state as EllipseState).method), + + fields: (state) => { + const s = state as EllipseState; + if (s.method === "axis" && s.phase === "major") return MAJOR_FIELDS; + if (s.method === "axis" && s.phase === "minor") return MINOR_FIELDS; + return []; + }, + fieldValues: (state, _locks, cursor): Record => { + const s = state as EllipseState; + if (!cursor) return {}; + if (s.method === "axis" && s.phase === "major") { + return { length: dist(s.center, cursor), angle: ((segAngleDeg(s.center, cursor) % 360) + 360) % 360 }; + } + if (s.method === "axis" && s.phase === "minor") { + return { radius: Math.abs(perpDist(s.center, s.major, cursor)) }; + } + return {}; + }, + pointFromFields: (state, locks, cursor) => { + const s = state as EllipseState; + if (s.method === "axis" && s.phase === "major") { + const ref = cursor ?? s.center; + const length = "length" in locks ? locks.length : dist(s.center, ref); + const angleDeg = "angle" in locks ? locks.angle : segAngleDeg(s.center, ref); + const ang = angleDeg * DEG; + return { x: s.center.x + Math.cos(ang) * length, y: s.center.y + Math.sin(ang) * length }; + } + if (s.method === "axis" && s.phase === "minor") { + if (!("radius" in locks)) return cursor; + const len = dist(s.center, s.major); + if (len < EPS) return cursor; + const dx = (s.major.x - s.center.x) / len; + const dy = (s.major.y - s.center.y) / len; + const sign = cursor && perpDist(s.center, s.major, cursor) < 0 ? -1 : 1; + const r = sign * Math.abs(locks.radius); + // Fusspunkt: Nebenachse ausgehend von der Mitte der Hauptachse (Zentrum), + // orthogonal zur Achsrichtung (-dy, dx). + return { x: s.center.x + -dy * r, y: s.center.y + dx * r }; + } + return null; + }, }; diff --git a/src/commands/cmds/explode.ts b/src/commands/cmds/explode.ts new file mode 100644 index 0000000..86d1517 --- /dev/null +++ b/src/commands/cmds/explode.ts @@ -0,0 +1,41 @@ +// Explode — löst die gewählten 2D-Elemente in ihre Einzelteile auf (Block → +// Teilgeometrien, Polylinie → Segmente, Rechteck → vier Linien). Sofort-Befehl +// ohne Punkt-Eingabe (wie Join/Split): wirkt auf die bestehende Auswahl. +// +// Die eigentliche Zerlegung liegt in `editors/explode.ts` — dort auch, was +// bewusst NICHT zerlegt wird (Kreis/Ellipse/Spline/Text/…): diese Elemente +// bleiben unverändert stehen, statt zu verschwinden. + +import { explodeDrawings } from "../../editors/explode"; +import type { Command, CommandContext, CommandResult, CommandSelection, CommandState } from "../types"; + +/** Gewählte 2D-Elemente (Mehrfachauswahl bevorzugt). */ +function selectedDrawingIds(sel: CommandSelection): string[] { + if (sel.drawingIds && sel.drawingIds.length) return sel.drawingIds; + return sel.drawingId ? [sel.drawingId] : []; +} + +const done = (): [CommandState, CommandResult] => [ + { phase: "idle", lastPoint: null }, + { draft: null, done: true }, +]; + +export const explodeCommand: Command = { + name: "explode", + labelKey: "cmd.explode.label", + prompt: () => "cmd.explode.label", + accepts: () => [], + options: () => [], + init: (): CommandState => ({ phase: "idle", lastPoint: null }), + + autoRun: (ctx: CommandContext): CommandResult => { + const ids = selectedDrawingIds(ctx.selection); + if (ids.length === 0) return { draft: null, done: true }; + return { draft: null, done: true, commit: (p) => explodeDrawings(p, ids) }; + }, + + onInput: (): [CommandState, CommandResult] => done(), + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: (): [CommandState, CommandResult] => done(), + onCancel: (): [CommandState, CommandResult] => done(), +}; diff --git a/src/commands/cmds/leader.test.ts b/src/commands/cmds/leader.test.ts index c291756..95bd3f9 100644 --- a/src/commands/cmds/leader.test.ts +++ b/src/commands/cmds/leader.test.ts @@ -1,11 +1,13 @@ /** * `leaderCommand` — Zielpunkt + Textanker → leeres `text`-Element mit * `leaderTarget` gesetzt, meldet `focusDrawingId` (öffnet den Inline-Editor). + * Nutzer-Wunsch „kein Knick-Punkt wie bei AutoCADs Multileader": optionale + * Knickpunkte über die Option „bends" (Default 0 = unverändertes Verhalten). */ import { describe, it, expect } from "vitest"; import { leaderCommand } from "./leader"; -import type { CommandContext, Project } from "../types"; +import type { CommandContext, CommandState, Project } from "../types"; function project(): Project { return { @@ -70,3 +72,59 @@ describe("leaderCommand", () => { expect(next.drawings2d[0].id).toBe(result.focusDrawingId); }); }); + +/** Zyklt die "bends"-Option, bis der gewünschte Wert erreicht ist (unabhängig + * vom aktuellen Stand — Option ist ein persistentes Modul-Singleton, s. + * `lastBendCount`, dasselbe Muster wie `lastCount` bei Array). */ +function setBends(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + for (let i = 0; i <= 4; i++) { + if (leaderCommand.options(s)[0].value === String(target)) return s; + [s] = leaderCommand.onInput(s, { kind: "option", id: "bends" }, ctx); + } + return s; +} + +describe("leaderCommand — Knickpunkte (Multileader-Stil)", () => { + it("Default (0 Knicke): keine leaderBendPoints im committeten Element", () => { + const p = project(); + const ctx = makeCtx(p); + const state = setBends(leaderCommand.init(), ctx, 0); + const [afterTarget] = leaderCommand.onInput(state, { kind: "point", point: { x: 10, y: 10 } }, ctx); + const [, result] = leaderCommand.onInput(afterTarget, { kind: "point", point: { x: 2, y: 2 } }, ctx); + const g = result.commit!(p).drawings2d[0].geom; + if (g.shape === "text") expect(g.leaderBendPoints).toBeUndefined(); + }); + + it("1 Knick: Ziel → Knick → Anker committet leaderTarget UND leaderBendPoints", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setBends(leaderCommand.init(), ctx, 1); + [state] = leaderCommand.onInput(state, { kind: "point", point: { x: 10, y: 10 } }, ctx); // Ziel + expect(leaderCommand.prompt(state)).toBe("cmd.leader.bend"); + [state] = leaderCommand.onInput(state, { kind: "point", point: { x: 6, y: 8 } }, ctx); // Knick + expect(leaderCommand.prompt(state)).toBe("cmd.leader.anchor"); + const [, result] = leaderCommand.onInput(state, { kind: "point", point: { x: 2, y: 2 } }, ctx); // Anker + const g = result.commit!(p).drawings2d[0].geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.at).toEqual({ x: 2, y: 2 }); + expect(g.leaderTarget).toEqual({ x: 10, y: 10 }); + expect(g.leaderBendPoints).toEqual([{ x: 6, y: 8 }]); + } + }); + + it("2 Knicke: beide Punkte landen in leaderBendPoints, in Klick-Reihenfolge", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setBends(leaderCommand.init(), ctx, 2); + [state] = leaderCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Ziel + [state] = leaderCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); // Knick 1 + [state] = leaderCommand.onInput(state, { kind: "point", point: { x: 2, y: 1 } }, ctx); // Knick 2 + const [, result] = leaderCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); // Anker + const g = result.commit!(p).drawings2d[0].geom; + if (g.shape === "text") { + expect(g.leaderBendPoints).toEqual([{ x: 1, y: 1 }, { x: 2, y: 1 }]); + } + }); +}); diff --git a/src/commands/cmds/leader.ts b/src/commands/cmds/leader.ts index 3b3eb4d..635fdb6 100644 --- a/src/commands/cmds/leader.ts +++ b/src/commands/cmds/leader.ts @@ -1,14 +1,22 @@ // Leader (Legenden-/Vorführungspfeil) — wie `text`, aber mit vorangestelltem -// Zielpunkt: Schritte: -// 1) „Zielpunkt:" → Punkt (Pfeilspitze, zeigt auf das referenzierte Detail) -// 2) „Textanker:" → Punkt (Textposition) -// Committet SOFORT ein leeres Text-Element mit `leaderTarget` gesetzt und -// meldet `focusDrawingId` — dieselbe Inline-Editor-Infrastruktur wie beim -// `text`-Befehl (kein neuer Shape, s. `Drawing2DGeom["text"].leaderTarget`). +// Zielpunkt UND optionalen Knickpunkten dazwischen (Nutzer-Wunsch: „Hinweis- +// linie hat nur EIN Segment, kein Knick-Punkt wie bei AutoCADs Multileader"). +// Anzahl Knicke über die Option „Knicke" (klickbar im Feld-Row, tippbar als +// „k", zyklisch 0..4 — Default 0 = EXAKT das bisherige Verhalten, zwei Klicks, +// keine Verhaltensänderung für den Normalfall). +// +// 1) „Zielpunkt:" → Punkt (Pfeilspitze, zeigt auf das referenzierte Detail) +// 2) „Knick N/M:" → Punkt, je Knick EINMAL (nur wenn „Knicke" > 0) +// 3) „Textanker:" → Punkt (Textposition) +// Committet SOFORT ein leeres Text-Element mit `leaderTarget` (+ ggf. +// `leaderBendPoints`) gesetzt und meldet `focusDrawingId` — dieselbe +// Inline-Editor-Infrastruktur wie beim `text`-Befehl (kein neuer Shape, +// s. `Drawing2DGeom["text"].leaderTarget`/`.leaderBendPoints`). import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; import type { + CmdOption, Command, CommandContext, CommandResult, @@ -18,27 +26,55 @@ import type { ToolDraft, Vec2, } from "../types"; +import type { TranslationKey } from "../../i18n"; const DEFAULT_TEXT_HEIGHT_M = 0.25; -const EPS = 1e-6; +const MAX_BENDS = 4; + +/** Persistente Knick-Anzahl über Aufrufe hinweg (wie `lastCount` bei Array). */ +let lastBendCount = 0; + +const BEND_OPTION: CmdOption = { id: "bends", labelKey: "cmd.leader.bends" }; interface LeaderTarget extends CommandState { phase: "target"; } +interface LeaderBend extends CommandState { + phase: "bend"; + target: Vec2; + bends: Vec2[]; + cursor: Vec2 | null; +} interface LeaderAnchor extends CommandState { phase: "anchor"; target: Vec2; + bends: Vec2[]; cursor: Vec2 | null; } -type LeaderState = LeaderTarget | LeaderAnchor; +type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor; -function appendEmptyLeaderText(p: Project, id: string, at: Vec2, target: Vec2, ctx: CommandContext): Project { +function appendLeaderText( + p: Project, + id: string, + at: Vec2, + target: Vec2, + bends: Vec2[], + ctx: CommandContext, +): Project { const d: Drawing2D = { id, type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, leaderTarget: target }, + geom: { + shape: "text", + at, + text: "", + height: DEFAULT_TEXT_HEIGHT_M, + angle: 0, + leaderTarget: target, + ...(bends.length > 0 ? { leaderBendPoints: bends } : {}), + }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } @@ -48,38 +84,66 @@ const idle = (): [CommandState, CommandResult] => [ { draft: null, done: true }, ]; -function anchorDraft(target: Vec2, cursor: Vec2 | null): ToolDraft { - if (!cursor || Math.hypot(cursor.x - target.x, cursor.y - target.y) < EPS) { - return { preview: [], vertices: [target] }; - } - const preview: DraftShape[] = [{ kind: "line", a: cursor, b: target }]; +/** Vorschau: der bisherige Pfad (Zielpunkt → platzierte Knicke) + Gummiband zum Cursor. */ +function pathDraft(target: Vec2, bends: Vec2[], cursor: Vec2 | null): ToolDraft { + const pts = [target, ...bends, ...(cursor ? [cursor] : [])]; + if (pts.length < 2) return { preview: [], vertices: [target] }; + const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }]; return { preview, vertices: [target] }; } +function promptKey(s: LeaderState): TranslationKey { + if (s.phase === "bend") return "cmd.leader.bend"; + if (s.phase === "anchor") return "cmd.leader.anchor"; + return "cmd.leader.target"; +} + export const leaderCommand: Command = { name: "leader", labelKey: "cmd.leader.label", - prompt: (s) => ((s as LeaderState).phase === "anchor" ? "cmd.leader.anchor" : "cmd.leader.target"), - accepts: () => ["point"], - options: () => [], + prompt: (s) => promptKey(s as LeaderState), + accepts: () => ["point", "option"], + options: () => [{ ...BEND_OPTION, value: String(lastBendCount) }], init: (): LeaderTarget => ({ phase: "target", lastPoint: null }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as LeaderState; - if (input.kind !== "point") return [s, { draft: null }]; - if (s.phase !== "anchor") { - const next: LeaderAnchor = { phase: "anchor", target: input.point, cursor: input.point, lastPoint: input.point }; - return [next, { draft: anchorDraft(input.point, input.point) }]; + + if (input.kind === "option") { + if (input.id === "bends") lastBendCount = (lastBendCount + 1) % (MAX_BENDS + 1); + return [s, { draft: null }]; } + if (input.kind !== "point") return [s, { draft: null }]; + const pt = input.point; + + if (s.phase === "target") { + if (lastBendCount > 0) { + const next: LeaderBend = { phase: "bend", target: pt, bends: [], cursor: pt, lastPoint: pt }; + return [next, { draft: pathDraft(pt, [], pt) }]; + } + const next: LeaderAnchor = { phase: "anchor", target: pt, bends: [], cursor: pt, lastPoint: pt }; + return [next, { draft: pathDraft(pt, [], pt) }]; + } + + if (s.phase === "bend") { + const bends = [...s.bends, pt]; + if (bends.length < lastBendCount) { + const next: LeaderBend = { phase: "bend", target: s.target, bends, cursor: pt, lastPoint: pt }; + return [next, { draft: pathDraft(s.target, bends, pt) }]; + } + const next: LeaderAnchor = { phase: "anchor", target: s.target, bends, cursor: pt, lastPoint: pt }; + return [next, { draft: pathDraft(s.target, bends, pt) }]; + } + + // phase "anchor": Textposition setzen, Leader committen. const id = uniqueId("dr2d"); - const at = input.point; - const target = s.target; + const { target, bends } = s; return [ idle()[0], { draft: null, done: true, - commit: (p) => appendEmptyLeaderText(p, id, at, target, ctx), + commit: (p) => appendLeaderText(p, id, pt, target, bends, ctx), focusDrawingId: id, }, ]; @@ -87,9 +151,8 @@ export const leaderCommand: Command = { onMove: (state, point): [CommandState, CommandResult] => { const s = state as LeaderState; - if (s.phase !== "anchor") return [s, { draft: null }]; - const ns: LeaderAnchor = { ...s, cursor: point }; - return [ns, { draft: anchorDraft(s.target, point) }]; + if (s.phase === "target") return [s, { draft: null }]; + return [{ ...s, cursor: point } as LeaderState, { draft: pathDraft(s.target, s.bends, point) }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), diff --git a/src/commands/cmds/line.test.ts b/src/commands/cmds/line.test.ts index 6aa0122..9df379d 100644 --- a/src/commands/cmds/line.test.ts +++ b/src/commands/cmds/line.test.ts @@ -85,3 +85,64 @@ describe("lineCommand — Cursor-HUD (Länge/Winkel)", () => { expect(res.draft).toBeNull(); }); }); + +describe("lineCommand — durchgehendes Verketten", () => { + it("committet JEDES Segment einzeln, der Befehl bleibt zwischendurch aktiv (kein done)", () => { + const p = project(); + const ctx = makeCtx(null); + let state = lineCommand.init(); + [state] = lineCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [afterSeg1, res1] = lineCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); + expect(res1.done).toBeFalsy(); + expect(res1.commit).toBeDefined(); + let next = res1.commit!(p); + expect(next.drawings2d.length).toBe(1); + + // Zweites Segment startet dort, wo das erste endete (3,0) — kein neuer Klick auf den Start nötig. + const [, res2] = lineCommand.onInput(afterSeg1, { kind: "point", point: { x: 3, y: 5 } }, ctx); + expect(res2.done).toBeFalsy(); + next = res2.commit!(next); + expect(next.drawings2d.length).toBe(2); + const g1 = next.drawings2d[0].geom; + const g2 = next.drawings2d[1].geom; + expect(g1.shape).toBe("line"); + expect(g2.shape).toBe("line"); + if (g1.shape === "line" && g2.shape === "line") { + expect(g1.a).toEqual({ x: 0, y: 0 }); + expect(g1.b).toEqual({ x: 3, y: 0 }); + // Zweites Segment knüpft am Endpunkt des ersten an. + expect(g2.a).toEqual({ x: 3, y: 0 }); + expect(g2.b).toEqual({ x: 3, y: 5 }); + } + }); + + it("Klick auf denselben Punkt (Nulllänge) wird ignoriert, Kette bleibt aktiv", () => { + const ctx = makeCtx(null); + let state = lineCommand.init(); + [state] = lineCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + const [after, res] = lineCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + expect(res.commit).toBeUndefined(); + expect(res.done).toBeFalsy(); + expect((after as { phase: string }).phase).toBe("end"); + }); + + it("Enter (onConfirm) beendet die Kette ohne abschliessendes Segment zum Cursor", () => { + const ctx = makeCtx(null); + let state = lineCommand.init(); + [state] = lineCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = lineCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); + const [after, res] = lineCommand.onConfirm(state, ctx); + expect(res.done).toBe(true); + expect(res.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("start"); + }); + + it("Escape (onCancel) beendet die Kette ebenso", () => { + const ctx = makeCtx(null); + let state = lineCommand.init(); + [state] = lineCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [after, res] = lineCommand.onCancel(state); + expect(res.done).toBe(true); + expect((after as { phase: string }).phase).toBe("start"); + }); +}); diff --git a/src/commands/cmds/line.ts b/src/commands/cmds/line.ts index a8af1cf..ffd2212 100644 --- a/src/commands/cmds/line.ts +++ b/src/commands/cmds/line.ts @@ -1,9 +1,24 @@ // Line — erster Befehl der Command-Engine (portiert lineTool aus // src/tools/tools.ts). Zwei Punkte → Drawing2D{shape:"line"}. // +// Durchgehendes Verketten (Nutzer-Wunsch: „genau EIN Segment pro Aufruf, +// kein durchgehendes Verketten mehrerer EINZEL-Linien in einer Geste — nur +// `polyline` bietet Mehrpunkt-Zug, aber als EIN zusammenhängendes Objekt +// statt N Linien"): nach dem zweiten Klick committet die Linie WIE BISHER +// (eigenständiges `Drawing2D{shape:"line"}`), der Befehl bleibt aber aktiv +// (`done` NICHT gesetzt) — der eben gesetzte Endpunkt wird sofort zum +// Startpunkt des nächsten Segments. Jedes Segment ist damit ein SEPARATES +// Element (anders als `polyline`, absichtlich — z. B. für Elemente, die +// später einzeln verschoben/gelöscht werden sollen). Enter/Rechtsklick/Esc +// beendet die Kette (kein abschliessendes Segment zum Cursor). Ein Klick auf +// denselben Punkt (Nulllänge) wird ignoriert statt die Kette zu beenden — +// anders als früher, wo ein solcher Klick den GESAMTEN (Einzel-)Befehl +// verwarf; das ergäbe bei einer laufenden Kette eine Überraschung. +// // Schritte: // 1) „Start of line:" → Punkt (Klick ODER getippt: 0,0 / r3,0 / 3<45) -// 2) „End of line:" → Punkt → commit Drawing2D line → done +// 2) „End of line:" → Punkt → commit Drawing2D line, Kette geht weiter +// (Enter/Rechtsklick/Esc beendet) // // Akzeptiert in JEDEM Punkt-Schritt sowohl Maus-Picks (gesnappt) als auch // getippte Koordinaten — das ist die Kern-Vereinheitlichung gegenüber dem alten @@ -95,15 +110,14 @@ export const lineCommand: Command = { const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; return [next, { draft: lineDraft(pt, pt) }]; } - // Zweiter Punkt: Null-Strecke verwerfen, sonst committen. + // Nächster Punkt: Null-Strecke ignorieren (Klick abgeprallt/Doppelklick), + // ansonsten committen und die Kette am eben gesetzten Endpunkt fortsetzen. if (segLen(s.a, pt) < EPS) { - return [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; + return [s, { draft: lineDraft(s.a, s.cursor) }]; } const a = s.a; - return [ - { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: (p) => appendLine(p, a, pt, ctx) }, - ]; + const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; + return [next, { draft: lineDraft(pt, pt), commit: (p) => appendLine(p, a, pt, ctx) }]; }, onMove: (state, point): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/mirror.ts b/src/commands/cmds/mirror.ts index ba79f84..73b0c51 100644 --- a/src/commands/cmds/mirror.ts +++ b/src/commands/cmds/mirror.ts @@ -12,8 +12,7 @@ // hängt das Spiegelbild als KOPIE an (das Original bleibt stehen). Das ist das // klassische Mirror „Kopie spiegeln" (Rhino/Vectorworks-Default). -import { commitTransform } from "../../tools/transform"; -import type { TransformSelection } from "../../tools/transform"; +import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -30,28 +29,6 @@ const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; const EPS = 1e-6; -/** Hat die Auswahl überhaupt etwas Spiegelbares? */ -function hasSelection(sel: CommandSelection): boolean { - return ( - sel.wallIds.length > 0 || - sel.drawingId !== null || - (sel.drawingIds?.length ?? 0) > 0 || - !!sel.extrudedSolidId || - !!sel.columnId - ); -} - -/** Auswahl → TransformSelection (gleiche Form). */ -function toTransformSel(sel: CommandSelection): TransformSelection { - return { - wallIds: sel.wallIds, - drawingId: sel.drawingId, - drawingIds: sel.drawingIds, - extrudedSolidId: sel.extrudedSolidId, - columnId: sel.columnId, - }; -} - // Zustand: erst ersten Achsenpunkt setzen, dann den zweiten (mit Auswahl-Snapshot). interface MirrorFirst extends CommandState { phase: "first"; @@ -122,7 +99,7 @@ export const mirrorCommand: Command = { const s = state as MirrorState; if (s.phase === "done") return idle(); // Leere Auswahl → nichts zu spiegeln (No-op + Hinweis, dann beenden). - if (!hasSelection(ctx.selection)) { + if (!hasTransformSelection(ctx.selection)) { return [{ phase: "done", lastPoint: null } as MirrorDone, { draft: null, done: true }]; } if (input.kind !== "point") { diff --git a/src/commands/cmds/move.ts b/src/commands/cmds/move.ts index f4214e9..3b82d41 100644 --- a/src/commands/cmds/move.ts +++ b/src/commands/cmds/move.ts @@ -13,8 +13,7 @@ // mode:"move") statt eine zweite Verschiebe-Logik zu duplizieren — er bewegt // Wände UND alle 2D-Formen immutabel an die Endlage. -import { commitTransform } from "../../tools/transform"; -import type { TransformSelection } from "../../tools/transform"; +import { commitTransform, hasTransformSelection, toTransformSel } from "../../tools/transform"; import { transformPreview } from "../../tools/transform"; import type { Command, @@ -47,28 +46,6 @@ function targetFromFields(base: Vec2, locks: Record, cursor: Vec return { x: base.x + Math.cos(ang) * length, y: base.y + Math.sin(ang) * length }; } -/** Hat die Auswahl überhaupt etwas Verschiebbares? */ -function hasSelection(sel: CommandSelection): boolean { - return ( - sel.wallIds.length > 0 || - sel.drawingId !== null || - (sel.drawingIds?.length ?? 0) > 0 || - !!sel.extrudedSolidId || - !!sel.columnId - ); -} - -/** Auswahl → TransformSelection (gleiche Form). */ -function toTransformSel(sel: CommandSelection): TransformSelection { - return { - wallIds: sel.wallIds, - drawingId: sel.drawingId, - drawingIds: sel.drawingIds, - extrudedSolidId: sel.extrudedSolidId, - columnId: sel.columnId, - }; -} - // Zustand: erst Basispunkt setzen, dann Ziel (mit Auswahl-Snapshot vom Start). interface MoveBase extends CommandState { phase: "base"; @@ -139,7 +116,7 @@ export const moveCommand: Command = { const s = state as MoveState; if (s.phase === "done") return idle(); // Leere Auswahl → nichts zu verschieben (No-op + Hinweis, dann beenden). - if (!hasSelection(ctx.selection)) { + if (!hasTransformSelection(ctx.selection)) { return [{ phase: "done", lastPoint: null } as MoveDone, { draft: null, done: true }]; } if (input.kind !== "point") { diff --git a/src/commands/cmds/pointmarker.test.ts b/src/commands/cmds/pointmarker.test.ts new file mode 100644 index 0000000..6c48add --- /dev/null +++ b/src/commands/cmds/pointmarker.test.ts @@ -0,0 +1,86 @@ +/** + * `pointmarkerCommand` — ein Klick → `shape:"pointmarker"` an genau diesem + * Punkt (kein Label, keine weiteren Felder, s. Kopfkommentar in + * `pointmarker.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { pointmarkerCommand } from "./pointmarker"; +import type { CommandContext, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("pointmarkerCommand", () => { + it("ein Klick committet shape:'pointmarker' an genau diesem Punkt", () => { + const p = project(); + const ctx = makeCtx(p); + const [, result] = pointmarkerCommand.onInput( + pointmarkerCommand.init(), + { kind: "point", point: { x: 4, y: 2 } }, + ctx, + ); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("pointmarker"); + if (g.shape === "pointmarker") { + expect(g.at).toEqual({ x: 4, y: 2 }); + } + }); + + it("jeder weitere Klick platziert ein WEITERES, unabhängiges Symbol", () => { + const p = project(); + const ctx = makeCtx(p); + const [, r1] = pointmarkerCommand.onInput(pointmarkerCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + let next = r1.commit!(p); + const [, r2] = pointmarkerCommand.onInput(pointmarkerCommand.init(), { kind: "point", point: { x: 5, y: 5 } }, ctx); + next = r2.commit!(next); + expect(next.drawings2d.length).toBe(2); + expect(next.drawings2d[0].id).not.toBe(next.drawings2d[1].id); + }); + + it("onConfirm/onCancel kehren in den Ruhezustand zurück (kein Commit)", () => { + const ctx = makeCtx(project()); + const [, res1] = pointmarkerCommand.onConfirm(pointmarkerCommand.init(), ctx); + expect(res1.commit).toBeUndefined(); + expect(res1.done).toBe(true); + const [, res2] = pointmarkerCommand.onCancel(pointmarkerCommand.init()); + expect(res2.commit).toBeUndefined(); + expect(res2.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/pointmarker.ts b/src/commands/cmds/pointmarker.ts new file mode 100644 index 0000000..963d73e --- /dev/null +++ b/src/commands/cmds/pointmarker.ts @@ -0,0 +1,78 @@ +// Punkt-/Knotenmarker (Nutzer-Wunsch: „Punkt-/Knotenmarker" aus der +// Werkzeug-Lücken-Liste). Einfachster aller Zeichen-Befehle: EIN Klick → +// Kreuz-in-Kreis-Symbol an genau dieser Stelle, keine weiteren Felder +// (analog `detailref.ts`, aber ohne Label/Blattverknüpfung). + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (drawing2d.ts) +const PREVIEW_CROSS = 0.12; + +interface PointMarkerIdle extends CommandState { + phase: "point"; +} +type PointMarkerState = PointMarkerIdle; + +function pointDraft(at: Vec2): ToolDraft { + const N = 32; + const pts: Vec2[] = []; + for (let i = 0; i < N; i++) { + const t = (i / N) * Math.PI * 2; + pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) }); + } + const preview: DraftShape[] = [ + { kind: "poly", pts, closed: true }, + { kind: "line", a: { x: at.x - PREVIEW_CROSS, y: at.y }, b: { x: at.x + PREVIEW_CROSS, y: at.y } }, + { kind: "line", a: { x: at.x, y: at.y - PREVIEW_CROSS }, b: { x: at.x, y: at.y + PREVIEW_CROSS } }, + ]; + return { preview, vertices: [at] }; +} + +function appendPointMarker(p: Project, at: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "pointmarker", at }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "point", lastPoint: null } as PointMarkerIdle, + { draft: null, done: true }, +]; + +export const pointmarkerCommand: Command = { + name: "pointmarker", + labelKey: "cmd.pointmarker.label", + prompt: () => "cmd.pointmarker.point", + accepts: () => ["point"], + options: () => [], + init: (): PointMarkerIdle => ({ phase: "point", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as PointMarkerState; + if (input.kind !== "point") return [s, { draft: null }]; + return [ + { phase: "point", lastPoint: null } as PointMarkerIdle, + { draft: null, done: true, commit: (p) => appendPointMarker(p, input.point, ctx) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/polygon.test.ts b/src/commands/cmds/polygon.test.ts index f75bb89..e67f444 100644 --- a/src/commands/cmds/polygon.test.ts +++ b/src/commands/cmds/polygon.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect } from "vitest"; import { polygonCommand } from "./polygon"; -import type { CommandContext, Project } from "../types"; +import type { CommandContext, CommandState, Project } from "../types"; function project(): Project { return { @@ -84,16 +84,14 @@ describe("polygonCommand", () => { ctx, ); // Von Default 6 hoch bis 12, dann Wrap auf 3. - let opts = polygonCommand.options(state); - expect(opts[0].value).toBe("6"); + const sidesValue = () => polygonCommand.options(state).find((o) => o.id === "sides")?.value; + expect(sidesValue()).toBe("6"); for (let i = 0; i < 6; i++) { [state] = polygonCommand.onInput(state, { kind: "option", id: "sides" }, ctx); } - opts = polygonCommand.options(state); - expect(opts[0].value).toBe("12"); + expect(sidesValue()).toBe("12"); [state] = polygonCommand.onInput(state, { kind: "option", id: "sides" }, ctx); - opts = polygonCommand.options(state); - expect(opts[0].value).toBe("3"); + expect(sidesValue()).toBe("3"); const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); const next = result.commit!(p); @@ -118,3 +116,167 @@ describe("polygonCommand", () => { expect(next.drawings2d.length).toBe(0); }); }); + +/** Treibt die „mode"-Option auf den Ziel-Wert, unabhängig vom aktuellen Modul-Zustand + * (`lastMode` ist ein Modul-Singleton, s. Leader/Array-Tests für dasselbe Muster). */ +function setMode(state: CommandState, ctx: CommandContext, target: "insc" | "circ"): CommandState { + let s = state; + let opts = polygonCommand.options(s); + while (opts.find((o) => o.id === "mode")?.value !== target) { + [s] = polygonCommand.onInput(s, { kind: "option", id: "mode" }, ctx); + opts = polygonCommand.options(s); + } + return s; +} + +/** Treibt die „sides"-Option auf den Ziel-Wert (`lastSides` ist ebenfalls ein + * Modul-Singleton — die vorherige Beschreibung „Ecken-Zahl…" lässt ihn bei 3 + * stehen, andere Tests hier dürfen sich darauf nicht verlassen). */ +function setSides(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + let opts = polygonCommand.options(s); + while (opts.find((o) => o.id === "sides")?.value !== String(target)) { + [s] = polygonCommand.onInput(s, { kind: "option", id: "sides" }, ctx); + opts = polygonCommand.options(s); + } + return s; +} + +describe("polygonCommand — Modus eingeschrieben/umschrieben", () => { + it("Default ist 'eingeschrieben' (insc) — Eckpunkte liegen exakt auf dem Klick-Radius", () => { + const p = project(); + const ctx = makeCtx(p); + const [state] = polygonCommand.onInput(polygonCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + expect(polygonCommand.options(state).find((o) => o.id === "mode")?.value).toBe("insc"); + }); + + it("Modus zyklt insc → circ → insc", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = polygonCommand.onInput(polygonCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + state = setMode(state, ctx, "circ"); + expect(polygonCommand.options(state).find((o) => o.id === "mode")?.value).toBe("circ"); + state = setMode(state, ctx, "insc"); + expect(polygonCommand.options(state).find((o) => o.id === "mode")?.value).toBe("insc"); + }); + + it("umschrieben: der Eckpunkt-Radius ist GRÖSSER als der eingegebene Radius (Apothema)", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = polygonCommand.onInput(polygonCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + state = setMode(state, ctx, "circ"); + state = setSides(state, ctx, 6); + // 6 Ecken (Default), Apothema = 5 → Eckpunkt-Radius = 5 / cos(30°) ≈ 5.7735. + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 5, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") { + expect(g.pts.length).toBe(6); + const r = Math.hypot(g.pts[0].x, g.pts[0].y); + expect(r).toBeCloseTo(5 / Math.cos(Math.PI / 6), 6); + // Die Kantenmitte (Mittelwert zweier benachbarter Ecken) liegt auf dem + // eingegebenen Apothema-Radius (5) — das definiert „umschrieben". + const midEdge = { x: (g.pts[0].x + g.pts[1].x) / 2, y: (g.pts[0].y + g.pts[1].y) / 2 }; + expect(Math.hypot(midEdge.x, midEdge.y)).toBeCloseTo(5, 6); + } + }); + + it("eingeschrieben (explizit gesetzt): Eckpunkt-Radius = eingegebener Radius, unverändert", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = polygonCommand.onInput(polygonCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + state = setMode(state, ctx, "insc"); + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 5, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") { + for (const pt of g.pts) expect(Math.hypot(pt.x, pt.y)).toBeCloseTo(5, 6); + } + }); +}); + +/** Treibt die „construct"-Option auf den Ziel-Wert (Modul-Singleton `lastMethod`, + * dasselbe Muster wie `setMode`/`setSides`). */ +function setConstruct(state: CommandState, ctx: CommandContext, target: "center" | "edge"): CommandState { + let s = state; + let opts = polygonCommand.options(s); + while (opts.find((o) => o.id === "construct")?.value !== target) { + [s] = polygonCommand.onInput(s, { kind: "option", id: "construct" }, ctx); + opts = polygonCommand.options(s); + } + return s; +} + +describe("polygonCommand — Konstruktion 'Kante' (zwei Punkte legen eine Kante fest)", () => { + it("Default-Konstruktion ist 'center'", () => { + expect(polygonCommand.options(polygonCommand.init()).find((o) => o.id === "construct")?.value).toBe( + "center", + ); + }); + + it("Konstruktion zyklt center → edge → center", () => { + const ctx = makeCtx(project()); + let state = setConstruct(polygonCommand.init(), ctx, "edge"); + expect(polygonCommand.options(state).find((o) => o.id === "construct")?.value).toBe("edge"); + state = setConstruct(state, ctx, "center"); + expect(polygonCommand.options(state).find((o) => o.id === "construct")?.value).toBe("center"); + }); + + it("Quadrat (4 Ecken) aus einer horizontalen Kante (0,0)→(2,0): alle 4 Seiten gleich lang, rechte Winkel", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setConstruct(polygonCommand.init(), ctx, "edge"); + state = setSides(state, ctx, 4); + [state] = polygonCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 2, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + expect(g.pts.length).toBe(4); + expect(g.pts[0]).toEqual({ x: 0, y: 0 }); + expect(g.pts[1]).toEqual({ x: 2, y: 0 }); + // Alle vier Kanten exakt Länge 2 (Quadrat), links von der Kante 0→1 abbiegend. + for (let i = 0; i < 4; i++) { + expect(dist(g.pts[i], g.pts[(i + 1) % 4])).toBeCloseTo(2, 6); + } + expect(g.pts[2].y).toBeGreaterThan(0); // links von (0,0)→(2,0) = +Y-Seite + } + }); + + it("gleichseitiges Dreieck (3 Ecken) aus einer Kante — dritte Ecke exakt auf der Mittelsenkrechten", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setConstruct(polygonCommand.init(), ctx, "edge"); + state = setSides(state, ctx, 3); + [state] = polygonCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 2, y: 0 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") { + expect(g.pts.length).toBe(3); + const apex = g.pts[2]; + expect(apex.x).toBeCloseTo(1, 6); // Mittelsenkrechte von (0,0)-(2,0) + expect(apex.y).toBeCloseTo(Math.sqrt(3), 6); // Höhe eines gleichseitigen Δ mit Seite 2 + } + }); + + it("Klick auf denselben Punkt (Nulllänge) wird ignoriert, bleibt in Phase 'edge2'", () => { + const ctx = makeCtx(project()); + let state = setConstruct(polygonCommand.init(), ctx, "edge"); + [state] = polygonCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + const [after, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 1, y: 1 } }, ctx); + expect(result.commit).toBeUndefined(); + expect((after as { phase: string }).phase).toBe("edge2"); + }); + + it("Wechsel zurück auf 'center' funktioniert nach einer Kanten-Konstruktion weiterhin normal", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setConstruct(polygonCommand.init(), ctx, "center"); + [state] = polygonCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = polygonCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); + const next = result.commit!(p); + expect(next.drawings2d[0].geom.shape).toBe("polyline"); + }); +}); diff --git a/src/commands/cmds/polygon.ts b/src/commands/cmds/polygon.ts index 8ee2a4e..e9011b7 100644 --- a/src/commands/cmds/polygon.ts +++ b/src/commands/cmds/polygon.ts @@ -1,14 +1,32 @@ -// Regelmässiges Vieleck — Mittelpunkt + Radius (umschriebener Kreis), Anzahl -// Ecken zyklt über eine Inline-Option (3..12, Default 6), analog zum -// `count`-Zyklus bei Multiline. Committet als geschlossene `polyline` — kein -// neuer Shape-Typ nötig, erbt dadurch Rendering/Snapping/Griffe/Export -// komplett vom bestehenden Polylinien-Pfad. Schritte: -// 1) „Mittelpunkt:" → Punkt -// 2) „Radius:" → Punkt (Abstand+Richtung des ersten Eckpunkts) ODER -// getippte Zahl (Radius, Richtung +X) → commit. Ecken-Zahl per Option. +// Regelmässiges Vieleck — Mittelpunkt + Radius, Anzahl Ecken zyklt über eine +// Inline-Option (3..12, Default 6, analog zum `count`-Zyklus bei Multiline), +// eine zweite Option „Modus" (eingeschrieben/umschrieben, analog AutoCADs +// POLYGON-Befehl): +// • Eingeschrieben (Default): Radius = Zentrum→Eckpunkt (die Eckpunkte +// liegen AUF dem Radius-Kreis, das Vieleck liegt IM Kreis). +// • Umschrieben: Radius = Zentrum→Kantenmitte (Apothema) — das Vieleck +// liegt UM den Radius-Kreis, jede Kante berührt ihn mittig. Umrechnung +// auf den tatsächlichen Eckpunkt-Radius über `r / cos(π/n)`. +// UND eine dritte Option „Konstruktion" (Zentrum/Kante, ebenfalls analog +// AutoCADs POLYGON „Edge"-Option): +// • Zentrum (Default): wie oben, Mittelpunkt + Radius. +// • Kante: zwei Punkte definieren EINE Kante direkt — das Vieleck wird +// davon ausgehend aufgebaut (nach links abbiegend, Aussenwinkel 2π/n je +// Ecke — ein konvexes, CCW aufgebautes Vieleck). „Modus" ist hier +// irrelevant (die Kante legt die Grösse schon eindeutig fest) und wird +// ausgeblendet. +// Committet als geschlossene `polyline` — kein neuer Shape-Typ nötig, erbt +// dadurch Rendering/Snapping/Griffe/Export komplett vom bestehenden +// Polylinien-Pfad. Schritte: +// • Zentrum: 1) „Mittelpunkt:" → Punkt +// 2) „Radius:" → Punkt (Abstand+Richtung des ersten Eckpunkts) +// ODER getippte Zahl (Radius, Richtung +X) → commit. +// • Kante: 1) „Erster Kantenpunkt:" → Punkt +// 2) „Zweiter Kantenpunkt:" → Punkt → commit. +// Ecken-Zahl/Modus/Konstruktion per Option. import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; +import { segmentHud, uniqueId } from "../../tools/types"; import type { CmdOption, Command, @@ -21,47 +39,115 @@ import type { ToolDraft, Vec2, } from "../types"; +import type { TranslationKey } from "../../i18n"; const EPS = 1e-6; const MIN_SIDES = 3; const MAX_SIDES = 12; +const DEG = Math.PI / 180; let lastSides = 6; -interface PolyIdle extends CommandState { - phase: "center"; +type PolygonMode = "inscribed" | "circumscribed"; +let lastMode: PolygonMode = "inscribed"; +const nextMode = (m: PolygonMode): PolygonMode => (m === "inscribed" ? "circumscribed" : "inscribed"); +const modeValue = (m: PolygonMode): string => (m === "inscribed" ? "insc" : "circ"); + +/** Konstruktionsart: Zentrum+Radius (Default) oder Kante (zwei Punkte). */ +type PolygonMethod = "center" | "edge"; +let lastMethod: PolygonMethod = "center"; +const nextConstructMethod = (m: PolygonMethod): PolygonMethod => (m === "center" ? "edge" : "center"); + +interface PolyP1 extends CommandState { + phase: "p1"; + method: PolygonMethod; } -interface PolyDrawing extends CommandState { +interface PolyRadius extends CommandState { phase: "radius"; + method: "center"; center: Vec2; cursor: Vec2 | null; } -type PolyState = PolyIdle | PolyDrawing; +interface PolyEdge2 extends CommandState { + phase: "edge2"; + method: "edge"; + a: Vec2; + cursor: Vec2 | null; +} +type PolyState = PolyP1 | PolyRadius | PolyEdge2; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; const RADIUS_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }]; +const EDGE_FIELDS: CommandField[] = [ + { id: "length", labelKey: "cmd.field.length" }, + { id: "angle", labelKey: "cmd.field.angle" }, +]; +const CONSTRUCT_OPTION: CmdOption = { id: "construct", labelKey: "cmd.polygon.construct" }; const SIDES_OPTION: CmdOption = { id: "sides", labelKey: "cmd.polygon.sides" }; +const MODE_OPTION: CmdOption = { id: "mode", labelKey: "cmd.polygon.mode" }; -/** Eckpunkte des umschriebenen regelmässigen Vielecks (erste Ecke Richtung `dir`). */ -function polygonPts(center: Vec2, r: number, sides: number, dir: Vec2 | null): Vec2[] { +/** + * Eckpunkt-Radius aus dem EINGEGEBENEN Radius: bei „eingeschrieben" ist das + * bereits der Eckpunkt-Radius (unverändert); bei „umschrieben" ist der + * eingegebene Radius das Apothema (Zentrum→Kantenmitte) — der tatsächliche + * Eckpunkt-Radius ist grösser, `apothem / cos(π/n)`. + */ +function vertexRadius(r: number, sides: number, mode: PolygonMode): number { + return mode === "circumscribed" ? r / Math.cos(Math.PI / sides) : r; +} + +/** Eckpunkte des regelmässigen Vielecks (erste Ecke Richtung `dir`), `r` = eingegebener Radius (Modus-abhängig). */ +function polygonPts(center: Vec2, r: number, sides: number, mode: PolygonMode, dir: Vec2 | null): Vec2[] { + const rv = vertexRadius(r, sides, mode); const t0 = dir && dist(center, dir) > EPS ? Math.atan2(dir.y - center.y, dir.x - center.x) : 0; const pts: Vec2[] = []; for (let i = 0; i < sides; i++) { const t = t0 + (i / sides) * Math.PI * 2; - pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); + pts.push({ x: center.x + rv * Math.cos(t), y: center.y + rv * Math.sin(t) }); + } + return pts; +} + +/** + * Eckpunkte des regelmässigen Vielecks aus einer EINZELNEN Kante `a→b`: die + * Kantenlänge/Richtung legt die Grösse/Drehung eindeutig fest. Läuft von `b` + * aus nach LINKS abbiegend weiter (Aussenwinkel 2π/n je Ecke) — ein + * konvexes, CCW aufgebautes Vieleck auf der linken Seite von a→b. + */ +function polygonFromEdge(a: Vec2, b: Vec2, sides: number): Vec2[] { + const edgeLen = dist(a, b); + const ext = (2 * Math.PI) / sides; + const pts: Vec2[] = [a, b]; + let cur = b; + let dir = Math.atan2(b.y - a.y, b.x - a.x); + for (let i = 2; i < sides; i++) { + dir += ext; + const next: Vec2 = { x: cur.x + edgeLen * Math.cos(dir), y: cur.y + edgeLen * Math.sin(dir) }; + pts.push(next); + cur = next; } return pts; } function polygonDraft(center: Vec2, r: number, dir: Vec2 | null, at: Vec2 | null): ToolDraft { if (r < EPS) return { preview: [], vertices: [center] }; - const preview: DraftShape[] = [{ kind: "poly", pts: polygonPts(center, r, lastSides, dir), closed: true }]; + const preview: DraftShape[] = [ + { kind: "poly", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, + ]; const draft: ToolDraft = { preview, vertices: [center] }; if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m × ${lastSides}` }; return draft; } +/** Vorschau der Kanten-Konstruktion — zeigt das VOLLE Vieleck, sobald die Kante eine Länge hat. */ +function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { + if (!cursor || dist(a, cursor) < EPS) return { preview: [{ kind: "line", a, b: a }], vertices: [a] }; + const pts = polygonFromEdge(a, cursor, lastSides); + return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) }; +} + function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): Project { if (r < EPS) return p; const d: Drawing2D = { @@ -69,40 +155,102 @@ function appendPolygon(p: Project, center: Vec2, r: number, dir: Vec2 | null, ct type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, dir), closed: true }, + geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +function appendPolygonFromEdge(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { + if (dist(a, b) < EPS) return p; + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } const idle = (): [CommandState, CommandResult] => [ - { phase: "center", lastPoint: null } as PolyIdle, + { phase: "p1", method: lastMethod, lastPoint: null } as PolyP1, { draft: null, done: true }, ]; +function promptKey(s: PolyState): TranslationKey { + if (s.phase === "p1") return s.method === "edge" ? "cmd.polygon.edgeStart" : "cmd.polygon.center"; + if (s.phase === "edge2") return "cmd.polygon.edgeEnd"; + return "cmd.polygon.radius"; +} + export const polygonCommand: Command = { name: "polygon", labelKey: "cmd.polygon.label", - prompt: (s) => ((s as PolyState).phase === "radius" ? "cmd.polygon.radius" : "cmd.polygon.center"), - accepts: (s) => ((s as PolyState).phase === "radius" ? ["point", "number", "option"] : ["point"]), - options: (s) => - (s as PolyState).phase === "radius" ? [{ ...SIDES_OPTION, value: String(lastSides) }] : [], - init: (): PolyIdle => ({ phase: "center", lastPoint: null }), + prompt: (s) => promptKey(s as PolyState), + accepts: (s) => ((s as PolyState).phase === "radius" ? ["point", "number", "option"] : ["point", "option"]), + options: (s) => { + const st = s as PolyState; + // „Konstruktion" und „Ecken" sind IMMER wählbar (auch vor dem ersten + // Klick — die Eckenzahl betrifft beide Konstruktionsarten gleichermassen); + // „Modus" (eingeschrieben/umschrieben) ist NUR bei der Zentrum-Methode + // sinnvoll, dort ausserdem erst NACH dem Zentrum-Klick sichtbar (Radius + // bezieht sich auf den geklickten Mittelpunkt). + const base: CmdOption[] = [ + { ...CONSTRUCT_OPTION, value: st.method }, + { ...SIDES_OPTION, value: String(lastSides) }, + ]; + if (st.phase === "radius") { + return [...base, { ...MODE_OPTION, value: modeValue(lastMode) }]; + } + return base; + }, + init: (): PolyP1 => ({ phase: "p1", method: lastMethod, lastPoint: null }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as PolyState; - if (s.phase !== "radius") { - if (input.kind !== "point") return [s, { draft: null }]; - const ns: PolyDrawing = { phase: "radius", center: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: polygonDraft(input.point, 0, null, null) }]; - } + if (input.kind === "option") { + if (input.id === "construct") { + lastMethod = nextConstructMethod(s.method); + return [{ phase: "p1", method: lastMethod, lastPoint: null } as PolyP1, { draft: null }]; + } if (input.id === "sides") { lastSides = lastSides >= MAX_SIDES ? MIN_SIDES : lastSides + 1; + if (s.phase === "radius") { + const r = s.cursor ? dist(s.center, s.cursor) : 0; + return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }]; + } + if (s.phase === "edge2") return [s, { draft: edgeDraft(s.a, s.cursor) }]; + return [s, { draft: null }]; + } + if (input.id === "mode" && s.phase === "radius") { + lastMode = nextMode(lastMode); const r = s.cursor ? dist(s.center, s.cursor) : 0; return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }]; } return [s, { draft: null }]; } + + if (s.phase === "p1") { + if (input.kind !== "point") return [s, { draft: null }]; + if (s.method === "edge") { + const ns: PolyEdge2 = { phase: "edge2", method: "edge", a: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: edgeDraft(input.point, input.point) }]; + } + const ns: PolyRadius = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point }; + return [ns, { draft: polygonDraft(input.point, 0, null, null) }]; + } + + if (s.phase === "edge2") { + if (input.kind !== "point" || dist(s.a, input.point) < EPS) { + return [s, { draft: edgeDraft(s.a, s.cursor) }]; + } + const a = s.a; + const b = input.point; + return [idle()[0], { draft: null, done: true, commit: (p) => appendPolygonFromEdge(p, a, b, ctx) }]; + } + + // phase "radius" let r: number; let dir: Vec2 | null; if (input.kind === "number") { @@ -124,34 +272,58 @@ export const polygonCommand: Command = { onMove: (state, point): [CommandState, CommandResult] => { const s = state as PolyState; - if (s.phase !== "radius") return [s, { draft: null }]; - const r = dist(s.center, point); - const ns: PolyDrawing = { ...s, cursor: point }; - return [ns, { draft: polygonDraft(s.center, r, point, point) }]; + if (s.phase === "radius") { + const r = dist(s.center, point); + const ns: PolyRadius = { ...s, cursor: point }; + return [ns, { draft: polygonDraft(s.center, r, point, point) }]; + } + if (s.phase === "edge2") { + const ns: PolyEdge2 = { ...s, cursor: point }; + return [ns, { draft: edgeDraft(s.a, point) }]; + } + return [s, { draft: null }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), onCancel: (): [CommandState, CommandResult] => idle(), - fields: (state) => ((state as PolyState).phase === "radius" ? RADIUS_FIELDS : []), + fields: (state) => { + const s = state as PolyState; + if (s.phase === "radius") return RADIUS_FIELDS; + if (s.phase === "edge2") return EDGE_FIELDS; + return []; + }, fieldValues: (state, _locks, cursor): Record => { const s = state as PolyState; - if (s.phase !== "radius" || !cursor) return {}; - return { radius: dist(s.center, cursor) }; + if (!cursor) return {}; + if (s.phase === "radius") return { radius: dist(s.center, cursor) }; + if (s.phase === "edge2") { + return { length: dist(s.a, cursor), angle: ((segAngleDeg(s.a, cursor) % 360) + 360) % 360 }; + } + return {}; }, pointFromFields: (state, locks, cursor) => { const s = state as PolyState; - if (s.phase !== "radius") return null; - const r = "radius" in locks ? Math.abs(locks.radius) : cursor ? dist(s.center, cursor) : 0; - if (cursor) { - const d = dist(s.center, cursor); - if (d > EPS) { - return { - x: s.center.x + ((cursor.x - s.center.x) / d) * r, - y: s.center.y + ((cursor.y - s.center.y) / d) * r, - }; + if (s.phase === "radius") { + const r = "radius" in locks ? Math.abs(locks.radius) : cursor ? dist(s.center, cursor) : 0; + if (cursor) { + const d = dist(s.center, cursor); + if (d > EPS) { + return { + x: s.center.x + ((cursor.x - s.center.x) / d) * r, + y: s.center.y + ((cursor.y - s.center.y) / d) * r, + }; + } } + return { x: s.center.x + r, y: s.center.y }; } - return { x: s.center.x + r, y: s.center.y }; + if (s.phase === "edge2") { + const ref = cursor ?? s.a; + const length = "length" in locks ? locks.length : dist(s.a, ref); + const angleDeg = "angle" in locks ? locks.angle : segAngleDeg(s.a, ref); + const ang = angleDeg * DEG; + return { x: s.a.x + Math.cos(ang) * length, y: s.a.y + Math.sin(ang) * length }; + } + return null; }, }; diff --git a/src/commands/cmds/polyline.arcMode.test.ts b/src/commands/cmds/polyline.arcMode.test.ts new file mode 100644 index 0000000..ed33e27 --- /dev/null +++ b/src/commands/cmds/polyline.arcMode.test.ts @@ -0,0 +1,231 @@ +/** + * Bogen-Modus der Polylinie: gerade und gekrümmte Segmente in EINEM Element. + * Zwei Varianten — DREI-PUNKT (Default: Durchgangspunkt + Endpunkt, Grösse + * hängt nur an diesen drei Punkten) und TANGENTIAL (Unteroption: schliesst + * weich an den Vorgänger an, Krümmung folgt daraus zwangsläufig). + */ + +import { describe, expect, it } from "vitest"; +import { polylineCommand } from "./polyline"; +import { sampleProject } from "../../model/sampleProject"; +import { bulgeArc } from "../../geometry/bulge"; +import type { CommandContext, CommandState, Project, Vec2 } from "../types"; + +const ctx = { + level: sampleProject.drawingLevels[0], + defaultCategoryCode: sampleProject.layers[0].code, +} as CommandContext; + +/** Spielt eine Eingabefolge ab und liefert das committete Projekt. */ +function run(inputs: ({ pt: Vec2 } | { opt: string } | "confirm")[]): Project { + let state: CommandState = polylineCommand.init(); + let project: Project = sampleProject; + for (const step of inputs) { + const [next, res] = + step === "confirm" + ? polylineCommand.onConfirm(state, ctx) + : "pt" in step + ? polylineCommand.onInput(state, { kind: "point", point: step.pt }, ctx) + : polylineCommand.onInput(state, { kind: "option", id: step.opt }, ctx); + state = next; + if (res.commit) project = res.commit(project); + } + return project; +} + +/** Die zuletzt angehängte Polylinie. */ +function lastPolyline(p: Project) { + const d = p.drawings2d[p.drawings2d.length - 1]; + if (d.geom.shape !== "polyline") throw new Error("keine Polylinie"); + return d.geom; +} + +describe("Polylinie — gerade (unverändert)", () => { + it("ohne Bogen-Modus bleibt alles gerade und OHNE bulge-Feld (Format unverändert)", () => { + const g = lastPolyline( + run([{ pt: { x: 0, y: 0 } }, { pt: { x: 4, y: 0 } }, { pt: { x: 4, y: 3 } }, "confirm"]), + ); + expect(g.pts.length).toBe(3); + expect(g.bulge).toBeUndefined(); + }); +}); + +describe("Polylinie — Drei-Punkt-Bogen (Default)", () => { + it("Durchgangspunkt + Endpunkt ergeben EIN Bogen-Segment", () => { + const g = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { opt: "arc" }, + { pt: { x: 2, y: 2 } }, // Durchgangspunkt + { pt: { x: 4, y: 0 } }, // Endpunkt + "confirm", + ]), + ); + // Der Durchgangspunkt ist KEIN Stützpunkt — nur Start und Ende. + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }]); + // Halbkreis über der Sehne → |bulge| = 1. + expect(Math.abs(g.bulge![0])).toBeCloseTo(1, 9); + }); + + it("der Bogen läuft tatsächlich durch den gesetzten Durchgangspunkt", () => { + const g = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { opt: "arc" }, + { pt: { x: 3, y: 1 } }, + { pt: { x: 5, y: -2 } }, + "confirm", + ]), + ); + const arc = bulgeArc(g.pts[0], g.pts[1], g.bulge![0])!; + expect(Math.hypot(3 - arc.center.x, 1 - arc.center.y)).toBeCloseTo(arc.r, 9); + }); + + it("die Grösse hängt NUR am eigenen Segment — nicht am Vorgänger (Nutzer-Anforderung)", () => { + // Derselbe Bogen (gleiche drei Punkte relativ zueinander), einmal nach + // einem langen und einmal nach einem kurzen Vorgänger-Segment: identisch. + const withLong = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { pt: { x: 10, y: 0 } }, + { opt: "arc" }, + { pt: { x: 12, y: 2 } }, + { pt: { x: 14, y: 0 } }, + "confirm", + ]), + ); + const withShort = lastPolyline( + run([ + { pt: { x: 9, y: 0 } }, + { pt: { x: 10, y: 0 } }, + { opt: "arc" }, + { pt: { x: 12, y: 2 } }, + { pt: { x: 14, y: 0 } }, + "confirm", + ]), + ); + expect(withShort.bulge![1]).toBeCloseTo(withLong.bulge![1], 12); + }); + + it("Modus pro Segment umschaltbar: gerade → Bogen → gerade in EINEM Element", () => { + const g = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { pt: { x: 4, y: 0 } }, + { opt: "arc" }, + { pt: { x: 6, y: 2 } }, // Durchgangspunkt + { pt: { x: 8, y: 0 } }, // Endpunkt + { opt: "arc" }, // zurück auf gerade + { pt: { x: 8, y: 4 } }, + "confirm", + ]), + ); + expect(g.pts.length).toBe(4); + expect(g.bulge![0]).toBe(0); + expect(Math.abs(g.bulge![1])).toBeGreaterThan(1e-6); + expect(g.bulge![2]).toBe(0); + }); +}); + +describe("Polylinie — tangentialer Bogen (Unteroption)", () => { + it("schliesst tangential ans vorherige Segment an und endet im geklickten Punkt", () => { + const g = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { pt: { x: 4, y: 0 } }, + { opt: "arc" }, + { opt: "tangent" }, + { pt: { x: 6, y: 2 } }, + "confirm", + ]), + ); + expect(g.pts.length).toBe(3); + expect(g.bulge![0]).toBe(0); + + // Waagrechter Start ⇒ Mittelpunkt senkrecht über/unter dem Startpunkt. + const arc = bulgeArc(g.pts[1], g.pts[2], g.bulge![1])!; + expect(arc.center.x).toBeCloseTo(4, 9); + const end = { + x: arc.center.x + arc.r * Math.cos(arc.a1), + y: arc.center.y + arc.r * Math.sin(arc.a1), + }; + expect(end.x).toBeCloseTo(6, 9); + expect(end.y).toBeCloseTo(2, 9); + }); + + it("erstes Segment bleibt gerade — ohne Vorgänger gibt es keine Tangente", () => { + const g = lastPolyline( + run([ + { opt: "arc" }, + { opt: "tangent" }, + { pt: { x: 0, y: 0 } }, + { pt: { x: 4, y: 0 } }, + "confirm", + ]), + ); + expect(g.bulge).toBeUndefined(); + }); + + it("aufeinanderfolgende tangentiale Bögen bleiben tangentenstetig", () => { + const g = lastPolyline( + run([ + { pt: { x: 0, y: 0 } }, + { pt: { x: 4, y: 0 } }, + { opt: "arc" }, + { opt: "tangent" }, + { pt: { x: 6, y: 2 } }, + // NICHT auf der Tangente (die zeigt in (6,2) senkrecht nach oben) — + // sonst wäre der tangentenstetige „Bogen" korrekterweise eine Gerade. + { pt: { x: 9, y: 5 } }, + "confirm", + ]), + ); + expect(Math.abs(g.bulge![2])).toBeGreaterThan(1e-6); + const a1 = bulgeArc(g.pts[1], g.pts[2], g.bulge![1])!; + const a2 = bulgeArc(g.pts[2], g.pts[3], g.bulge![2])!; + // Tangentenstetig: beide Mittelpunkte liegen mit dem Berührpunkt auf EINER + // Geraden (gemeinsame Normale). + const p = g.pts[2]; + const v1 = { x: a1.center.x - p.x, y: a1.center.y - p.y }; + const v2 = { x: a2.center.x - p.x, y: a2.center.y - p.y }; + expect(Math.abs(v1.x * v2.y - v1.y * v2.x)).toBeLessThan(1e-6); + }); +}); + +describe("Polylinie — Ring schliessen im Bogen-Modus (REGRESSION: Schluss-Segment verlor seinen Bulge)", () => { + // Alle drei Wege, einen Ring zu schliessen, müssen dem SCHLUSS-Segment + // (letzter Punkt → Start) denselben tangentenstetigen Bogen geben wie jedes + // andere Segment — vorher committeten alle drei eine gerade Kante, weil das + // Bulge-Array einen Eintrag zu kurz war (`drawing2d.ts` liest den fehlenden + // Index als `undefined` = gerade). + const path: ({ pt: Vec2 } | { opt: string })[] = [ + { pt: { x: 0, y: 0 } }, + { pt: { x: 4, y: 0 } }, // Segment 0: gerade (kein Vorgänger für die Tangente) + { opt: "arc" }, + { opt: "tangent" }, + { pt: { x: 4, y: 3 } }, // Segment 1: Bogen (Tangente knickt von (1,0) auf (0,1) ab) + ]; + + it('Option „close"', () => { + const g = lastPolyline(run([...path, { opt: "close" }])); + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }]); + expect(g.bulge).toHaveLength(3); + expect(Math.abs(g.bulge![2])).toBeGreaterThan(1e-6); + }); + + it('Ring-Toggle („mode") + Enter', () => { + const g = lastPolyline(run([...path, { opt: "mode" }, "confirm"])); + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }]); + expect(g.bulge).toHaveLength(3); + expect(Math.abs(g.bulge![2])).toBeGreaterThan(1e-6); + }); + + it("Klick nahe am Startpunkt", () => { + // Knapp innerhalb der Fangdistanz (CLOSE_HIT), nicht exakt (0,0) — + // realistischer Nutzer-Klick beim Schliessen per Auge. + const g = lastPolyline(run([...path, { pt: { x: 0.001, y: 0.001 } }])); + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }]); + expect(g.bulge).toHaveLength(3); + expect(Math.abs(g.bulge![2])).toBeGreaterThan(1e-6); + }); +}); diff --git a/src/commands/cmds/polyline.ts b/src/commands/cmds/polyline.ts index 258b276..88dbfb3 100644 --- a/src/commands/cmds/polyline.ts +++ b/src/commands/cmds/polyline.ts @@ -1,11 +1,25 @@ // Polyline — mehrteiliger Zug (portiert polylineTool). Schritte: // 1) „Startpunkt:" → Punkt -// 2) „Nächster Punkt ( Schliessen Zurück ):" → Punkt … (Enter beendet offen, -// „Schliessen" schließt; Klick auf den Startpunkt schließt ebenfalls) +// 2) „Nächster Punkt ( Bogen Schliessen Zurück ):" → Punkt … (Enter beendet +// offen, „Schliessen" schließt; Klick auf den Startpunkt schließt ebenfalls) // // Akzeptiert je Punkt Maus-Picks UND getippte Koordinaten (0,0 · r3,0 · 5<45). +// +// BOGEN-MODUS (Option „Bogen"): statt einer Geraden entsteht ein Kreisbogen. +// Gespeichert wird er als `bulge` am Segment (DXF-Konvention), also im selben +// Element; Bogen- und Geradenstücke mischen sich frei in EINER Polylinie. +// Zwei Varianten, umschaltbar über die Unteroption „Tangential": +// • AUS (Default): DREI-PUNKT-Bogen — erst ein Durchgangspunkt, dann der +// Endpunkt. Radius und Wölbung hängen NUR an diesen drei Punkten, jedes +// Segment ist also unabhängig einstellbar (Nutzer-Anforderung: die Grösse +// soll nicht am vorherigen/ersten Punkt der Kette hängen). +// • AN: der Bogen schliesst TANGENTIAL ans vorherige Segment an (AutoCADs +// PLINE-Default) — bequem für weiche Übergänge, aber die Krümmung ergibt +// sich dann zwangsläufig aus dem Vorgänger. Das erste Segment hat keine +// Tangenten-Referenz und bleibt gerade. import type { Drawing2D } from "../../model/types"; +import { bulgeArcPoints, bulgeThroughPoint } from "../../geometry/bulge"; import { segmentHud, uniqueId } from "../../tools/types"; import type { Command, @@ -42,20 +56,89 @@ function polyNextFromFields(last: Vec2, locks: Record, cursor: V return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length }; } +/** + * Bulge eines Bogens, der in `a` TANGENTIAL an die Richtung `dir` anschliesst + * und in `b` endet. Nach dem Sehnen-Tangenten-Satz ist der Winkel θ VON DER + * SEHNE ZUR TANGENTE die halbe Zentriwinkel-Spanne (θ = Δ/2), und + * `bulge = tan(Δ/4)` — also `tan(θ/2)`. Die Richtung der Winkelmessung ist + * wesentlich: von der Sehne zur Tangente, passend zur Vorzeichenkonvention + * von `bulge` (positiv = Ausbauchung LINKS von a→b). Andersherum gemessen + * läge die Tangente am falschen Bogenende. Ohne Richtung (erstes Segment) + * oder bei entarteter Sehne bleibt es gerade (0). + */ +function tangentBulge(a: Vec2, b: Vec2, dir: Vec2 | null): number { + if (!dir) return 0; + const cx = b.x - a.x, cy = b.y - a.y; + const len = Math.hypot(cx, cy); + const dl = Math.hypot(dir.x, dir.y); + if (len < EPS || dl < EPS) return 0; + const ux = cx / len, uy = cy / len; + const dx = dir.x / dl, dy = dir.y / dl; + const theta = Math.atan2(ux * dy - uy * dx, ux * dx + uy * dy); + return Math.tan(theta / 2); +} + +/** Richtung, in der das zuletzt gelegte Segment endet (Tangente für den nächsten Bogen). */ +function lastDirection(points: Vec2[], bulges: number[]): Vec2 | null { + const n = points.length; + if (n < 2) return null; + const a = points[n - 2]; + const b = points[n - 1]; + const bulge = bulges[n - 2] ?? 0; + const chord = { x: b.x - a.x, y: b.y - a.y }; + if (Math.abs(bulge) < EPS) return chord; + // Austritts-Tangente eines Bogens: die Sehne um den halben Zentriwinkel + // gedreht (Δ/2 = 2·atan(bulge)) — am ENDE mit umgekehrtem Vorzeichen wie am + // Anfang (der Bogen ist symmetrisch zur Sehne). + const ang = -2 * Math.atan(bulge); + const c = Math.cos(ang), si = Math.sin(ang); + return { x: chord.x * c - chord.y * si, y: chord.x * si + chord.y * c }; +} + interface PolyIdle extends CommandState { phase: "start"; /** Gewählter Schließ-Modus (bleibt über den Befehl hinweg erhalten). */ closed: boolean; + /** Bogen-Modus (bleibt über den Befehl hinweg erhalten, wie `closed`). */ + arc: boolean; + /** Im Bogen-Modus: tangential an den Vorgänger statt Drei-Punkt-Bogen. */ + tangent: boolean; } interface PolyDrawing extends CommandState { phase: "next"; points: Vec2[]; + /** Bulge je Segment (Index = Segment `points[i] → points[i+1]`), 0 = gerade. */ + bulges: number[]; cursor: Vec2 | null; /** Soll der committete Zug als Ring (geschlossen) gelten? Default: offen. */ closed: boolean; + arc: boolean; + tangent: boolean; + /** + * Drei-Punkt-Bogen: bereits gesetzter Durchgangspunkt, der noch auf seinen + * Endpunkt wartet. `null` = kein Bogen in Arbeit. + */ + pendingThrough: Vec2 | null; } type PolyState = PolyIdle | PolyDrawing; +/** + * Bulge des SCHLUSS-Segments (letzter Punkt → Start), wenn ein Ring ohne + * weiteren Klick geschlossen wird (Option „close" bzw. Ring-Toggle + Enter). + * Ein bereits gesetzter Drei-Punkt-Durchgangspunkt gilt dann für DIESES + * Segment; sonst tangential an den Vorgänger, wie bei jedem anderen Bogen. + * Ohne diesen Eintrag liest `drawing2d.ts` dort einen fehlenden Bulge (Index + * ausserhalb des Arrays) und zeichnet die Schlusskante immer gerade. + */ +function closingBulge(s: PolyDrawing): number { + if (!s.arc) return 0; + const prev = s.points[s.points.length - 1]; + const start = s.points[0]; + return s.pendingThrough + ? bulgeThroughPoint(prev, s.pendingThrough, start) + : tangentBulge(prev, start, lastDirection(s.points, s.bulges)); +} + /** Sofort-schließen-Aktion (nur ≥3 Punkte): committet als Ring und beendet. */ const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" }; const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" }; @@ -65,15 +148,57 @@ const closedOption = (closed: boolean): CmdOption => ({ labelKey: "cmd.polyline.closedOpt", value: closed ? "on" : "off", }); +/** Toggle-Option: folgende Segmente als Kreisbogen statt gerade. */ +const arcOption = (arc: boolean): CmdOption => ({ + id: "arc", + labelKey: "cmd.polyline.arcOpt", + value: arc ? "on" : "off", +}); +/** Unteroption (nur im Bogen-Modus): tangential an den Vorgänger statt Drei-Punkt. */ +const tangentOption = (on: boolean): CmdOption => ({ + id: "tangent", + labelKey: "cmd.polyline.tangentOpt", + value: on ? "on" : "off", +}); -/** Vorschau (Zug + Gummiband zum Cursor) + HUD (Länge·Winkel des letzten Segments). */ -function polyDraft(points: Vec2[], cursor: Vec2 | null, closed = false): ToolDraft { - const pts = cursor ? [...points, cursor] : points; +/** + * Vorschau (Zug + Gummiband zum Cursor) + HUD (Länge·Winkel des letzten + * Segments). Bogen-Segmente werden für die VORSCHAU tesselliert — der Draft + * kennt nur Linien/Polygonzüge; gespeichert wird selbstverständlich der + * exakte `bulge` (s. `appendPolyline`). + */ +function polyDraft( + points: Vec2[], + bulges: number[], + cursor: Vec2 | null, + closed = false, + arcMode = false, + tangent = false, + pendingThrough: Vec2 | null = null, +): ToolDraft { + const all = cursor ? [...points, cursor] : points; + const last = points[points.length - 1]; + // Vorschau-Bulge des Gummiband-Segments: Drei-Punkt (sobald der + // Durchgangspunkt gesetzt ist), sonst tangential — oder gerade. + const previewBulge = + !cursor || !last || !arcMode + ? 0 + : pendingThrough + ? bulgeThroughPoint(last, pendingThrough, cursor) + : tangent + ? tangentBulge(last, cursor, lastDirection(points, bulges)) + : 0; + const allBulges = cursor ? [...bulges, previewBulge] : bulges; + // Bogen-Segmente für die Vorschau ausrollen. + const pts: Vec2[] = all.length ? [all[0]] : []; + for (let i = 0; i < all.length - 1; i++) { + const sub = bulgeArcPoints(all[i], all[i + 1], allBulges[i] ?? 0); + for (let k = 1; k < sub.length; k++) pts.push(sub[k]); + } // Ring nur ab 3 Punkten zeigen; darunter bleibt die Vorschau offen. - const showClosed = closed && pts.length >= 3; + const showClosed = closed && all.length >= 3; const preview: DraftShape[] = [{ kind: "poly", pts, closed: showClosed }]; const draft: ToolDraft = { preview, vertices: points }; - const last = points[points.length - 1]; if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); return draft; } @@ -82,38 +207,54 @@ function polyDraft(points: Vec2[], cursor: Vec2 | null, closed = false): ToolDra function appendPolyline( p: Project, pts: Vec2[], + bulges: number[], closed: boolean, ctx: CommandContext, ): Project { + // `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner + // Geradenzug bleibt damit bitgleich zu vorher (additives Feld). + const hasArc = bulges.some((b) => Math.abs(b) > EPS); const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts, closed }, + geom: hasArc + ? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) } + : { shape: "polyline", pts, closed }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } /** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */ -const idle = (closed = false): [CommandState, CommandResult] => [ - { phase: "start", lastPoint: null, closed } as PolyIdle, +const idle = (closed = false, arc = false, tangent = false): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null, closed, arc, tangent } as PolyIdle, { draft: null, done: true }, ]; export const polylineCommand: Command = { name: "polyline", labelKey: "cmd.polyline.label", - prompt: (s) => ((s as PolyState).phase === "next" ? "cmd.polyline.next" : "cmd.polyline.start"), + prompt: (s) => { + const ps = s as PolyState; + if (ps.phase !== "next") return "cmd.polyline.start"; + // Drei-Punkt-Bogen: erst Durchgangspunkt, dann Endpunkt. + if (ps.arc && !ps.tangent && !ps.pendingThrough) return "cmd.polyline.arcThrough"; + return "cmd.polyline.next"; + }, // Auch im Startschritt darf der Schließ-Modus gewählt werden. accepts: () => ["point", "number", "option"], options: (s) => { const ps = s as PolyState; const toggle = closedOption(ps.closed); - if (ps.phase !== "next") return [toggle]; - return ps.points.length >= 2 ? [CLOSE, toggle, UNDO] : [toggle, UNDO]; + const arc = arcOption(ps.arc); + const sub = ps.arc ? [tangentOption(ps.tangent)] : []; + if (ps.phase !== "next") return [arc, ...sub, toggle]; + return ps.points.length >= 2 + ? [CLOSE, arc, ...sub, toggle, UNDO] + : [arc, ...sub, toggle, UNDO]; }, - init: (): PolyIdle => ({ phase: "start", lastPoint: null, closed: false }), + init: (): PolyIdle => ({ phase: "start", lastPoint: null, closed: false, arc: false, tangent: false }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as PolyState; @@ -121,61 +262,146 @@ export const polylineCommand: Command = { if (input.kind === "option") { // Schließ-Modus umschalten (Tastenkürzel „C" bzw. Klick im Feld-Row); // in jedem Schritt verfügbar, ohne den laufenden Zug zu beenden. - if (input.id === "mode") { - const ns = { ...s, closed: !s.closed } as PolyState; - return [ns, { draft: s.phase === "next" ? polyDraft(s.points, s.cursor, ns.closed) : null }]; + if (input.id === "mode" || input.id === "arc" || input.id === "tangent") { + // Modus-Wechsel verwirft einen halb gesetzten Drei-Punkt-Bogen — + // sonst bezöge sich der wartende Durchgangspunkt auf eine andere + // Bogen-Variante als die jetzt gewählte. + const base = + input.id === "mode" + ? { ...s, closed: !s.closed } + : input.id === "arc" + ? { ...s, arc: !s.arc } + : { ...s, tangent: !s.tangent }; + const ns = (s.phase === "next" ? { ...base, pendingThrough: null } : base) as PolyState; + return [ + ns, + { + draft: + s.phase === "next" + ? polyDraft(s.points, s.bulges, s.cursor, ns.closed, ns.arc, ns.tangent, null) + : null, + }, + ]; } if (s.phase !== "next") return [s, { draft: null }]; if (input.id === "undo") { + // Wartet ein Durchgangspunkt, nimmt „Zurück" zuerst diesen zurück. + if (s.pendingThrough) { + const ns: PolyDrawing = { ...s, pendingThrough: null }; + return [ns, { draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, null) }]; + } const pts = s.points.slice(0, -1); + const bulges = s.bulges.slice(0, Math.max(0, pts.length - 1)); if (pts.length === 0) - return [{ phase: "start", lastPoint: null, closed: s.closed } as PolyIdle, { draft: null }]; + return [ + { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, + { draft: null }, + ]; const ns: PolyDrawing = { phase: "next", points: pts, + bulges, cursor: s.cursor, lastPoint: pts[pts.length - 1], closed: s.closed, + arc: s.arc, + tangent: s.tangent, + pendingThrough: null, }; - return [ns, { draft: polyDraft(pts, s.cursor, s.closed) }]; + return [ns, { draft: polyDraft(pts, bulges, s.cursor, s.closed, s.arc, s.tangent, null) }]; } // Sofort schließen: committet als Ring (unabhängig vom Toggle-Zustand). if (input.id === "close" && s.points.length >= 3) { const pts = s.points; + const bl = [...s.bulges, closingBulge(s)]; return [ - { phase: "start", lastPoint: null, closed: s.closed } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, true, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, + { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, ]; } - return [s, { draft: polyDraft(s.points, s.cursor, s.closed) }]; + return [ + s, + { draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) }, + ]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "next" ? polyDraft(s.points, s.cursor, s.closed) : null }]; + return [ + s, + { + draft: + s.phase === "next" + ? polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) + : null, + }, + ]; } const pt = input.point; if (s.phase !== "next") { - const ns: PolyDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt, closed: s.closed }; - return [ns, { draft: polyDraft([pt], pt, s.closed) }]; + const ns: PolyDrawing = { + phase: "next", + points: [pt], + bulges: [], + cursor: pt, + lastPoint: pt, + closed: s.closed, + arc: s.arc, + tangent: s.tangent, + pendingThrough: null, + }; + return [ns, { draft: polyDraft([pt], [], pt, s.closed, s.arc, s.tangent, null) }]; } - // Klick nahe Startpunkt → schließen (committet als Ring). + // Drei-Punkt-Bogen: der ERSTE Klick setzt nur den Durchgangspunkt; das + // Segment entsteht erst mit dem zweiten Klick (Endpunkt). + if (s.arc && !s.tangent && !s.pendingThrough) { + const ns: PolyDrawing = { ...s, pendingThrough: pt, cursor: pt }; + return [ns, { draft: polyDraft(s.points, s.bulges, pt, s.closed, s.arc, s.tangent, pt) }]; + } + // Bulge des neuen Segments: Drei-Punkt (über den gesetzten Durchgangspunkt) + // oder tangential an den Vorgänger. + const prev = s.points[s.points.length - 1]; + const newBulge = !s.arc + ? 0 + : s.pendingThrough + ? bulgeThroughPoint(prev, s.pendingThrough, pt) + : tangentBulge(prev, pt, lastDirection(s.points, s.bulges)); + // Klick nahe Startpunkt → schließen (committet als Ring). `newBulge` ist + // bereits die korrekte Krümmung des Schluss-Segments (prev→pt, genau wie + // die Vorschau in `polyDraft` sie zeigt) — MUSS mit angehängt werden, + // sonst liest `drawing2d.ts` dort einen fehlenden Bulge-Eintrag und + // schliesst immer gerade, obwohl die Vorschau eben noch den Bogen zeigte. if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; + const bl = [...s.bulges, newBulge]; return [ - { phase: "start", lastPoint: null, closed: s.closed } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, true, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, + { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, true, ctx) }, ]; } const points = [...s.points, pt]; - const ns: PolyDrawing = { phase: "next", points, cursor: pt, lastPoint: pt, closed: s.closed }; - return [ns, { draft: polyDraft(points, pt, s.closed) }]; + const bulges = [...s.bulges, newBulge]; + const ns: PolyDrawing = { + phase: "next", + points, + bulges, + cursor: pt, + lastPoint: pt, + closed: s.closed, + arc: s.arc, + tangent: s.tangent, + pendingThrough: null, + }; + return [ns, { draft: polyDraft(points, bulges, pt, s.closed, s.arc, s.tangent, null) }]; }, onMove: (state, point): [CommandState, CommandResult] => { const s = state as PolyState; if (s.phase !== "next") return [s, { draft: null }]; const ns: PolyDrawing = { ...s, cursor: point }; - return [ns, { draft: polyDraft(s.points, point, s.closed) }]; + return [ + ns, + { draft: polyDraft(s.points, s.bulges, point, s.closed, s.arc, s.tangent, s.pendingThrough) }, + ]; }, // Enter/Space/Rechtsklick: Zug beenden (≥2 Punkte). Der Schließ-Modus des @@ -186,14 +412,16 @@ export const polylineCommand: Command = { if (s.phase === "next" && s.points.length >= 2) { const pts = s.points; const close = s.closed && pts.length >= 3; + const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges; return [ - { phase: "start", lastPoint: null, closed: s.closed } as PolyIdle, - { draft: null, done: true, commit: (p) => appendPolyline(p, pts, close, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, + { draft: null, done: true, commit: (p) => appendPolyline(p, pts, bl, close, ctx) }, ]; } - return idle(s.closed); + return idle(s.closed, s.arc, s.tangent); }, - onCancel: (state): [CommandState, CommandResult] => idle((state as PolyState).closed), + onCancel: (state): [CommandState, CommandResult] => + idle((state as PolyState).closed, (state as PolyState).arc, (state as PolyState).tangent), // Tab-Feld-Zyklus nur im „next"-Schritt: Länge + Winkel relativ zum letzten // Punkt. (Erster Punkt = freie Koordinate, kein Feld-Modus.) diff --git a/src/commands/cmds/ray.test.ts b/src/commands/cmds/ray.test.ts new file mode 100644 index 0000000..147fcd0 --- /dev/null +++ b/src/commands/cmds/ray.test.ts @@ -0,0 +1,87 @@ +/** + * `rayCommand` — zwei Punkte → `Drawing2DGeom["ray"]` (nur a/b gespeichert; + * die einseitige „unendliche" Verlängerung über `b` hinaus passiert beim + * Rendern, `a` bleibt der feste Anker). + */ + +import { describe, it, expect } from "vitest"; +import { rayCommand } from "./ray"; +import type { CommandContext, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("rayCommand", () => { + it("zwei Punkte → shape:'ray' mit exakt a/b (keine Verlängerung im Modell)", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterStart] = rayCommand.onInput( + rayCommand.init(), + { kind: "point", point: { x: 0, y: 0 } }, + ctx, + ); + const [, result] = rayCommand.onInput( + afterStart, + { kind: "point", point: { x: 4, y: 0 } }, + ctx, + ); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("ray"); + if (g.shape === "ray") { + expect(g.a).toEqual({ x: 0, y: 0 }); + expect(g.b).toEqual({ x: 4, y: 0 }); + } + }); + + it("Null-Strecke (gleicher Punkt) committet nichts", () => { + const p = project(); + const ctx = makeCtx(p); + const [afterStart] = rayCommand.onInput( + rayCommand.init(), + { kind: "point", point: { x: 1, y: 1 } }, + ctx, + ); + const [, result] = rayCommand.onInput( + afterStart, + { kind: "point", point: { x: 1, y: 1 } }, + ctx, + ); + expect(result.commit).toBeUndefined(); + expect(result.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/ray.ts b/src/commands/cmds/ray.ts new file mode 100644 index 0000000..dff9979 --- /dev/null +++ b/src/commands/cmds/ray.ts @@ -0,0 +1,137 @@ +// Strahl (Nutzer-Wunsch: „Ray, halb-unendliche Linie — nur xline, beidseitig +// unendlich, existiert") — wie `xline`, aber nur EINSEITIG (über den +// Richtungspunkt hinaus) verlängert; der Startpunkt bleibt ein fester Anker. +// Schritte: +// 1) „Anker:" → Punkt +// 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit + +import type { Drawing2D } from "../../model/types"; +import { segmentHud, uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandField, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const DEG = Math.PI / 180; +const RAY_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const segAngleDeg = (a: Vec2, b: Vec2): number => + (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; + +const LINE_FIELDS: CommandField[] = [ + { id: "length", labelKey: "cmd.field.length" }, + { id: "angle", labelKey: "cmd.field.angle" }, +]; + +function lineEndFromFields(a: Vec2, locks: Record, cursor: Vec2 | null): Vec2 { + const ref = cursor ?? a; + const length = "length" in locks ? locks.length : segLen(a, ref); + const angleDeg = "angle" in locks ? locks.angle : segAngleDeg(a, ref); + const ang = angleDeg * DEG; + return { x: a.x + Math.cos(ang) * length, y: a.y + Math.sin(ang) * length }; +} + +interface RayIdle extends CommandState { + phase: "start"; +} +interface RayDrawing extends CommandState { + phase: "end"; + a: Vec2; + cursor: Vec2 | null; +} +type RayState = RayIdle | RayDrawing; + +/** Vorschau: kurzes Segment PLUS Verlängerung NUR über den Cursor hinaus (Anker bleibt fest). */ +function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { + const preview: DraftShape[] = []; + if (cursor && segLen(a, cursor) >= EPS) { + const len = segLen(a, cursor); + const ux = (cursor.x - a.x) / len; + const uy = (cursor.y - a.y) / len; + preview.push({ + kind: "line", + a, + b: { x: cursor.x + ux * RAY_PREVIEW_EXT_M, y: cursor.y + uy * RAY_PREVIEW_EXT_M }, + }); + } + const draft: ToolDraft = { preview, vertices: [a] }; + if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor); + return draft; +} + +function appendRay(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "ray", a, b }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +export const rayCommand: Command = { + name: "ray", + labelKey: "cmd.ray.label", + prompt: (s) => ((s as RayState).phase === "end" ? "cmd.ray.end" : "cmd.ray.start"), + accepts: () => ["point", "number"], + options: () => [], + init: (): RayIdle => ({ phase: "start", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as RayState; + if (input.kind !== "point") return [s, { draft: s.phase === "end" ? rayDraft(s.a, s.cursor) : null }]; + const pt = input.point; + if (s.phase !== "end") { + const next: RayDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; + return [next, { draft: rayDraft(pt, pt) }]; + } + if (segLen(s.a, pt) < EPS) { + return [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; + } + const a = s.a; + return [ + { phase: "start", lastPoint: null }, + { draft: null, done: true, commit: (p) => appendRay(p, a, pt, ctx) }, + ]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as RayState; + if (s.phase !== "end") return [s, { draft: null }]; + const next: RayDrawing = { ...s, cursor: point }; + return [next, { draft: rayDraft(s.a, point) }]; + }, + + onConfirm: (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null }, + { draft: null, done: true }, + ], + onCancel: (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null }, + { draft: null, done: true }, + ], + + fields: (state) => ((state as RayState).phase === "end" ? LINE_FIELDS : []), + pointFromFields: (state, locks, cursor) => { + const s = state as RayState; + if (s.phase !== "end") return null; + return lineEndFromFields(s.a, locks, cursor); + }, + fieldValues: (state, _locks, cursor): Record => { + const s = state as RayState; + if (s.phase !== "end" || !cursor) return {}; + return { + length: segLen(s.a, cursor), + angle: ((segAngleDeg(s.a, cursor) % 360) + 360) % 360, + }; + }, +}; diff --git a/src/commands/cmds/rect.test.ts b/src/commands/cmds/rect.test.ts new file mode 100644 index 0000000..8c39f3c --- /dev/null +++ b/src/commands/cmds/rect.test.ts @@ -0,0 +1,177 @@ +/** + * `rectCommand` — drei Konstruktionsmethoden (2-Punkt/3-Punkt-gedreht/ + * Zentrum, alle achsparallel-agnostisch) + NEU Eck-Radius (rein additiv, + * gilt für alle drei Methoden, Default 0 = scharfe Ecken, byte-identisch + * zum bisherigen Verhalten). + */ + +import { describe, it, expect } from "vitest"; +import { rectCommand } from "./rect"; +import type { CommandContext, CommandState, Project, Vec2 } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const dist = (a: Vec2, b: Vec2) => Math.hypot(b.x - a.x, b.y - a.y); + +/** Treibt die „radius"-Option auf den Ziel-Wert (Modul-Singleton, s. Leader/ + * Array/Polygon-Tests für dasselbe Muster — Reihenfolge-unabhängig). */ +function setRadius(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + let opts = rectCommand.options(s); + while (opts.find((o) => o.id === "radius")?.value !== String(target)) { + [s] = rectCommand.onInput(s, { kind: "option", id: "radius" }, ctx); + opts = rectCommand.options(s); + } + return s; +} + +describe("rectCommand — 2-Punkt (Default-Methode), Radius 0", () => { + it("zwei gegenüberliegende Ecken → shape:'rect'", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setRadius(rectCommand.init(), ctx, 0); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 4, y: 2 } }, ctx); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("rect"); + if (g.shape === "rect") { + expect(g.min).toEqual({ x: 0, y: 0 }); + expect(g.max).toEqual({ x: 4, y: 2 }); + } + }); +}); + +describe("rectCommand — Eck-Radius", () => { + it("Default ist 0 (scharfe Ecken)", () => { + expect(rectCommand.options(rectCommand.init()).find((o) => o.id === "radius")?.value).toBe("0"); + }); + + it("zyklt 0 → 0.02 → 0.05 → 0.1 → 0.2 → 0.3 → 0", () => { + const ctx = makeCtx(project()); + let state = rectCommand.init() as CommandState; + const seq = [0.02, 0.05, 0.1, 0.2, 0.3, 0]; + for (const target of seq) { + state = setRadius(state, ctx, target); + expect(rectCommand.options(state).find((o) => o.id === "radius")?.value).toBe(String(target)); + } + }); + + it("Radius > 0 committet eine geschlossene 'polyline' mit bulge statt 'rect' (2-Punkt-Methode)", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setRadius(rectCommand.init(), ctx, 0.2); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 4, y: 2 } }, ctx); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + expect(g.closed).toBe(true); + expect(g.pts.length).toBe(8); // 2 Tangentenpunkte je der 4 Ecken + expect(g.bulge?.length).toBe(8); + // Genau 4 Bogensegmente (Fillets), 4 gerade (die Kanten dazwischen). + const realBulges = (g.bulge ?? []).filter((b) => Math.abs(b) > 1e-9); + expect(realBulges.length).toBe(4); + // Die Tangentenpunkte der Ecke (0,0) liegen exakt Radius 0.2 von der + // ursprünglichen scharfen Ecke entfernt, auf beiden angrenzenden Kanten. + const nearOrigin = g.pts.filter((pt) => dist(pt, { x: 0, y: 0 }) < 1); // grobe Vorauswahl + expect(nearOrigin.length).toBe(2); + for (const pt of nearOrigin) expect(dist(pt, { x: 0, y: 0 })).toBeCloseTo(0.2, 6); + } + }); + + it("Radius 0 bleibt weiterhin 'rect' (byte-identisch zum alten Verhalten)", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setRadius(rectCommand.init(), ctx, 0); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 4, y: 2 } }, ctx); + const next = result.commit!(p); + expect(next.drawings2d[0].geom.shape).toBe("rect"); + }); + + it("wird auf die halbe kürzere Kantenlänge geklammert (Radius grösser als möglich)", () => { + const p = project(); + const ctx = makeCtx(p); + // Rechteck 1×0.4 — kürzere Kante 0.4, max. sinnvoller Radius 0.2. + let state = setRadius(rectCommand.init(), ctx, 0.3); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 1, y: 0.4 } }, ctx); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + const nearOrigin = g.pts.filter((pt) => dist(pt, { x: 0, y: 0 }) < 0.3); + for (const pt of nearOrigin) { + expect(dist(pt, { x: 0, y: 0 })).toBeLessThanOrEqual(0.2 + 1e-6); + } + } + }); + + it("wirkt auch bei der Zentrum-Methode", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setRadius(rectCommand.init(), ctx, 0.05); + [state] = rectCommand.onInput(state, { kind: "option", id: "method" }, ctx); // corner → three + [state] = rectCommand.onInput(state, { kind: "option", id: "method" }, ctx); // three → center + expect(rectCommand.options(state).find((o) => o.id === "method")?.value).toBe("center"); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Mittelpunkt + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 2, y: 1 } }, ctx); // Ecke + const next = result.commit!(p); + expect(next.drawings2d[0].geom.shape).toBe("polyline"); + }); + + it("wirkt bei der 3-Punkt-Methode (gedreht) — Ergebnis bleibt eine 'polyline' mit bulge", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setRadius(rectCommand.init(), ctx, 0.05); + [state] = rectCommand.onInput(state, { kind: "option", id: "method" }, ctx); // corner → three + expect(rectCommand.options(state).find((o) => o.id === "method")?.value).toBe("3pt"); + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); // Basis-Start + [state] = rectCommand.onInput(state, { kind: "point", point: { x: 2, y: 0 } }, ctx); // Basis-Ende + const [, result] = rectCommand.onInput(state, { kind: "point", point: { x: 0, y: 1 } }, ctx); // Höhe + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + const realBulges = (g.bulge ?? []).filter((b) => Math.abs(b) > 1e-9); + expect(realBulges.length).toBe(4); + } + }); +}); diff --git a/src/commands/cmds/rect.ts b/src/commands/cmds/rect.ts index bf1c26c..aa3e0bb 100644 --- a/src/commands/cmds/rect.ts +++ b/src/commands/cmds/rect.ts @@ -15,9 +15,24 @@ // // Getippte Maße: die zweite/dritte Ecke kann relativ (`r,`) eingegeben // werden (die Engine löst `r…` relativ zu lastPoint auf). +// +// Eck-Radius (Nutzer-Wunsch: „kein Rundeck-Eck-Radius bei der Erzeugung, +// `Drawing2DGeom["rect"]` hat gar kein Radius-Feld, nur nachträgliches +// fillet möglich"): zweite, IMMER sichtbare Option „Radius" (zyklisch durch +// gängige Architektur-Werte 0/2/5/10/20/30 cm), orthogonal zur Methode — gilt +// für alle drei Konstruktionsarten (arbeitet rein über die 4 tatsächlichen +// Eckpunkte, unabhängig von Achsparallelität/Drehung). Bei Radius 0 (Default) +// BYTE-IDENTISCH zum bisherigen Verhalten (`shape:"rect"` bzw. scharfe +// Polylinie); bei Radius > 0 committet eine geschlossene `polyline` mit +// `bulge`-Bogensegmenten an den vier Ecken (kein neues Modellfeld nötig — +// `Drawing2DGeom["polyline"].bulge` existiert bereits für genau diesen Zweck, +// s. `model/types.ts`). Radius wird auf die halbe kürzere Kantenlänge +// geklammert (sonst würden sich benachbarte Fillets überlappen). import type { Drawing2D } from "../../model/types"; import { deltaHud, segmentHud, uniqueId } from "../../tools/types"; +import { filletCorner } from "../../geometry/kernel2d"; +import { bulgeArcPoints, bulgeThroughPoint } from "../../geometry/bulge"; import type { Command, CommandContext, @@ -49,6 +64,13 @@ const methodOption = (m: RectMethod): CmdOption => ({ value: methodValue(m), }); +/** Eck-Radius: gängige Architektur-Werte (Meter), 0 = scharfe Ecken (Default). */ +const RADIUS_PRESETS = [0, 0.02, 0.05, 0.1, 0.2, 0.3]; +let lastRadius = 0; +const nextRadius = (): number => RADIUS_PRESETS[(RADIUS_PRESETS.indexOf(lastRadius) + 1) % RADIUS_PRESETS.length]; +/** Umschalt-Option fürs Eck-Radius (tippbar als „r", IMMER sichtbar — gilt für alle Methoden). */ +const radiusOption = (): CmdOption => ({ id: "radius", labelKey: "cmd.rect.radius", value: String(lastRadius) }); + /** Tab-Felder des Breite/Höhe-Schritts (2-Punkt & Zentrum). */ const RECT_FIELDS: CommandField[] = [ { id: "width", labelKey: "cmd.field.width" }, @@ -194,10 +216,61 @@ function rectGeom(a: Vec2, b: Vec2): { min: Vec2; max: Vec2 } { }; } +// ── Eck-Radius ─────────────────────────────────────────────────────────────── + +/** + * Rundet die 4 Ecken eines Rechtecks (beliebige Umlaufreihenfolge/Ausrichtung + * — arbeitet rein über die tatsächliche Punkt-Geometrie, keine Achsparallel- + * Annahme) mit Radius `r`, geklammert auf die halbe kürzeste Kantenlänge + * (sonst würden sich benachbarte Fillets überlappen). `null` bei `r<=0` oder + * wenn selbst der geklammerte Radius nicht mehr passt (entartetes Rechteck). + */ +function roundedRectPts(corners: Vec2[], r: number): { pts: Vec2[]; bulge: number[] } | null { + if (r < EPS) return null; + const n = corners.length; + let maxR = Infinity; + for (let i = 0; i < n; i++) { + maxR = Math.min(maxR, segLen(corners[i], corners[(i + 1) % n]) / 2); + } + const rr = Math.min(r, maxR - EPS); + if (rr < EPS) return null; + + const pts: Vec2[] = []; + const bulge: number[] = []; + for (let i = 0; i < n; i++) { + const prev = corners[(i - 1 + n) % n]; + const cur = corners[i]; + const next = corners[(i + 1) % n]; + const f = filletCorner(cur, prev, next, rr); + if (!f) return null; // (nahezu) kollineare Ecke — sollte bei einem Rechteck nicht vorkommen + // Bogen-Mittelpunkt: auf dem Fillet-Kreis, in Richtung der ursprünglichen + // (jetzt weggerundeten) Ecke vom Bogen-Zentrum aus gesehen. + const dx = cur.x - f.center.x; + const dy = cur.y - f.center.y; + const dl = Math.hypot(dx, dy) || 1; + const mid: Vec2 = { x: f.center.x + (dx / dl) * rr, y: f.center.y + (dy / dl) * rr }; + pts.push(f.tangentA, f.tangentB); + bulge.push(bulgeThroughPoint(f.tangentA, mid, f.tangentB), 0); + } + return { pts, bulge }; +} + +/** Tessellierte Punkte einer gerundeten geschlossenen Kontur — für die Live-Vorschau. */ +function tessellateRounded(pts: Vec2[], bulge: number[]): Vec2[] { + const out: Vec2[] = []; + const n = pts.length; + for (let i = 0; i < n; i++) { + out.push(...bulgeArcPoints(pts[i], pts[(i + 1) % n], bulge[i]).slice(0, -1)); + } + return out; +} + // ── Vorschau ───────────────────────────────────────────────────────────────── function corners4Draft(pts: Vec2[], hud: ToolDraft["hud"] | null): ToolDraft { - const preview: DraftShape[] = [{ kind: "poly", pts, closed: true }]; + const rounded = roundedRectPts(pts, lastRadius); + const previewPts = rounded ? tessellateRounded(rounded.pts, rounded.bulge) : pts; + const preview: DraftShape[] = [{ kind: "poly", pts: previewPts, closed: true }]; const draft: ToolDraft = { preview, vertices: [pts[0]] }; if (hud) draft.hud = hud; return draft; @@ -274,6 +347,27 @@ function appendRotated(p: Project, pts: Vec2[], ctx: CommandContext): Project { return { ...p, drawings2d: [...p.drawings2d, d] }; } +/** + * Gerundetes Rechteck (Eck-Radius > 0) als geschlossene `polyline` MIT + * `bulge` — ersetzt `appendRect`/`appendRotated`, wenn `lastRadius` > 0 ist, + * unabhängig von der Konstruktionsmethode (`corners` sind die 4 scharfen + * Ecken, egal ob achsparallel oder gedreht). No-Op, wenn der Radius nicht + * passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten + * Rechteck). + */ +function appendRectRounded(p: Project, corners: Vec2[], ctx: CommandContext): Project { + const rr = roundedRectPts(corners, lastRadius); + if (!rr) return p; + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + const idle = (method: RectMethod): [CommandState, CommandResult] => [ { phase: "corner1", lastPoint: null, method } as RectIdle, { draft: null, done: true }, @@ -295,7 +389,7 @@ export const rectCommand: Command = { labelKey: "cmd.rect.label", prompt: (s) => promptKey(s as RectState), accepts: () => ["point", "number", "option"], - options: (s) => [methodOption((s as RectState).method)], + options: (s) => [methodOption((s as RectState).method), radiusOption()], init: (): RectIdle => ({ phase: "corner1", lastPoint: null, method: "corner" }), onInput: (state, input, ctx): [CommandState, CommandResult] => { @@ -309,6 +403,13 @@ export const rectCommand: Command = { const ns: RectIdle = { phase: "corner1", lastPoint: null, method: m }; return [ns, { draft: null }]; } + if (input.id === "radius") { + // Radius zyklisch umschalten — anders als „Methode" wird die laufende + // Konstruktion NICHT verworfen, nur die Vorschau aktualisiert (der + // Radius wirkt erst beim Commit, betrifft also keine Punkt-Historie). + lastRadius = nextRadius(); + return [s, { draft: draftFor(s) }]; + } return [s, { draft: null }]; } @@ -341,22 +442,30 @@ export const rectCommand: Command = { draft: null, done: true, commit: (p) => { - if (method === "center") { - const g = centerGeom(a, pt); - return appendRect(p, g.min, g.max, ctx); + const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt); + if (lastRadius >= EPS) { + const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; + return appendRectRounded(p, corners, ctx); } - const g = rectGeom(a, pt); return appendRect(p, g.min, g.max, ctx); }, }, ]; } - // phase "rise" (3-Punkt) → committen als gedrehte, geschlossene Polylinie. + // phase "rise" (3-Punkt) → committen als gedrehte, geschlossene Polylinie + // (scharf) oder mit gerundeten Ecken (Radius > 0). const { a, b } = s; return [ { phase: "corner1", lastPoint: null, method: "three" } as RectIdle, - { draft: null, done: true, commit: (p) => appendRotated(p, rotatedCorners(a, b, pt), ctx) }, + { + draft: null, + done: true, + commit: (p) => { + const corners = rotatedCorners(a, b, pt); + return lastRadius >= EPS ? appendRectRounded(p, corners, ctx) : appendRotated(p, corners, ctx); + }, + }, ]; }, diff --git a/src/commands/cmds/revcloud.test.ts b/src/commands/cmds/revcloud.test.ts new file mode 100644 index 0000000..2714f7a --- /dev/null +++ b/src/commands/cmds/revcloud.test.ts @@ -0,0 +1,141 @@ +/** + * `revcloudCommand` — Punktfolge (wie `polyline`) → geschlossene/offene + * `polyline` mit Beulen-`bulge` (Revisionswolke). + */ + +import { describe, it, expect } from "vitest"; +import { revcloudCommand } from "./revcloud"; +import type { CommandContext, CommandState, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +/** Treibt die „arcSize"-Option auf den Ziel-Wert (Modul-Singleton, s. Polygon-Tests). */ +function setArcSize(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + let opts = revcloudCommand.options(s); + while (opts.find((o) => o.id === "arcSize")?.value !== `${target}m`) { + [s] = revcloudCommand.onInput(s, { kind: "option", id: "arcSize" }, ctx); + opts = revcloudCommand.options(s); + } + return s; +} + +describe("revcloudCommand", () => { + it("Enter nach ≥2 Punkten committet eine OFFENE Polylinie mit bulge", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setArcSize(revcloudCommand.init(), ctx, 0.5); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 3, y: 0 } }, ctx); + const [, result] = revcloudCommand.onConfirm(state, ctx); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") { + expect(g.closed).toBe(false); + expect(g.bulge?.length).toBeGreaterThan(0); + expect(g.bulge?.every((b) => Math.abs(b) > 1e-9)).toBe(true); + // Start-/Endpunkt der expandierten Kontur bleiben die Original-Klicks. + expect(g.pts[0]).toEqual({ x: 0, y: 0 }); + expect(g.pts[g.pts.length - 1]).toEqual({ x: 3, y: 0 }); + } + }); + + it("Klick nahe dem Startpunkt (≥3 Punkte) committet als GESCHLOSSENEN Ring", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setArcSize(revcloudCommand.init(), ctx, 0.5); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 4, y: 4 } }, ctx); + const [, result] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0.05, y: 0.02 } }, ctx); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") { + expect(g.closed).toBe(true); + } + }); + + it("die explizite 'Schliessen'-Option committet ebenfalls als Ring", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setArcSize(revcloudCommand.init(), ctx, 0.5); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 4, y: 4 } }, ctx); + expect(revcloudCommand.options(state).some((o) => o.id === "close")).toBe(true); + const [, result] = revcloudCommand.onInput(state, { kind: "option", id: "close" }, ctx); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + const g = next.drawings2d[0].geom; + if (g.shape === "polyline") expect(g.closed).toBe(true); + }); + + it("'Schliessen'-Option ist erst ab 3 Punkten verfügbar", () => { + const ctx = makeCtx(project()); + let state = revcloudCommand.init() as CommandState; + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + expect(revcloudCommand.options(state).some((o) => o.id === "close")).toBe(false); + }); + + it("Beulengrösse zyklt durch die Presets", () => { + const ctx = makeCtx(project()); + let state = setArcSize(revcloudCommand.init(), ctx, 0.2); + expect(revcloudCommand.options(state).find((o) => o.id === "arcSize")?.value).toBe("0.2m"); + state = setArcSize(state, ctx, 1.2); + expect(revcloudCommand.options(state).find((o) => o.id === "arcSize")?.value).toBe("1.2m"); + }); + + it("Enter mit nur 1 Punkt committet nichts (kehrt in den Ruhezustand zurück)", () => { + const ctx = makeCtx(project()); + let state = revcloudCommand.init() as CommandState; + [state] = revcloudCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + const [after, result] = revcloudCommand.onConfirm(state, ctx); + expect(result.commit).toBeUndefined(); + expect(result.done).toBe(true); + expect((after as { phase: string }).phase).toBe("start"); + }); + + it("onCancel kehrt in den Ruhezustand zurück", () => { + const [, res] = revcloudCommand.onCancel(revcloudCommand.init()); + expect(res.done).toBe(true); + expect(res.commit).toBeUndefined(); + }); +}); diff --git a/src/commands/cmds/revcloud.ts b/src/commands/cmds/revcloud.ts new file mode 100644 index 0000000..00dc278 --- /dev/null +++ b/src/commands/cmds/revcloud.ts @@ -0,0 +1,154 @@ +// Revisionswolke (Nutzer-Wunsch: „Keine Revisionswolken/Markup-Werkzeuge"). +// Schritte (wie `polyline.ts`, aber ohne dessen Bogen-/Tangenten-Unteroptionen +// — JEDES Segment wird automatisch zu Beulen, s. `geometry/revisionCloud.ts`): +// 1) „Startpunkt:" → Punkt +// 2) „Nächster Punkt ( Schliessen ):" → Punkt … Enter beendet OFFEN (≥2 +// Punkte); Klick nahe dem Startpunkt ODER die Option „Schliessen" +// committet als RING (≥3 Punkte). +// Beulengrösse (Ziel-Bogenlänge) per Option, zyklisch, persistiert über +// Aufrufe hinweg (wie `lastSides` bei `polygon.ts`). + +import type { Drawing2D } from "../../model/types"; +import { bulgeArcPoints } from "../../geometry/bulge"; +import { revisionCloudPts } from "../../geometry/revisionCloud"; +import { segmentHud, uniqueId } from "../../tools/types"; +import type { + CmdOption, + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug + +const ARC_SIZE_PRESETS = [0.2, 0.3, 0.5, 0.8, 1.2]; +let lastArcSize = 0.3; +const nextArcSize = (): number => + ARC_SIZE_PRESETS[(ARC_SIZE_PRESETS.indexOf(lastArcSize) + 1) % ARC_SIZE_PRESETS.length]; + +const ARC_SIZE_OPTION: CmdOption = { id: "arcSize", labelKey: "cmd.revcloud.arcSize" }; +const CLOSE: CmdOption = { id: "close", labelKey: "cmd.revcloud.close" }; + +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); + +interface RevcloudIdle extends CommandState { + phase: "start"; +} +interface RevcloudDrawing extends CommandState { + phase: "next"; + points: Vec2[]; + cursor: Vec2 | null; +} +type RevcloudState = RevcloudIdle | RevcloudDrawing; + +/** Vorschau: die tatsächliche Beulen-Kontur (tesselliert), inkl. Gummiband zum Cursor. */ +function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { + const all = cursor ? [...points, cursor] : points; + const expanded = revisionCloudPts(all, false, lastArcSize); + const pts: Vec2[] = []; + if (expanded) { + pts.push(expanded.pts[0]); + for (let i = 0; i < expanded.pts.length - 1; i++) { + const sub = bulgeArcPoints(expanded.pts[i], expanded.pts[i + 1], expanded.bulge[i]); + for (let k = 1; k < sub.length; k++) pts.push(sub[k]); + } + } + const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }]; + const draft: ToolDraft = { preview, vertices: points }; + const last = points[points.length - 1]; + if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); + return draft; +} + +function appendRevcloud(p: Project, points: Vec2[], closed: boolean, ctx: CommandContext): Project { + const expanded = revisionCloudPts(points, closed, lastArcSize); + if (!expanded) return p; + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null } as RevcloudIdle, + { draft: null, done: true }, +]; + +export const revcloudCommand: Command = { + name: "revcloud", + labelKey: "cmd.revcloud.label", + prompt: (s) => ((s as RevcloudState).phase === "next" ? "cmd.revcloud.next" : "cmd.revcloud.start"), + accepts: () => ["point", "option"], + options: (s) => { + const st = s as RevcloudState; + const base = [{ ...ARC_SIZE_OPTION, value: `${lastArcSize}m` }]; + return st.phase === "next" && st.points.length >= 3 ? [CLOSE, ...base] : base; + }, + init: (): RevcloudIdle => ({ phase: "start", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as RevcloudState; + + if (input.kind === "option") { + if (input.id === "arcSize") { + lastArcSize = nextArcSize(); + return [ + s, + { draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null }, + ]; + } + if (input.id === "close" && s.phase === "next" && s.points.length >= 3) { + const pts = s.points; + return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + } + return [s, { draft: null }]; + } + + if (input.kind !== "point") { + return [s, { draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null }]; + } + const pt = input.point; + + if (s.phase !== "next") { + const ns: RevcloudDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt }; + return [ns, { draft: revcloudDraft([pt], pt) }]; + } + + // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring). + if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { + const pts = s.points; + return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, true, ctx) }]; + } + const points = [...s.points, pt]; + const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; + return [ns, { draft: revcloudDraft(points, pt) }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as RevcloudState; + if (s.phase !== "next") return [s, { draft: null }]; + const ns: RevcloudDrawing = { ...s, cursor: point }; + return [ns, { draft: revcloudDraft(s.points, point) }]; + }, + + // Enter/Space/Rechtsklick: Zug als OFFENE Wolke beenden (≥2 Punkte). + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as RevcloudState; + if (s.phase === "next" && s.points.length >= 2) { + const pts = s.points; + return [idle()[0], { draft: null, done: true, commit: (p) => appendRevcloud(p, pts, false, ctx) }]; + } + return idle(); + }, + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/rotate.test.ts b/src/commands/cmds/rotate.test.ts new file mode 100644 index 0000000..8e3394c --- /dev/null +++ b/src/commands/cmds/rotate.test.ts @@ -0,0 +1,113 @@ +/** + * Rotate-Befehl: beide Eingabewege (getippter Winkel bzw. Referenz + neue + * Richtung) und der No-op bei leerer Auswahl. + */ + +import { describe, expect, it } from "vitest"; +import { rotateCommand } from "./rotate"; +import { sampleProject } from "../../model/sampleProject"; +import type { CommandContext, CommandSelection, CommandState, Project, Vec2 } from "../types"; + +/** Eine Linie von (0,0) nach (2,0) als Testobjekt. */ +function projectWithLine(): Project { + return { + ...sampleProject, + drawings2d: [ + { + id: "ln", + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 2, y: 0 } }, + }, + ], + }; +} + +const EMPTY_SEL: CommandSelection = { wallIds: [], drawingId: null }; +const LINE_SEL: CommandSelection = { wallIds: [], drawingId: "ln" }; + +function ctxFor(project: Project, selection: CommandSelection): CommandContext { + return { + project, + selection, + level: project.drawingLevels[0], + defaultCategoryCode: project.layers[0].code, + } as CommandContext; +} + +/** Spielt Eingaben ab und liefert das (ggf. committete) Projekt. */ +function run( + inputs: ({ pt: Vec2 } | { num: number })[], + selection: CommandSelection = LINE_SEL, +): Project { + let state: CommandState = rotateCommand.init(); + let project = projectWithLine(); + for (const step of inputs) { + const input = "pt" in step ? ({ kind: "point", point: step.pt } as const) : ({ kind: "number", value: step.num } as const); + const [next, res] = rotateCommand.onInput(state, input, ctxFor(project, selection)); + state = next; + if (res.commit) project = res.commit(project); + } + return project; +} + +const line = (p: Project) => { + const g = p.drawings2d[0].geom; + if (g.shape !== "line") throw new Error("keine Linie"); + return g; +}; + +describe("rotate — getippter Winkel", () => { + it("dreht um den gewählten Drehpunkt (90° um den Ursprung)", () => { + const g = line(run([{ pt: { x: 0, y: 0 } }, { num: 90 }])); + expect(g.a.x).toBeCloseTo(0, 9); + expect(g.a.y).toBeCloseTo(0, 9); + // (2,0) → (0,2) + expect(g.b.x).toBeCloseTo(0, 9); + expect(g.b.y).toBeCloseTo(2, 9); + }); + + it("der Drehpunkt bleibt fix — auch abseits des Objekts", () => { + const g = line(run([{ pt: { x: 2, y: 0 } }, { num: 180 }])); + // Drehpunkt (2,0): (0,0) → (4,0), (2,0) bleibt. + expect(g.a.x).toBeCloseTo(4, 9); + expect(g.b.x).toBeCloseTo(2, 9); + }); + + it("negative Winkel drehen im Uhrzeigersinn", () => { + const g = line(run([{ pt: { x: 0, y: 0 } }, { num: -90 }])); + expect(g.b.y).toBeCloseTo(-2, 9); + }); +}); + +describe("rotate — Referenz + neue Richtung", () => { + it("dreht um den Winkel ZWISCHEN den beiden Richtungen", () => { + // Referenz zeigt nach +X, Ziel nach +Y ⇒ 90°. + const g = line(run([{ pt: { x: 0, y: 0 } }, { pt: { x: 1, y: 0 } }, { pt: { x: 0, y: 5 } }])); + expect(g.b.x).toBeCloseTo(0, 9); + expect(g.b.y).toBeCloseTo(2, 9); + }); + + it("die LÄNGE der Referenz ist egal — nur die Richtung zählt", () => { + const near = line(run([{ pt: { x: 0, y: 0 } }, { pt: { x: 1, y: 1 } }, { pt: { x: -1, y: 1 } }])); + const far = line(run([{ pt: { x: 0, y: 0 } }, { pt: { x: 9, y: 9 } }, { pt: { x: -3, y: 3 } }])); + expect(near.b.x).toBeCloseTo(far.b.x, 9); + expect(near.b.y).toBeCloseTo(far.b.y, 9); + }); +}); + +describe("rotate — Randfälle", () => { + it("ohne Auswahl passiert nichts (No-op, Befehl beendet)", () => { + const before = projectWithLine(); + const after = run([{ pt: { x: 0, y: 0 } }, { num: 90 }], EMPTY_SEL); + expect(after.drawings2d).toEqual(before.drawings2d); + }); + + it("ein Referenzpunkt AUF dem Drehpunkt wird ignoriert (keine Richtung)", () => { + // Zweiter Klick = Drehpunkt selbst → bleibt im Winkel-Schritt, nichts committet. + const g = line(run([{ pt: { x: 1, y: 1 } }, { pt: { x: 1, y: 1 } }])); + expect(g.b.x).toBeCloseTo(2, 9); + expect(g.b.y).toBeCloseTo(0, 9); + }); +}); diff --git a/src/commands/cmds/rotate.ts b/src/commands/cmds/rotate.ts new file mode 100644 index 0000000..6b5b2e3 --- /dev/null +++ b/src/commands/cmds/rotate.ts @@ -0,0 +1,203 @@ +// Rotate — dreht die AKTUELLE Auswahl um einen frei gewählten Drehpunkt. +// Schritte (AutoCAD-ROTATE-Muster, inkl. Referenz-Variante): +// 1) „Drehpunkt:" → Punkt +// 2) „Winkel:" → ZAHL (Grad) ⇒ sofort drehen und fertig +// ODER Punkt ⇒ Referenzrichtung, weiter mit 3) +// 3) „Neue Richtung:" → Punkt (Live-Vorschau) → commit +// +// Der getippte Winkel ist der schnelle Normalfall; die Zwei-Punkt-Variante ist +// die „Referenz"-Eingabe (etwas an einer vorhandenen Kante ausrichten, ohne +// deren Winkel zu kennen). +// +// Die Auswahl kommt vorab über `ctx.selection` (erst selektieren, dann Befehl — +// wie Move/Copy/Mirror). Gedreht wird über den bestehenden, getesteten +// `commitTransform` (op:"rotate", mode:"move") — er bewegt das ORIGINAL, es +// entsteht keine Kopie. + +import { + commitTransform, + hasTransformSelection, + toTransformSel, + transformPreview, +} from "../../tools/transform"; +import type { + Command, + CommandResult, + CommandSelection, + CommandState, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const DEG = Math.PI / 180; +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const angleDeg = (c: Vec2, p: Vec2): number => (Math.atan2(p.y - c.y, p.x - c.x) * 180) / Math.PI; + + +/** + * Punkte-Tripel für `transformFn("rotate", …)`: Drehpunkt, Referenzrichtung, + * Zielrichtung. Für einen GETIPPTEN Winkel werden Referenz (+X-Achse) und Ziel + * synthetisch erzeugt — der Drehwinkel ist dann genau der eingegebene. + */ +function rotatePts(center: Vec2, deg: number): Vec2[] { + const a = deg * DEG; + return [ + center, + { x: center.x + 1, y: center.y }, + { x: center.x + Math.cos(a), y: center.y + Math.sin(a) }, + ]; +} + +interface RotBase extends CommandState { + phase: "base"; +} +interface RotAngle extends CommandState { + phase: "angle"; + sel: CommandSelection; + center: Vec2; + cursor: Vec2 | null; +} +interface RotTarget extends CommandState { + phase: "target"; + sel: CommandSelection; + center: Vec2; + ref: Vec2; + cursor: Vec2 | null; +} +interface RotDone extends CommandState { + phase: "done"; +} +type RotState = RotBase | RotAngle | RotTarget | RotDone; + +/** Live-Vorschau: gedrehte Auswahl + Drehpunkt/Schenkel als Hilfsgeometrie. */ +function rotDraft( + project: Project, + sel: CommandSelection, + pts: Vec2[], + deg: number, + legs: Vec2[], +): ToolDraft { + const preview = transformPreview(project, toTransformSel(sel), "rotate", pts, "move", 1); + const center = pts[0]; + return { + preview: [...preview, ...legs.map((p) => ({ kind: "line" as const, a: center, b: p }))], + vertices: [center], + hud: { at: legs[legs.length - 1] ?? center, text: `${(((deg % 360) + 360) % 360).toFixed(1)}°` }, + }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "done", lastPoint: null } as RotDone, + { draft: null, done: true }, +]; + +export const rotateCommand: Command = { + name: "rotate", + labelKey: "cmd.rotate.label", + prompt: (s) => { + const rs = s as RotState; + if (rs.phase === "angle") return "cmd.rotate.angle"; + if (rs.phase === "target") return "cmd.rotate.target"; + if (rs.phase === "done") return "cmd.rotate.empty"; + return "cmd.rotate.base"; + }, + // Im Winkel-Schritt sind BEIDE Eingaben gültig: getippte Grad oder ein Punkt. + accepts: (s) => ((s as RotState).phase === "angle" ? ["point", "number"] : ["point"]), + options: () => [], + + init: (): RotBase => ({ phase: "base", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as RotState; + if (s.phase === "done") return idle(); + if (!hasTransformSelection(ctx.selection)) { + return [{ phase: "done", lastPoint: null } as RotDone, { draft: null, done: true }]; + } + + // Getippter Winkel (nur im Winkel-Schritt): sofort drehen. + if (input.kind === "number" && s.phase === "angle") { + const { center, sel } = s; + const pts = rotatePts(center, input.value); + return [ + { phase: "done", lastPoint: null } as RotDone, + { + draft: null, + done: true, + commit: (p) => commitTransform(p, toTransformSel(sel), "rotate", pts, "move", 1), + }, + ]; + } + + if (input.kind !== "point") return [s, { draft: null }]; + const pt = input.point; + + if (s.phase === "base") { + const next: RotAngle = { + phase: "angle", + sel: ctx.selection, + center: pt, + cursor: pt, + lastPoint: pt, + }; + return [next, { draft: null }]; + } + + if (s.phase === "angle") { + // Punkt statt Zahl ⇒ Referenzrichtung; ohne echte Richtung ignorieren. + if (segLen(s.center, pt) < EPS) return [s, { draft: null }]; + const next: RotTarget = { + phase: "target", + sel: s.sel, + center: s.center, + ref: pt, + cursor: pt, + lastPoint: pt, + }; + return [next, { draft: rotDraft(ctx.project, s.sel, rotatePts(s.center, 0), 0, [pt]) }]; + } + + // Zielrichtung → commit. + if (segLen(s.center, pt) < EPS) return [s, { draft: null }]; + const { center, ref, sel } = s; + return [ + { phase: "done", lastPoint: null } as RotDone, + { + draft: null, + done: true, + commit: (p) => + commitTransform(p, toTransformSel(sel), "rotate", [center, ref, pt], "move", 1), + }, + ]; + }, + + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { + const s = state as RotState; + if (s.phase === "angle") { + // Noch keine Referenz: Vorschau gegen die +X-Achse (= getippter Winkel). + const deg = angleDeg(s.center, point); + const ns: RotAngle = { ...s, cursor: point }; + if (segLen(s.center, point) < EPS) return [ns, { draft: null }]; + return [ + ns, + { draft: rotDraft(ctx.project, s.sel, rotatePts(s.center, deg), deg, [point]) }, + ]; + } + if (s.phase === "target") { + const ns: RotTarget = { ...s, cursor: point }; + if (segLen(s.center, point) < EPS) return [ns, { draft: null }]; + const deg = angleDeg(s.center, point) - angleDeg(s.center, s.ref); + return [ + ns, + { + draft: rotDraft(ctx.project, s.sel, [s.center, s.ref, point], deg, [s.ref, point]), + }, + ]; + } + return [s, { draft: null }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/scale.test.ts b/src/commands/cmds/scale.test.ts new file mode 100644 index 0000000..0c835b9 --- /dev/null +++ b/src/commands/cmds/scale.test.ts @@ -0,0 +1,152 @@ +/** + * Scale-Befehl. Schwerpunkt ist die Stelle, an der eine naive Umsetzung falsch + * wäre: `mvGeom` bildet nur PUNKTE ab — Radius, Schrifthöhe und der + * Bemassungs-Abstand müssen beim Skalieren mitziehen, sonst bliebe ein Kreis + * unter 2× gleich gross. + */ + +import { describe, expect, it } from "vitest"; +import { scaleCommand } from "./scale"; +import { sampleProject } from "../../model/sampleProject"; +import type { Drawing2DGeom } from "../../model/types"; +import type { CommandContext, CommandSelection, CommandState, Project, Vec2 } from "../types"; + +function projectWith(geom: Drawing2DGeom): Project { + return { + ...sampleProject, + drawings2d: [ + { + id: "el", + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom, + }, + ], + }; +} + +const SEL: CommandSelection = { wallIds: [], drawingId: "el" }; + +function run( + geom: Drawing2DGeom, + inputs: ({ pt: Vec2 } | { num: number })[], + selection: CommandSelection = SEL, +): Drawing2DGeom { + let state: CommandState = scaleCommand.init(); + let project = projectWith(geom); + for (const step of inputs) { + const input = + "pt" in step + ? ({ kind: "point", point: step.pt } as const) + : ({ kind: "number", value: step.num } as const); + const ctx = { + project, + selection, + level: project.drawingLevels[0], + defaultCategoryCode: project.layers[0].code, + } as CommandContext; + const [next, res] = scaleCommand.onInput(state, input, ctx); + state = next; + if (res.commit) project = res.commit(project); + } + return project.drawings2d[0].geom; +} + +describe("scale — getippter Faktor", () => { + it("skaliert Punkte um den Basispunkt", () => { + const g = run({ shape: "line", a: { x: 1, y: 0 }, b: { x: 3, y: 0 } }, [ + { pt: { x: 1, y: 0 } }, + { num: 2 }, + ]); + if (g.shape !== "line") throw new Error(); + expect(g.a.x).toBeCloseTo(1, 9); // Basispunkt bleibt fix + expect(g.b.x).toBeCloseTo(5, 9); // Abstand 2 → 4 + }); + + it("KREIS: der Radius zieht mit (sonst bliebe er gleich gross)", () => { + const g = run({ shape: "circle", center: { x: 2, y: 0 }, r: 1 }, [ + { pt: { x: 0, y: 0 } }, + { num: 3 }, + ]); + if (g.shape !== "circle") throw new Error(); + expect(g.center.x).toBeCloseTo(6, 9); + expect(g.r).toBeCloseTo(3, 9); + }); + + it("ELLIPSE: beide Halbachsen ziehen mit", () => { + const g = run({ shape: "ellipse", center: { x: 0, y: 0 }, rx: 2, ry: 1, rotation: 0 }, [ + { pt: { x: 0, y: 0 } }, + { num: 0.5 }, + ]); + if (g.shape !== "ellipse") throw new Error(); + expect(g.rx).toBeCloseTo(1, 9); + expect(g.ry).toBeCloseTo(0.5, 9); + }); + + it("TEXT: die Schrifthöhe zieht mit", () => { + const g = run({ shape: "text", at: { x: 0, y: 0 }, text: "A", height: 0.2, angle: 0 }, [ + { pt: { x: 0, y: 0 } }, + { num: 2 }, + ]); + if (g.shape !== "text") throw new Error(); + expect(g.height).toBeCloseTo(0.4, 9); + }); + + it("BEMASSUNG: der Masslinien-Abstand zieht mit, die Punkte ebenfalls", () => { + const g = run( + { shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], offset: 1 }, + [{ pt: { x: 0, y: 0 } }, { num: 2 }], + ); + if (g.shape !== "dimension") throw new Error(); + expect(g.offset).toBeCloseTo(2, 9); + expect(g.pts[1].x).toBeCloseTo(4, 9); + }); + + it("POLYLINIE mit Bogen: `bulge` bleibt unverändert (Formverhältnis, skaleninvariant)", () => { + const g = run( + { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [0.5] }, + [{ pt: { x: 0, y: 0 } }, { num: 3 }], + ); + if (g.shape !== "polyline") throw new Error(); + expect(g.bulge?.[0]).toBeCloseTo(0.5, 12); + expect(g.pts[1].x).toBeCloseTo(6, 9); + }); + + it("Faktor 0 oder negativ wird ignoriert (keine sinnvolle Skalierung)", () => { + const before: Drawing2DGeom = { shape: "circle", center: { x: 1, y: 0 }, r: 1 }; + expect(run(before, [{ pt: { x: 0, y: 0 } }, { num: 0 }])).toEqual(before); + expect(run(before, [{ pt: { x: 0, y: 0 } }, { num: -2 }])).toEqual(before); + }); +}); + +describe("scale — Referenzlänge", () => { + it("Faktor ergibt sich aus neue Länge ÷ Referenzlänge", () => { + // Referenz 2 Einheiten, Ziel 6 ⇒ Faktor 3. + const g = run({ shape: "circle", center: { x: 1, y: 0 }, r: 1 }, [ + { pt: { x: 0, y: 0 } }, + { pt: { x: 2, y: 0 } }, + { pt: { x: 6, y: 0 } }, + ]); + if (g.shape !== "circle") throw new Error(); + expect(g.r).toBeCloseTo(3, 9); + expect(g.center.x).toBeCloseTo(3, 9); + }); + + it("nur die LÄNGE zählt, nicht die Richtung der Referenz", () => { + const a = run({ shape: "circle", center: { x: 0, y: 0 }, r: 1 }, [ + { pt: { x: 0, y: 0 } }, + { pt: { x: 2, y: 0 } }, + { pt: { x: 0, y: 4 } }, + ]); + if (a.shape !== "circle") throw new Error(); + expect(a.r).toBeCloseTo(2, 9); + }); + + it("ohne Auswahl passiert nichts", () => { + const before: Drawing2DGeom = { shape: "circle", center: { x: 1, y: 0 }, r: 1 }; + expect(run(before, [{ pt: { x: 0, y: 0 } }, { num: 5 }], { wallIds: [], drawingId: null })).toEqual( + before, + ); + }); +}); diff --git a/src/commands/cmds/scale.ts b/src/commands/cmds/scale.ts new file mode 100644 index 0000000..44d6be4 --- /dev/null +++ b/src/commands/cmds/scale.ts @@ -0,0 +1,165 @@ +// Scale — skaliert die AKTUELLE Auswahl gleichmässig um einen frei gewählten +// Basispunkt. Schritte (AutoCAD-SCALE-Muster inkl. Referenz-Variante): +// 1) „Basispunkt:" → Punkt (bleibt fix) +// 2) „Faktor:" → ZAHL ⇒ sofort skalieren und fertig +// ODER Punkt ⇒ Referenzlänge, weiter mit 3) +// 3) „Neue Länge:" → Punkt (Live-Vorschau) → commit +// +// Die Referenz-Variante ist der Grund, warum es den Befehl braucht: „diese +// Kante soll so lang werden wie jene" lässt sich ohne Rechnen abgreifen. +// +// WICHTIG — was mitskaliert: 2D-Geometrie inklusive Radien, Schrifthöhen und +// Bemassungs-Abstand (s. `tools/transform.ts::scaleGeom`). Bei Wänden/Stützen +// skalieren nur LAGE und Achslänge; die Dicke bzw. das Profil steckt im +// jeweiligen Typ (geteilte Ressource) und bliebe sonst für ALLE Elemente +// desselben Typs verändert — bewusste Grenze, s. PENDENZEN.md. + +import { + commitTransform, + hasTransformSelection, + toTransformSel, + transformPreview, +} from "../../tools/transform"; +import type { + Command, + CommandResult, + CommandSelection, + CommandState, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); + +/** + * Punkte-Tripel für `transformFn("scale", …)`: Basispunkt, Referenzpunkt, + * Zielpunkt. Für einen GETIPPTEN Faktor werden Referenz (1 Einheit rechts) und + * Ziel (f Einheiten rechts) synthetisch erzeugt. + */ +function scalePts(base: Vec2, factor: number): Vec2[] { + return [base, { x: base.x + 1, y: base.y }, { x: base.x + factor, y: base.y }]; +} + +interface ScBase extends CommandState { + phase: "base"; +} +interface ScFactor extends CommandState { + phase: "factor"; + sel: CommandSelection; + base: Vec2; +} +interface ScTarget extends CommandState { + phase: "target"; + sel: CommandSelection; + base: Vec2; + ref: Vec2; + cursor: Vec2 | null; +} +interface ScDone extends CommandState { + phase: "done"; +} +type ScState = ScBase | ScFactor | ScTarget | ScDone; + +function scDraft(project: Project, sel: CommandSelection, pts: Vec2[], f: number): ToolDraft { + const preview = transformPreview(project, toTransformSel(sel), "scale", pts, "move", 1); + const base = pts[0]; + return { + preview: [...preview, { kind: "line", a: base, b: pts[2] }], + vertices: [base], + hud: { at: pts[2], text: `×${f.toFixed(3)}` }, + }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "done", lastPoint: null } as ScDone, + { draft: null, done: true }, +]; + +export const scaleCommand: Command = { + name: "scale", + labelKey: "cmd.scale.label", + prompt: (s) => { + const ss = s as ScState; + if (ss.phase === "factor") return "cmd.scale.factor"; + if (ss.phase === "target") return "cmd.scale.target"; + if (ss.phase === "done") return "cmd.scale.empty"; + return "cmd.scale.base"; + }, + accepts: (s) => ((s as ScState).phase === "factor" ? ["point", "number"] : ["point"]), + options: () => [], + + init: (): ScBase => ({ phase: "base", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as ScState; + if (s.phase === "done") return idle(); + if (!hasTransformSelection(ctx.selection)) { + return [{ phase: "done", lastPoint: null } as ScDone, { draft: null, done: true }]; + } + + // Getippter Faktor: sofort skalieren. 0/negativ ist keine sinnvolle + // Skalierung (Objekt verschwände bzw. klappte um) — ignoriert. + if (input.kind === "number" && s.phase === "factor") { + if (input.value <= EPS) return [s, { draft: null }]; + const { base, sel } = s; + const pts = scalePts(base, input.value); + return [ + { phase: "done", lastPoint: null } as ScDone, + { + draft: null, + done: true, + commit: (p) => commitTransform(p, toTransformSel(sel), "scale", pts, "move", 1), + }, + ]; + } + + if (input.kind !== "point") return [s, { draft: null }]; + const pt = input.point; + + if (s.phase === "base") { + const next: ScFactor = { phase: "factor", sel: ctx.selection, base: pt, lastPoint: pt }; + return [next, { draft: null }]; + } + + if (s.phase === "factor") { + // Referenzlänge; ohne Länge (Klick auf den Basispunkt) ignorieren. + if (segLen(s.base, pt) < EPS) return [s, { draft: null }]; + const next: ScTarget = { + phase: "target", + sel: s.sel, + base: s.base, + ref: pt, + cursor: pt, + lastPoint: pt, + }; + return [next, { draft: scDraft(ctx.project, s.sel, [s.base, pt, pt], 1) }]; + } + + // Neue Länge → commit. + if (segLen(s.base, pt) < EPS) return [s, { draft: null }]; + const { base, ref, sel } = s; + return [ + { phase: "done", lastPoint: null } as ScDone, + { + draft: null, + done: true, + commit: (p) => commitTransform(p, toTransformSel(sel), "scale", [base, ref, pt], "move", 1), + }, + ]; + }, + + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { + const s = state as ScState; + if (s.phase !== "target") return [s, { draft: null }]; + const ns: ScTarget = { ...s, cursor: point }; + const refLen = segLen(s.base, s.ref); + if (refLen < EPS) return [ns, { draft: null }]; + const f = segLen(s.base, point) / refLen; + return [ns, { draft: scDraft(ctx.project, s.sel, [s.base, s.ref, point], f) }]; + }, + + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/scalebar.test.ts b/src/commands/cmds/scalebar.test.ts new file mode 100644 index 0000000..f4598d6 --- /dev/null +++ b/src/commands/cmds/scalebar.test.ts @@ -0,0 +1,115 @@ +/** + * `scalebarCommand` — ein Klick → `shape:"scalebar"` mit den aktuellen + * Segmentlänge-/Anzahl-Optionen (persistieren über Aufrufe hinweg, wie + * `lastSides` bei `polygon.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { scalebarCommand } from "./scalebar"; +import type { CommandContext, CommandState, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +/** Treibt die „length"-Option auf den Ziel-Wert (Modul-Singleton, s. Polygon-Tests). */ +function setLength(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + let opts = scalebarCommand.options(s); + while (opts.find((o) => o.id === "length")?.value !== `${target}m`) { + [s] = scalebarCommand.onInput(s, { kind: "option", id: "length" }, ctx); + opts = scalebarCommand.options(s); + } + return s; +} + +/** Treibt die „segments"-Option auf den Ziel-Wert. */ +function setSegments(state: CommandState, ctx: CommandContext, target: number): CommandState { + let s = state; + let opts = scalebarCommand.options(s); + while (opts.find((o) => o.id === "segments")?.value !== String(target)) { + [s] = scalebarCommand.onInput(s, { kind: "option", id: "segments" }, ctx); + opts = scalebarCommand.options(s); + } + return s; +} + +describe("scalebarCommand", () => { + it("ein Klick committet shape:'scalebar' mit den aktuellen Optionen", () => { + const p = project(); + const ctx = makeCtx(p); + let state = setLength(scalebarCommand.init(), ctx, 2); + state = setSegments(state, ctx, 4); + const [, result] = scalebarCommand.onInput(state, { kind: "point", point: { x: 1, y: 2 } }, ctx); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("scalebar"); + if (g.shape === "scalebar") { + expect(g.at).toEqual({ x: 1, y: 2 }); + expect(g.segmentLength).toBe(2); + expect(g.segments).toBe(4); + } + }); + + it("Segmentlänge zyklt durch die Presets und wrapt zurück", () => { + const ctx = makeCtx(project()); + let state = setLength(scalebarCommand.init(), ctx, 0.5); + expect(scalebarCommand.options(state).find((o) => o.id === "length")?.value).toBe("0.5m"); + state = setLength(state, ctx, 50); + expect(scalebarCommand.options(state).find((o) => o.id === "length")?.value).toBe("50m"); + state = setLength(state, ctx, 0.5); // wrapt weiter zurück zum Anfang + expect(scalebarCommand.options(state).find((o) => o.id === "length")?.value).toBe("0.5m"); + }); + + it("Segmentanzahl zyklt zwischen 2 und 8", () => { + const ctx = makeCtx(project()); + let state = setSegments(scalebarCommand.init(), ctx, 2); + expect(scalebarCommand.options(state).find((o) => o.id === "segments")?.value).toBe("2"); + state = setSegments(state, ctx, 8); + expect(scalebarCommand.options(state).find((o) => o.id === "segments")?.value).toBe("8"); + }); + + it("onConfirm/onCancel kehren in den Ruhezustand zurück (kein Commit)", () => { + const ctx = makeCtx(project()); + const [, res1] = scalebarCommand.onConfirm(scalebarCommand.init(), ctx); + expect(res1.commit).toBeUndefined(); + expect(res1.done).toBe(true); + const [, res2] = scalebarCommand.onCancel(scalebarCommand.init()); + expect(res2.commit).toBeUndefined(); + expect(res2.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/scalebar.ts b/src/commands/cmds/scalebar.ts new file mode 100644 index 0000000..3790ea3 --- /dev/null +++ b/src/commands/cmds/scalebar.ts @@ -0,0 +1,105 @@ +// Massstabsbalken (Nutzer-Wunsch: „kein Massstabsbalken existiert"). Schritte: +// 1) „Punkt (linke untere Ecke):" → Punkt → commit mit den aktuellen +// Segmentlänge-/Anzahl-Optionen (persistieren über Aufrufe hinweg, wie +// `lastSides` bei `polygon.ts`). +// Segmentlänge + Anzahl per Option (zyklisch, tippbar als „l"/„n"). + +import type { Drawing2D } from "../../model/types"; +import { uniqueId } from "../../tools/types"; +import type { + CmdOption, + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50]; +let lastLength = 1; +const nextLength = (): number => LENGTH_PRESETS[(LENGTH_PRESETS.indexOf(lastLength) + 1) % LENGTH_PRESETS.length]; + +const MIN_SEGMENTS = 2; +const MAX_SEGMENTS = 8; +let lastSegments = 5; + +const LENGTH_OPTION: CmdOption = { id: "length", labelKey: "cmd.scalebar.length" }; +const SEGMENTS_OPTION: CmdOption = { id: "segments", labelKey: "cmd.scalebar.segments" }; + +interface ScalebarIdle extends CommandState { + phase: "point"; +} +type ScalebarState = ScalebarIdle; + +/** Vorschau: abwechselnd gefüllte/leere Rechtecke, wie das Rendering (grob, ohne Beschriftung). */ +function pointDraft(at: Vec2): ToolDraft { + const h = lastLength * 0.06; // rein optische Balkenhöhe für die Vorschau + const preview: DraftShape[] = []; + for (let i = 0; i < lastSegments; i++) { + const x0 = at.x + i * lastLength; + const x1 = x0 + lastLength; + preview.push({ + kind: "poly", + pts: [ + { x: x0, y: at.y }, + { x: x1, y: at.y }, + { x: x1, y: at.y + h }, + { x: x0, y: at.y + h }, + ], + closed: true, + }); + } + return { + preview, + vertices: [at], + hud: { at, text: `${lastLength}m × ${lastSegments} = ${(lastLength * lastSegments).toFixed(1)}m` }, + }; +} + +function appendScalebar(p: Project, at: Vec2, ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments }, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "point", lastPoint: null } as ScalebarIdle, + { draft: null, done: true }, +]; + +export const scalebarCommand: Command = { + name: "scalebar", + labelKey: "cmd.scalebar.label", + prompt: () => "cmd.scalebar.point", + accepts: () => ["point", "option"], + options: () => [ + { ...LENGTH_OPTION, value: `${lastLength}m` }, + { ...SEGMENTS_OPTION, value: String(lastSegments) }, + ], + init: (): ScalebarIdle => ({ phase: "point", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as ScalebarState; + if (input.kind === "option") { + if (input.id === "length") lastLength = nextLength(); + else if (input.id === "segments") { + lastSegments = lastSegments >= MAX_SEGMENTS ? MIN_SEGMENTS : lastSegments + 1; + } + return [s, { draft: null }]; + } + if (input.kind !== "point") return [s, { draft: null }]; + return [idle()[0], { draft: null, done: true, commit: (p) => appendScalebar(p, input.point, ctx) }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onConfirm: (): [CommandState, CommandResult] => idle(), + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/cmds/spline.test.ts b/src/commands/cmds/spline.test.ts index 85a4881..e0702fb 100644 --- a/src/commands/cmds/spline.test.ts +++ b/src/commands/cmds/spline.test.ts @@ -59,6 +59,7 @@ describe("splineCommand", () => { if (g.shape === "spline") { expect(g.closed).toBe(false); expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 3 }, { x: 5, y: 1 }]); + expect(g.mode).toBe("fit"); // Default, unverändert. } }); @@ -75,3 +76,50 @@ describe("splineCommand", () => { if (g.shape === "spline") expect(g.closed).toBe(true); }); }); + +describe("splineCommand — Kurven-Modus (fit/control)", () => { + it("Default-Option-Wert ist 'fit'", () => { + const state = splineCommand.init(); + const opt = splineCommand.options(state).find((o) => o.id === "curveMode"); + expect(opt?.value).toBe("fit"); + }); + + it("Option 'curveMode' zyklt fit → cv → fit", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = splineCommand.onInput(splineCommand.init(), { kind: "option", id: "curveMode" }, ctx); + expect(splineCommand.options(state).find((o) => o.id === "curveMode")?.value).toBe("cv"); + [state] = splineCommand.onInput(state, { kind: "option", id: "curveMode" }, ctx); + expect(splineCommand.options(state).find((o) => o.id === "curveMode")?.value).toBe("fit"); + }); + + it("Modus 'control' committet geom.mode:'control'", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = splineCommand.onInput(splineCommand.init(), { kind: "option", id: "curveMode" }, ctx); // → cv + [state] = splineCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = splineCommand.onInput(state, { kind: "point", point: { x: 2, y: 5 } }, ctx); + [state] = splineCommand.onInput(state, { kind: "point", point: { x: 6, y: 5 } }, ctx); + const [, result] = splineCommand.onConfirm(state, ctx); + const g = result.commit!(p).drawings2d[0].geom; + if (g.shape === "spline") { + expect(g.mode).toBe("control"); + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 5 }, { x: 6, y: 5 }]); + } + }); + + it("Umschalten des Kurven-Modus verwirft die laufende Konstruktion NICHT (bleibt in Phase 'next', Punkte erhalten)", () => { + const p = project(); + const ctx = makeCtx(p); + let [state] = splineCommand.onInput(splineCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = splineCommand.onInput(state, { kind: "point", point: { x: 2, y: 3 } }, ctx); + [state] = splineCommand.onInput(state, { kind: "option", id: "curveMode" }, ctx); // → cv, mitten im Zug + expect(splineCommand.prompt(state)).toBe("cmd.spline.next"); + const [, result] = splineCommand.onConfirm(state, ctx); + const g = result.commit!(p).drawings2d[0].geom; + if (g.shape === "spline") { + expect(g.mode).toBe("control"); + expect(g.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 3 }]); + } + }); +}); diff --git a/src/commands/cmds/spline.ts b/src/commands/cmds/spline.ts index 8940856..d002f0c 100644 --- a/src/commands/cmds/spline.ts +++ b/src/commands/cmds/spline.ts @@ -1,13 +1,23 @@ -// Spline — glatte Kurve DURCH mehrere Wegpunkte (uniformer Catmull-Rom), -// Bedienung 1:1 wie `polyline` (s. dort), nur dass die Vorschau/das Ergebnis -// zwischen den Punkten rundet statt gerade Kanten zu ziehen. Schritte: +// Spline — glatte Kurve über mehreren Wegpunkten, Bedienung 1:1 wie +// `polyline` (s. dort), nur dass die Vorschau/das Ergebnis zwischen den +// Punkten rundet statt gerade Kanten zu ziehen. Schritte: // 1) „Startpunkt:" → Punkt // 2) „Nächster Punkt ( Schliessen Zurück ):" → Punkt … (Enter beendet offen, // „Schliessen" schließt; Klick auf den Startpunkt schließt ebenfalls) +// +// Zwei Kurven-Modi (Option „Modus", tippbar/klickbar, zyklisch fit↔control +// — analog zum Methode-Zyklus bei `circle.ts`/`arc.ts`, hier nur 2 Werte): +// • „fit" (Default, unverändert): die Kurve verläuft DURCH die Wegpunkte +// (uniformer Catmull-Rom). +// • „control" (Kontrollpunkt-/CV-Modus): die Wegpunkte sind Kontrollpunkte +// eines kubischen B-Splines — die Kurve wird nur von ihnen GEZOGEN, +// berührt sie i. A. NICHT (nur Start/Ende bei offener Kurve, geklemmt). +// Kein Gewicht pro Kontrollpunkt (NURBS) — bewusst auf den unbewichteten +// Fall beschränkt, s. PENDENZEN.md. import type { Drawing2D } from "../../model/types"; import { segmentHud, uniqueId } from "../../tools/types"; -import { sampleCatmullRom } from "../../tools/curves"; +import { sampleCatmullRom, sampleUniformBSpline } from "../../tools/curves"; import type { Command, CommandContext, @@ -24,15 +34,19 @@ const EPS = 1e-6; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +type CurveMode = "fit" | "control"; + interface SplineIdle extends CommandState { phase: "start"; closed: boolean; + curveMode: CurveMode; } interface SplineDrawing extends CommandState { phase: "next"; points: Vec2[]; cursor: Vec2 | null; closed: boolean; + curveMode: CurveMode; } type SplineState = SplineIdle | SplineDrawing; @@ -43,12 +57,22 @@ const closedOption = (closed: boolean): CmdOption => ({ labelKey: "cmd.polyline.closedOpt", value: closed ? "on" : "off", }); +const curveModeOption = (mode: CurveMode): CmdOption => ({ + id: "curveMode", + labelKey: "cmd.spline.curveMode", + value: mode === "control" ? "cv" : "fit", +}); + +/** Kurvenpunkte je nach Modus (fit = interpolierend, control = B-Spline-Kontrollnetz). */ +function sampleCurve(pts: Vec2[], closed: boolean, mode: CurveMode): Vec2[] { + return mode === "control" ? sampleUniformBSpline(pts, closed) : sampleCatmullRom(pts, closed); +} /** Vorschau (geglätteter Zug + Gummiband zum Cursor) + HUD. */ -function splineDraft(points: Vec2[], cursor: Vec2 | null, closed = false): ToolDraft { +function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: CurveMode): ToolDraft { const pts = cursor ? [...points, cursor] : points; const showClosed = closed && pts.length >= 3; - const curve = sampleCatmullRom(pts, showClosed); + const curve = sampleCurve(pts, showClosed, mode); const preview: DraftShape[] = [{ kind: "poly", pts: curve, closed: showClosed }]; const draft: ToolDraft = { preview, vertices: points }; const last = points[points.length - 1]; @@ -56,19 +80,19 @@ function splineDraft(points: Vec2[], cursor: Vec2 | null, closed = false): ToolD return draft; } -function appendSpline(p: Project, pts: Vec2[], closed: boolean, ctx: CommandContext): Project { +function appendSpline(p: Project, pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): Project { const d: Drawing2D = { id: uniqueId("dr2d"), type: "drawing2d", levelId: ctx.level.id, categoryCode: ctx.defaultCategoryCode, - geom: { shape: "spline", pts, closed }, + geom: { shape: "spline", pts, closed, mode }, }; return { ...p, drawings2d: [...p.drawings2d, d] }; } -const idle = (closed = false): [CommandState, CommandResult] => [ - { phase: "start", lastPoint: null, closed } as SplineIdle, +const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null, closed, curveMode } as SplineIdle, { draft: null, done: true }, ]; @@ -79,11 +103,11 @@ export const splineCommand: Command = { accepts: () => ["point", "option"], options: (s) => { const ps = s as SplineState; - const toggle = closedOption(ps.closed); - if (ps.phase !== "next") return [toggle]; - return ps.points.length >= 2 ? [CLOSE, toggle, UNDO] : [toggle, UNDO]; + const toggles = [closedOption(ps.closed), curveModeOption(ps.curveMode)]; + if (ps.phase !== "next") return toggles; + return ps.points.length >= 2 ? [CLOSE, ...toggles, UNDO] : [...toggles, UNDO]; }, - init: (): SplineIdle => ({ phase: "start", lastPoint: null, closed: false }), + init: (): SplineIdle => ({ phase: "start", lastPoint: null, closed: false, curveMode: "fit" }), onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as SplineState; @@ -91,57 +115,79 @@ export const splineCommand: Command = { if (input.kind === "option") { if (input.id === "mode") { const ns = { ...s, closed: !s.closed } as SplineState; - return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, ns.closed) : null }]; + return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, ns.closed, s.curveMode) : null }]; + } + if (input.id === "curveMode") { + const ns = { ...s, curveMode: s.curveMode === "control" ? "fit" : "control" } as SplineState; + return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, ns.curveMode) : null }]; } if (s.phase !== "next") return [s, { draft: null }]; if (input.id === "undo") { const pts = s.points.slice(0, -1); if (pts.length === 0) - return [{ phase: "start", lastPoint: null, closed: s.closed } as SplineIdle, { draft: null }]; + return [ + { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, + { draft: null }, + ]; const ns: SplineDrawing = { phase: "next", points: pts, cursor: s.cursor, lastPoint: pts[pts.length - 1], closed: s.closed, + curveMode: s.curveMode, }; - return [ns, { draft: splineDraft(pts, s.cursor, s.closed) }]; + return [ns, { draft: splineDraft(pts, s.cursor, s.closed, s.curveMode) }]; } if (input.id === "close" && s.points.length >= 3) { const pts = s.points; return [ - { phase: "start", lastPoint: null, closed: s.closed } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, + { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, ]; } - return [s, { draft: splineDraft(s.points, s.cursor, s.closed) }]; + return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed) : null }]; + return [s, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, s.curveMode) : null }]; } const pt = input.point; if (s.phase !== "next") { - const ns: SplineDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt, closed: s.closed }; - return [ns, { draft: splineDraft([pt], pt, s.closed) }]; + const ns: SplineDrawing = { + phase: "next", + points: [pt], + cursor: pt, + lastPoint: pt, + closed: s.closed, + curveMode: s.curveMode, + }; + return [ns, { draft: splineDraft([pt], pt, s.closed, s.curveMode) }]; } if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; return [ - { phase: "start", lastPoint: null, closed: s.closed } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, + { draft: null, done: true, commit: (p) => appendSpline(p, pts, true, s.curveMode, ctx) }, ]; } const points = [...s.points, pt]; - const ns: SplineDrawing = { phase: "next", points, cursor: pt, lastPoint: pt, closed: s.closed }; - return [ns, { draft: splineDraft(points, pt, s.closed) }]; + const ns: SplineDrawing = { + phase: "next", + points, + cursor: pt, + lastPoint: pt, + closed: s.closed, + curveMode: s.curveMode, + }; + return [ns, { draft: splineDraft(points, pt, s.closed, s.curveMode) }]; }, onMove: (state, point): [CommandState, CommandResult] => { const s = state as SplineState; if (s.phase !== "next") return [s, { draft: null }]; const ns: SplineDrawing = { ...s, cursor: point }; - return [ns, { draft: splineDraft(s.points, point, s.closed) }]; + return [ns, { draft: splineDraft(s.points, point, s.closed, s.curveMode) }]; }, onConfirm: (state, ctx): [CommandState, CommandResult] => { @@ -150,11 +196,11 @@ export const splineCommand: Command = { const pts = s.points; const close = s.closed && pts.length >= 3; return [ - { phase: "start", lastPoint: null, closed: s.closed } as SplineIdle, - { draft: null, done: true, commit: (p) => appendSpline(p, pts, close, ctx) }, + { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, + { draft: null, done: true, commit: (p) => appendSpline(p, pts, close, s.curveMode, ctx) }, ]; } - return idle(s.closed); + return idle(s.closed, s.curveMode); }, - onCancel: (state): [CommandState, CommandResult] => idle((state as SplineState).closed), + onCancel: (state): [CommandState, CommandResult] => idle((state as SplineState).closed, (state as SplineState).curveMode), }; diff --git a/src/commands/cmds/trim.ts b/src/commands/cmds/trim.ts index c790860..622beb5 100644 --- a/src/commands/cmds/trim.ts +++ b/src/commands/cmds/trim.ts @@ -36,19 +36,23 @@ import type { Vec2, } from "../types"; -const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl +export const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl // ── Kurven-Abstraktion: line/polyline/rect → Punktliste + closed ────────────── -interface Curve { +export interface Curve { pts: Vec2[]; closed: boolean; /** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei polyline. */ bulge?: number[]; } -/** Wandelt eine trim-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder null. */ -function geomToCurve(g: Drawing2DGeom): Curve | null { +/** + * Wandelt eine trim-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder + * null. Exportiert — `break.ts` (BREAK-Befehl) nutzt dieselbe Kurven- + * Abstraktion + Hit-Test wie trim/extend, statt sie zu duplizieren. + */ +export function geomToCurve(g: Drawing2DGeom): Curve | null { if (g.shape === "line") return { pts: [g.a, g.b], closed: false }; if (g.shape === "polyline") return { pts: g.pts, closed: g.closed, bulge: g.bulge }; if (g.shape === "rect") { @@ -65,8 +69,8 @@ function geomToCurve(g: Drawing2DGeom): Curve | null { return null; // circle/arc/text: hier nicht trim-fähig } -/** Ist diese Form trim-fähig (line/polyline/rect)? */ -function isTrimmable(d: Drawing2D): boolean { +/** Ist diese Form trim-fähig (line/polyline/rect)? Exportiert, s. `geomToCurve`. */ +export function isTrimmable(d: Drawing2D): boolean { const g = d.geom; return g.shape === "line" || g.shape === "polyline" || g.shape === "rect"; } @@ -77,7 +81,7 @@ function isTrimmable(d: Drawing2D): boolean { * (runden) Kontur funktioniert statt entlang der geraden Sehne — s. gleiches * Vorgehen in offset.ts (`curveHitEdges`). */ -function curveHitEdges(curve: Curve): [Vec2, Vec2][] { +export function curveHitEdges(curve: Curve): [Vec2, Vec2][] { if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed); const n = curve.pts.length; const edgeCount = curve.closed ? n : n - 1; @@ -90,13 +94,14 @@ function curveHitEdges(curve: Curve): [Vec2, Vec2][] { } /** Nächstes trim-fähiges Drawing2D der Ebene zum Klickpunkt (innerhalb Toleranz). */ -function pickCurveAt( +export function pickCurveAt( project: Project, levelId: string, pt: Vec2, + tol = HIT_TOL, ): Drawing2D | null { let best: Drawing2D | null = null; - let bestD = HIT_TOL; + let bestD = tol; for (const d of project.drawings2d) { if (d.levelId !== levelId) continue; if (!isTrimmable(d)) continue; @@ -142,8 +147,8 @@ function sameChain(a: { pts: Vec2[]; closed: boolean }, b: Curve): boolean { return true; } -/** Eine getrimmte Rest-Kette als passende Drawing2D-Geometrie. */ -function chainToGeom(chain: { pts: Vec2[]; closed: boolean; bulge?: number[] }): Drawing2DGeom { +/** Eine getrimmte Rest-Kette als passende Drawing2D-Geometrie. Exportiert, s. `geomToCurve`. */ +export function chainToGeom(chain: { pts: Vec2[]; closed: boolean; bulge?: number[] }): Drawing2DGeom { if (chain.pts.length === 2 && !chain.closed && !hasRealBulge(chain.bulge)) { return { shape: "line", a: chain.pts[0], b: chain.pts[1] }; } diff --git a/src/commands/cmds/wipeout.test.ts b/src/commands/cmds/wipeout.test.ts new file mode 100644 index 0000000..31b831d --- /dev/null +++ b/src/commands/cmds/wipeout.test.ts @@ -0,0 +1,106 @@ +/** + * `wipeoutCommand` — Punktfolge (wie `polyline`) → geschlossene weisse + * `polyline` (Maskenregion). Anders als `revcloud`/`polyline` gibt es KEINEN + * offenen Endzustand: sowohl Klick-nahe-Start als auch Enter schliessen. + */ + +import { describe, it, expect } from "vitest"; +import { wipeoutCommand } from "./wipeout"; +import type { CommandContext, Project } from "../types"; + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +describe("wipeoutCommand", () => { + it("Klick nahe Startpunkt (≥3 Punkte) schliesst und committet weiss gefüllt", () => { + const p = project(); + const ctx = makeCtx(p); + let state = wipeoutCommand.init(); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 4, y: 4 } }, ctx); + const [, result] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 0.05, y: 0.02 } }, ctx); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const d = next.drawings2d[0]; + expect(d.geom.shape).toBe("polyline"); + if (d.geom.shape === "polyline") { + expect(d.geom.closed).toBe(true); + expect(d.geom.pts).toEqual([ + { x: 0, y: 0 }, + { x: 4, y: 0 }, + { x: 4, y: 4 }, + ]); + } + expect(d.background).toBe("#ffffff"); + expect(d.color).toBe("#ffffff"); + }); + + it("Enter (≥3 Punkte) schliesst AUTOMATISCH statt offen zu bleiben", () => { + const p = project(); + const ctx = makeCtx(p); + let state = wipeoutCommand.init(); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 4, y: 4 } }, ctx); + const [, result] = wipeoutCommand.onConfirm(state, ctx); + expect(result.done).toBe(true); + expect(result.commit).toBeDefined(); + const next = result.commit!(p); + expect(next.drawings2d.length).toBe(1); + const g = next.drawings2d[0].geom; + expect(g.shape).toBe("polyline"); + if (g.shape === "polyline") expect(g.closed).toBe(true); + }); + + it("Enter mit nur 2 Punkten committet NICHTS (kein sinnvoller offener Endzustand)", () => { + const p = project(); + const ctx = makeCtx(p); + let state = wipeoutCommand.init(); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 0, y: 0 } }, ctx); + [state] = wipeoutCommand.onInput(state, { kind: "point", point: { x: 4, y: 0 } }, ctx); + const [, result] = wipeoutCommand.onConfirm(state, ctx); + expect(result.commit).toBeUndefined(); + expect(result.done).toBe(true); + }); + + it("onCancel kehrt in den Ruhezustand zurück (kein Commit)", () => { + const [, res] = wipeoutCommand.onCancel(wipeoutCommand.init()); + expect(res.commit).toBeUndefined(); + expect(res.done).toBe(true); + }); +}); diff --git a/src/commands/cmds/wipeout.ts b/src/commands/cmds/wipeout.ts new file mode 100644 index 0000000..d6d0d73 --- /dev/null +++ b/src/commands/cmds/wipeout.ts @@ -0,0 +1,128 @@ +// Wipeout/Maskenregion (Nutzer-Wunsch: „Wipeout/Maskenregion" aus der +// Werkzeug-Lücken-Liste). Schritte (wie `revcloud.ts`, aber ohne dessen +// Beulen-Logik — eine Maskenfläche ist eine ganz normale gerade Kontur): +// 1) „Startpunkt:" → Punkt +// 2) „Nächster Punkt:" → Punkt … Klick nahe dem Startpunkt ODER Enter +// (≥3 Punkte) schliesst und committet. +// +// ANDERS als bei jedem anderen Mehrpunkt-Werkzeug MUSS ein Wipeout immer +// GESCHLOSSEN sein (eine offene „Maske" hätte kein Innen/Aussen) — Enter +// schliesst hier daher automatisch, statt (wie bei `revcloud`) offen zu +// beenden. +// +// Bewusst KEIN neuer Shape-Typ: das Ergebnis ist eine ganz normale +// `Drawing2DGeom["polyline"]` (geschlossen, keine Bögen) mit weisser +// Füll- UND Strichfarbe (`background`/`color`, beide bereits vorhandene +// Attribut-Override-Felder) — sie deckt darunterliegende Zeichnung ab, weil +// neue Elemente an das ENDE von `project.drawings2d` angehängt werden und +// damit automatisch oben im Zeichen-Stapel liegen (dieselbe Reihenfolge, die +// „Nach vorne holen"/„Nach hinten legen" im Kontextmenü nutzt) — keine +// eigene Z-Order-Logik nötig. Farbe/Deckkraft bleiben über das +// Attribute-Panel wie bei jeder anderen Fläche nachträglich änderbar (kein +// Sonderfall, nur ein sinnvoller Default). + +import type { Drawing2D } from "../../model/types"; +import { segmentHud, uniqueId } from "../../tools/types"; +import type { + Command, + CommandContext, + CommandResult, + CommandState, + DraftShape, + Project, + ToolDraft, + Vec2, +} from "../types"; + +const EPS = 1e-6; +const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug +const MASK_COLOR = "#ffffff"; // Deckt wie Papier ab — Fläche UND Rand (unsichtbare Kontur) + +const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); + +interface WipeoutIdle extends CommandState { + phase: "start"; +} +interface WipeoutDrawing extends CommandState { + phase: "next"; + points: Vec2[]; + cursor: Vec2 | null; +} +type WipeoutState = WipeoutIdle | WipeoutDrawing; + +function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { + const pts = cursor ? [...points, cursor] : points; + const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }]; + const draft: ToolDraft = { preview, vertices: points }; + const last = points[points.length - 1]; + if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); + return draft; +} + +function appendWipeout(p: Project, points: Vec2[], ctx: CommandContext): Project { + const d: Drawing2D = { + id: uniqueId("dr2d"), + type: "drawing2d", + levelId: ctx.level.id, + categoryCode: ctx.defaultCategoryCode, + geom: { shape: "polyline", pts: points, closed: true }, + background: MASK_COLOR, + color: MASK_COLOR, + }; + return { ...p, drawings2d: [...p.drawings2d, d] }; +} + +const idle = (): [CommandState, CommandResult] => [ + { phase: "start", lastPoint: null } as WipeoutIdle, + { draft: null, done: true }, +]; + +export const wipeoutCommand: Command = { + name: "wipeout", + labelKey: "cmd.wipeout.label", + prompt: (s) => ((s as WipeoutState).phase === "next" ? "cmd.wipeout.next" : "cmd.wipeout.start"), + accepts: () => ["point"], + options: () => [], + init: (): WipeoutIdle => ({ phase: "start", lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as WipeoutState; + if (input.kind !== "point") { + return [s, { draft: s.phase === "next" ? wipeoutDraft(s.points, s.cursor) : null }]; + } + const pt = input.point; + + if (s.phase !== "next") { + const ns: WipeoutDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt }; + return [ns, { draft: wipeoutDraft([pt], pt) }]; + } + + // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet). + if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { + const pts = s.points; + return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + } + const points = [...s.points, pt]; + const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; + return [ns, { draft: wipeoutDraft(points, pt) }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = state as WipeoutState; + if (s.phase !== "next") return [s, { draft: null }]; + const ns: WipeoutDrawing = { ...s, cursor: point }; + return [ns, { draft: wipeoutDraft(s.points, point) }]; + }, + + // Enter/Space/Rechtsklick: schliesst AUTOMATISCH (≥3 Punkte) — anders als + // bei `revcloud`/`polyline` gibt es keinen sinnvollen offenen Endzustand. + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as WipeoutState; + if (s.phase === "next" && s.points.length >= 3) { + const pts = s.points; + return [idle()[0], { draft: null, done: true, commit: (p) => appendWipeout(p, pts, ctx) }]; + } + return idle(); + }, + onCancel: (): [CommandState, CommandResult] => idle(), +}; diff --git a/src/commands/engine.ts b/src/commands/engine.ts index 0aa97b9..e96e420 100644 --- a/src/commands/engine.ts +++ b/src/commands/engine.ts @@ -100,11 +100,18 @@ export class CommandEngine { /** Identität des Schritts, für den der Feld-Zustand gilt (Reset bei Wechsel). */ private fieldPhaseKey: string | null = null; private listeners = new Set<() => void>(); + /** Nutzer-Kürzel-Übersteuerungen (s. `state/commandAliasOverrides.ts`); leer bis gesetzt. */ + private aliasOverrides: Record = {}; constructor(host: EngineHost) { this.host = host; } + /** Setzt die aktuellen Nutzer-Kürzel-Übersteuerungen (Remap-UI). */ + setAliasOverrides(overrides: Record): void { + this.aliasOverrides = overrides; + } + // ── Abo / Snapshot ───────────────────────────────────────────────────────── subscribe(fn: () => void): () => void { @@ -258,7 +265,7 @@ export class CommandEngine { /** Startet einen Befehl per Name/Alias/Präfix. Liefert true bei Erfolg. */ start(nameOrPrefix: string): boolean { - const cmd = resolveCommand(nameOrPrefix) ?? getCommand(nameOrPrefix); + const cmd = resolveCommand(nameOrPrefix, this.aliasOverrides) ?? getCommand(nameOrPrefix); if (!cmd) return false; return this.startCommand(cmd); } diff --git a/src/commands/registry.test.ts b/src/commands/registry.test.ts new file mode 100644 index 0000000..adb9c55 --- /dev/null +++ b/src/commands/registry.test.ts @@ -0,0 +1,65 @@ +/** + * `resolveCommand`/`allCommandNames` — insbesondere die NEUE `customAliases`- + * Übersteuerung (Nutzer-Wunsch: „Befehls-Kürzel sind hart codiert, keine + * Remap-UI"). Reihenfolge: exakter Befehlsname > Nutzer-Kürzel > eingebautes + * Kürzel > eindeutiges Präfix. + */ + +import { describe, it, expect } from "vitest"; +import { resolveCommand, allCommandNames, COMMANDS } from "./registry"; + +describe("resolveCommand — ohne customAliases (unverändertes Verhalten)", () => { + it("exakter Befehlsname", () => { + expect(resolveCommand("line")?.name).toBe("line"); + }); + + it("eingebautes Kürzel", () => { + expect(resolveCommand("l")?.name).toBe("line"); + }); + + it("unbekannt → null", () => { + expect(resolveCommand("qqqq")).toBeNull(); + }); +}); + +describe("resolveCommand — customAliases", () => { + it("löst ein NEUES Nutzer-Kürzel auf, das kein eingebautes Kürzel ist", () => { + expect(resolveCommand("zz", { zz: "circle" })?.name).toBe("circle"); + }); + + it("überschreibt ein eingebautes Kürzel mit demselben Schlüssel", () => { + // "l" ist eingebaut für "line" — ein Nutzer-Kürzel soll es übersteuern können. + expect(resolveCommand("l")?.name).toBe("line"); + expect(resolveCommand("l", { l: "leader" })?.name).toBe("leader"); + }); + + it("kann NIE einen exakten Befehlsnamen überschreiben", () => { + // "wall" ist selbst ein exakter Befehlsname — ein Kürzel-Override mit + // demselben Schlüssel darf ihn nicht kapern. + expect(resolveCommand("wall", { wall: "circle" })?.name).toBe("wall"); + }); + + it("ein Kürzel auf einen unbekannten Befehlsnamen liefert null (kein Absturz)", () => { + expect(resolveCommand("zz", { zz: "does-not-exist" })).toBeNull(); + }); + + it("case-insensitiv wie die eingebauten Kürzel", () => { + expect(resolveCommand("ZZ", { zz: "circle" })?.name).toBe("circle"); + }); +}); + +describe("allCommandNames", () => { + it("liefert alle registrierten Befehle, alphabetisch, ohne Duplikate", () => { + const names = allCommandNames(); + expect(names.length).toBe(Object.keys(COMMANDS).length); + expect(names).toEqual([...names].sort()); + expect(new Set(names).size).toBe(names.length); + }); + + it("enthält bekannte Befehle (Stichprobe)", () => { + const names = allCommandNames(); + expect(names).toContain("line"); + expect(names).toContain("break"); + expect(names).toContain("detailref"); + }); +}); diff --git a/src/commands/registry.ts b/src/commands/registry.ts index d90d110..5eada83 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -7,6 +7,7 @@ import type { Command } from "./types"; import { lineCommand } from "./cmds/line"; import { polylineCommand } from "./cmds/polyline"; import { xlineCommand } from "./cmds/xline"; +import { rayCommand } from "./cmds/ray"; import { wallCommand } from "./cmds/wall"; import { ceilingCommand } from "./cmds/ceiling"; import { openingCommand, fensterCommand, tuerCommand } from "./cmds/opening"; @@ -24,18 +25,28 @@ import { splineCommand } from "./cmds/spline"; import { bezierCommand } from "./cmds/bezier"; import { dimensionCommand } from "./cmds/dimension"; import { koteCommand } from "./cmds/kote"; +import { detailrefCommand } from "./cmds/detailref"; +import { scalebarCommand } from "./cmds/scalebar"; +import { revcloudCommand } from "./cmds/revcloud"; +import { pointmarkerCommand } from "./cmds/pointmarker"; +import { wipeoutCommand } from "./cmds/wipeout"; import { textCommand } from "./cmds/text"; import { leaderCommand } from "./cmds/leader"; import { textpathCommand } from "./cmds/textpath"; import { textboxCommand } from "./cmds/textbox"; import { moveCommand } from "./cmds/move"; import { mirrorCommand } from "./cmds/mirror"; +import { rotateCommand } from "./cmds/rotate"; +import { scaleCommand } from "./cmds/scale"; +import { explodeCommand } from "./cmds/explode"; +import { alignCommand } from "./cmds/align"; import { joinCommand } from "./cmds/join"; import { copyCommand } from "./cmds/copy"; import { arrayCommand } from "./cmds/array"; import { offsetCommand } from "./cmds/offset"; import { extrudeCommand } from "./cmds/extrude"; import { trimCommand } from "./cmds/trim"; +import { breakCommand } from "./cmds/break"; import { extendCommand } from "./cmds/extend"; import { filletCommand } from "./cmds/fillet"; import { chamferCommand } from "./cmds/chamfer"; @@ -63,6 +74,7 @@ export const COMMANDS: Record = { line: lineCommand, polyline: polylineCommand, xline: xlineCommand, + ray: rayCommand, rect: rectCommand, circle: circleCommand, arc: arcCommand, @@ -72,18 +84,28 @@ export const COMMANDS: Record = { bezier: bezierCommand, dimension: dimensionCommand, kote: koteCommand, + detailref: detailrefCommand, + scalebar: scalebarCommand, + revcloud: revcloudCommand, + pointmarker: pointmarkerCommand, + wipeout: wipeoutCommand, text: textCommand, leader: leaderCommand, textpath: textpathCommand, textbox: textboxCommand, move: moveCommand, mirror: mirrorCommand, + rotate: rotateCommand, + scale: scaleCommand, + explode: explodeCommand, + align: alignCommand, join: joinCommand, copy: copyCommand, array: arrayCommand, offset: offsetCommand, extrude: extrudeCommand, trim: trimCommand, + break: breakCommand, extend: extendCommand, fillet: filletCommand, chamfer: chamferCommand, @@ -127,6 +149,8 @@ export const ALIASES: Record = { xl: "xline", hilfslinie: "xline", konstruktionslinie: "xline", + ry: "ray", + strahl: "ray", bl: "block", symbol: "block", db: "defblock", @@ -143,6 +167,21 @@ export const ALIASES: Record = { bemassung: "dimension", kt: "kote", hoehenkote: "kote", + dr: "detailref", + detail: "detailref", + verweis: "detailref", + sb: "scalebar", + massstabsbalken: "scalebar", + massstab: "scalebar", + rv: "revcloud", + wolke: "revcloud", + revisionswolke: "revcloud", + pm: "pointmarker", + punkt: "pointmarker", + knoten: "pointmarker", + wo: "wipeout", + maske: "wipeout", + maskierung: "wipeout", bz: "bezier", tx: "text", txt: "text", @@ -154,6 +193,14 @@ export const ALIASES: Record = { m: "move", s: "mirror", spiegeln: "mirror", + ro: "rotate", + drehen: "rotate", + sc: "scale", + skalieren: "scale", + x: "explode", + aufloesen: "explode", + al: "align", + ausrichten: "align", j: "join", verbinden: "join", cp: "copy", @@ -162,6 +209,8 @@ export const ALIASES: Record = { o: "offset", ex: "extrude", tr: "trim", + br: "break", + unterbrechen: "break", ext: "extend", verlaengern: "extend", verlängern: "extend", @@ -185,13 +234,20 @@ export function getCommand(name: string): Command | undefined { } /** - * Löst eine getippte Eingabe zu einem Befehl auf: erst exakter Name, dann Alias, - * dann eindeutiges Präfix (case-insensitiv). Mehrdeutige/leere Präfixe → null. + * Löst eine getippte Eingabe zu einem Befehl auf: erst exakter Name, dann + * NUTZER-Kürzel (`customAliases`, s. `state/commandAliasOverrides.ts` — + * Nutzer-Wunsch „Befehls-Kürzel sind hart codiert, keine Remap-UI"), dann das + * eingebaute Kürzel, dann eindeutiges Präfix (case-insensitiv). Mehrdeutige/ + * leere Präfixe → null. Ein Nutzer-Kürzel kann ein EINGEBAUTES Kürzel + * überschreiben (gleicher Schlüssel, anderes Ziel), aber NIE einen exakten + * Befehlsnamen (der gewinnt immer zuerst — sonst würde getipptes „wall" + * plötzlich etwas anderes tun). */ -export function resolveCommand(raw: string): Command | null { +export function resolveCommand(raw: string, customAliases?: Record): Command | null { const q = raw.trim().toLowerCase(); if (q === "") return null; if (COMMANDS[q]) return COMMANDS[q]; + if (customAliases?.[q]) return COMMANDS[customAliases[q]] ?? null; if (ALIASES[q]) return COMMANDS[ALIASES[q]] ?? null; const matches = autocomplete(q); if (matches.length === 1) return COMMANDS[matches[0]] ?? null; @@ -199,6 +255,11 @@ export function resolveCommand(raw: string): Command | null { return null; } +/** Alle bekannten Befehlsnamen, alphabetisch — für die Kürzel-Remap-UI. */ +export function allCommandNames(): string[] { + return Object.keys(COMMANDS).sort(); +} + /** * Präfix-Autocomplete: alle Befehlsnamen, die mit dem (lowercase) Präfix * beginnen, alphabetisch. Aliase werden NICHT mitgelistet (sie sind Kürzel, diff --git a/src/commands/types.ts b/src/commands/types.ts index 52772a2..d125be0 100644 --- a/src/commands/types.ts +++ b/src/commands/types.ts @@ -71,6 +71,14 @@ export interface CommandSelection { extrudedSolidId?: string | null; /** Gewählte Stütze (Tragwerk), falls eine selektiert ist. */ columnId?: string | null; + /** Gewählte Decken (Mehrfachauswahl). */ + ceilingIds?: string[]; + /** Gewählte Dächer (Mehrfachauswahl); s. `TransformSelection.roofIds`. */ + roofIds?: string[]; + /** Gewählte Treppen (Mehrfachauswahl). */ + stairIds?: string[]; + /** Gewählte Räume (Mehrfachauswahl). */ + roomIds?: string[]; } /** Live-Kontext, den ein Befehl bei jedem Schritt erhält (analog ToolContext). */ diff --git a/src/editors/align.test.ts b/src/editors/align.test.ts new file mode 100644 index 0000000..45d932c --- /dev/null +++ b/src/editors/align.test.ts @@ -0,0 +1,119 @@ +/** Ausrichten und Verteilen der 2D-Auswahl. */ + +import { describe, expect, it } from "vitest"; +import { alignDrawings, distributeDrawings } from "./align"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project } from "../model/types"; + +/** Rechtecke als Testobjekte: bbox ist direkt ablesbar. */ +function rects(boxes: [string, number, number, number, number][]): Project { + const drawings2d: Drawing2D[] = boxes.map(([id, x0, y0, x1, y1]) => ({ + id, + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom: { shape: "rect", min: { x: x0, y: y0 }, max: { x: x1, y: y1 } }, + })); + return { ...sampleProject, drawings2d }; +} + +const box = (p: Project, id: string) => { + const g = p.drawings2d.find((d) => d.id === id)!.geom; + if (g.shape !== "rect") throw new Error(); + return g; +}; + +describe("alignDrawings", () => { + const P = rects([ + ["a", 0, 0, 2, 1], + ["b", 5, 3, 6, 5], + ["c", 10, 1, 14, 2], + ]); + + it("linksbündig: alle an den linkesten Rand der AUSWAHL", () => { + const out = alignDrawings(P, ["a", "b", "c"], "left"); + expect(box(out, "a").min.x).toBeCloseTo(0, 9); + expect(box(out, "b").min.x).toBeCloseTo(0, 9); + expect(box(out, "c").min.x).toBeCloseTo(0, 9); + // Nur verschoben, nicht verzerrt: Breiten unverändert. + expect(box(out, "c").max.x - box(out, "c").min.x).toBeCloseTo(4, 9); + }); + + it("rechtsbündig richtet an der rechten Kante aus", () => { + const out = alignDrawings(P, ["a", "b", "c"], "right"); + for (const id of ["a", "b", "c"]) expect(box(out, id).max.x).toBeCloseTo(14, 9); + }); + + it("zentriert (X) bringt alle Mitten auf die Mitte der Auswahl", () => { + const out = alignDrawings(P, ["a", "b", "c"], "centerX"); + const mid = (id: string) => (box(out, id).min.x + box(out, id).max.x) / 2; + expect(mid("a")).toBeCloseTo(7, 9); // Hülle 0..14 → Mitte 7 + expect(mid("b")).toBeCloseTo(7, 9); + expect(mid("c")).toBeCloseTo(7, 9); + }); + + it("oben/unten wirken auf Y und lassen X in Ruhe", () => { + const out = alignDrawings(P, ["a", "b", "c"], "top"); + for (const id of ["a", "b", "c"]) expect(box(out, id).max.y).toBeCloseTo(5, 9); + expect(box(out, "a").min.x).toBeCloseTo(0, 9); // X unverändert + }); + + it("unter zwei Elementen passiert nichts", () => { + expect(alignDrawings(P, ["a"], "left")).toBe(P); + expect(alignDrawings(P, [], "left")).toBe(P); + }); + + it("rührt nicht gewählte Elemente nicht an", () => { + const out = alignDrawings(P, ["a", "b"], "left"); + expect(box(out, "c").min.x).toBeCloseTo(10, 9); + }); +}); + +describe("distributeDrawings", () => { + it("verteilt die Mitten mit gleichen Abständen; die Äusseren bleiben stehen", () => { + const P = rects([ + ["a", 0, 0, 2, 1], // Mitte 1 + ["b", 3, 0, 4, 1], // Mitte 3.5 (wandert) + ["c", 8, 0, 10, 1], // Mitte 9 + ["d", 18, 0, 20, 1], // Mitte 19 + ]); + const out = distributeDrawings(P, ["a", "b", "c", "d"], "x"); + const mid = (id: string) => (box(out, id).min.x + box(out, id).max.x) / 2; + expect(mid("a")).toBeCloseTo(1, 9); + expect(mid("d")).toBeCloseTo(19, 9); + // Gleiche Schrittweite (19−1)/3 = 6. + expect(mid("b")).toBeCloseTo(7, 9); + expect(mid("c")).toBeCloseTo(13, 9); + }); + + it("nutzt die Reihenfolge auf der Achse, nicht die Auswahlreihenfolge", () => { + const P = rects([ + ["links", 0, 0, 1, 1], + ["rechts", 10, 0, 11, 1], + ["mitte", 8, 0, 9, 1], + ]); + const out = distributeDrawings(P, ["rechts", "links", "mitte"], "x"); + const mid = (id: string) => (box(out, id).min.x + box(out, id).max.x) / 2; + expect(mid("mitte")).toBeCloseTo(5.5, 9); // genau mittig zwischen 0.5 und 10.5 + }); + + it("verteilt entlang Y, ohne X zu verändern", () => { + const P = rects([ + ["a", 0, 0, 1, 1], + ["b", 5, 2, 6, 3], + ["c", 0, 10, 1, 11], + ]); + const out = distributeDrawings(P, ["a", "b", "c"], "y"); + const midY = (id: string) => (box(out, id).min.y + box(out, id).max.y) / 2; + expect(midY("b")).toBeCloseTo(5.5, 9); // zwischen 0.5 und 10.5 + expect(box(out, "b").min.x).toBeCloseTo(5, 9); // X unangetastet + }); + + it("unter drei Elementen gibt es nichts zu verteilen", () => { + const P = rects([ + ["a", 0, 0, 1, 1], + ["b", 5, 0, 6, 1], + ]); + expect(distributeDrawings(P, ["a", "b"], "x")).toBe(P); + }); +}); diff --git a/src/editors/align.ts b/src/editors/align.ts new file mode 100644 index 0000000..20ba1bd --- /dev/null +++ b/src/editors/align.ts @@ -0,0 +1,123 @@ +// Ausrichten und Verteilen der 2D-Auswahl — reine Modell-Funktionen (wie +// `editors/explode.ts`), damit sie ohne UI testbar bleiben. +// +// Beides arbeitet auf den BOUNDING-BOXEN der Elemente (dieselbe Herleitung wie +// im Attribut-Panel, s. `geomBBox`) und verschiebt sie anschliessend als +// Ganzes. Die Form selbst bleibt unangetastet — es wird nur verschoben, nie +// skaliert oder verzerrt. + +import type { Drawing2D, Project, Vec2 } from "../model/types"; +import { geomBBox } from "../state/selectionInfo"; +import { mvGeom } from "../tools/transform"; + +/** Ausrichtungskante bzw. -achse. */ +export type AlignMode = "left" | "right" | "centerX" | "top" | "bottom" | "centerY"; + +/** Verteilungsachse: gleiche Abstände der Mittelpunkte entlang X bzw. Y. */ +export type DistributeAxis = "x" | "y"; + +interface Boxed { + d: Drawing2D; + minX: number; + minY: number; + maxX: number; + maxY: number; +} + +function boxesOf(project: Project, ids: string[]): Boxed[] { + const wanted = new Set(ids); + return project.drawings2d + .filter((d) => wanted.has(d.id)) + .map((d) => ({ d, ...geomBBox(d.geom) })); +} + +/** Verschiebt die genannten Elemente um je einen eigenen Vektor. */ +function moveBy(project: Project, deltas: Map): Project { + if (deltas.size === 0) return project; + return { + ...project, + drawings2d: project.drawings2d.map((d) => { + const delta = deltas.get(d.id); + if (!delta || (delta.x === 0 && delta.y === 0)) return d; + const fn = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); + return { ...d, geom: mvGeom(d.geom, fn) }; + }), + }; +} + +/** + * Richtet die Elemente an der gemeinsamen Kante bzw. Mittelachse aus. Bezug + * ist die Hülle ALLER gewählten Elemente (wie in Grafikprogrammen üblich): + * „linksbündig" schiebt alle an den linkesten Rand der Auswahl. + * + * Weniger als zwei Elemente ergeben keine Ausrichtung (nichts, woran man sich + * ausrichten könnte) — das Projekt bleibt unverändert. + */ +export function alignDrawings(project: Project, ids: string[], mode: AlignMode): Project { + const boxes = boxesOf(project, ids); + if (boxes.length < 2) return project; + + const minX = Math.min(...boxes.map((b) => b.minX)); + const maxX = Math.max(...boxes.map((b) => b.maxX)); + const minY = Math.min(...boxes.map((b) => b.minY)); + const maxY = Math.max(...boxes.map((b) => b.maxY)); + const cx = (minX + maxX) / 2; + const cy = (minY + maxY) / 2; + + const deltas = new Map(); + for (const b of boxes) { + let dx = 0; + let dy = 0; + switch (mode) { + case "left": + dx = minX - b.minX; + break; + case "right": + dx = maxX - b.maxX; + break; + case "centerX": + dx = cx - (b.minX + b.maxX) / 2; + break; + case "top": + dy = maxY - b.maxY; + break; + case "bottom": + dy = minY - b.minY; + break; + case "centerY": + dy = cy - (b.minY + b.maxY) / 2; + break; + } + deltas.set(b.d.id, { x: dx, y: dy }); + } + return moveBy(project, deltas); +} + +/** + * Verteilt die Elemente mit GLEICHEN MITTENABSTÄNDEN entlang der Achse. Die + * beiden äussersten bleiben stehen und spannen den Bereich auf — alles + * dazwischen rückt auf gleichmässige Abstände. + * + * Unter drei Elementen gibt es nichts zu verteilen (die Äusseren bleiben ja + * ohnehin stehen) — das Projekt bleibt unverändert. + */ +export function distributeDrawings(project: Project, ids: string[], axis: DistributeAxis): Project { + const boxes = boxesOf(project, ids); + if (boxes.length < 3) return project; + + const center = (b: Boxed) => (axis === "x" ? (b.minX + b.maxX) / 2 : (b.minY + b.maxY) / 2); + const sorted = [...boxes].sort((a, b) => center(a) - center(b)); + const first = center(sorted[0]); + const last = center(sorted[sorted.length - 1]); + const step = (last - first) / (sorted.length - 1); + + const deltas = new Map(); + sorted.forEach((b, i) => { + // Erstes und letztes Element bleiben unangetastet (sie definieren den Bereich). + if (i === 0 || i === sorted.length - 1) return; + const target = first + step * i; + const shift = target - center(b); + deltas.set(b.d.id, axis === "x" ? { x: shift, y: 0 } : { x: 0, y: shift }); + }); + return moveBy(project, deltas); +} diff --git a/src/editors/elementClipboardSerialize.test.ts b/src/editors/elementClipboardSerialize.test.ts new file mode 100644 index 0000000..52e4ea5 --- /dev/null +++ b/src/editors/elementClipboardSerialize.test.ts @@ -0,0 +1,73 @@ +/** + * `elementClipboardSerialize` — OS-Zwischenablage-Text-Serialisierung für + * `ElementClipboard` (`serializeClipboardText`/`parseClipboardText`). Deckt + * den Roundtrip sowie die defensive Ablehnung fremder/kaputter Texte ab + * (Grundvoraussetzung dafür, dass ein `navigator.clipboard.readText()`- + * Ergebnis mit BELIEBIGEM Inhalt niemals `pasteElementClipboard` zum + * Absturz bringt). + */ +import { describe, it, expect } from "vitest"; +import { serializeClipboardText, parseClipboardText } from "./elementClipboardSerialize"; +import { EMPTY_CLIPBOARD } from "./elementClipboard"; +import type { ElementClipboard } from "./elementClipboard"; +import type { Wall } from "../model/types"; + +function wall(id: string): Wall { + return { + id, + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 5, y: 0 }, + wallTypeId: "wt1", + height: 2.6, + }; +} + +function sampleClip(): ElementClipboard { + return { ...EMPTY_CLIPBOARD, walls: [wall("w1")] }; +} + +describe("elementClipboardSerialize — Roundtrip", () => { + it("serialize → parse ergibt eine äquivalente ElementClipboard", () => { + const clip = sampleClip(); + expect(parseClipboardText(serializeClipboardText(clip))).toEqual(clip); + }); + + it("Roundtrip funktioniert auch für eine leere Zwischenablage", () => { + expect(parseClipboardText(serializeClipboardText(EMPTY_CLIPBOARD))).toEqual(EMPTY_CLIPBOARD); + }); +}); + +describe("elementClipboardSerialize — parseClipboardText lehnt Fremdtext defensiv ab", () => { + it("liefert null für kein JSON", () => { + expect(parseClipboardText("Hallo, das ist normaler Text")).toBeNull(); + }); + + it("liefert null für gültiges JSON ohne unsere Marke", () => { + expect(parseClipboardText(JSON.stringify({ foo: "bar" }))).toBeNull(); + }); + + it("liefert null für JSON mit falscher Marke", () => { + expect( + parseClipboardText(JSON.stringify({ __dossier: "irgendwas-anderes", clip: EMPTY_CLIPBOARD })), + ).toBeNull(); + }); + + it("liefert null, wenn 'clip' fehlt", () => { + expect(parseClipboardText(JSON.stringify({ __dossier: "dossier-element-clipboard-v1" }))).toBeNull(); + }); + + it("liefert null, wenn ein Bauteil-Feld kein Array ist (verformte Daten)", () => { + const broken = { __dossier: "dossier-element-clipboard-v1", clip: { ...EMPTY_CLIPBOARD, walls: "kaputt" } }; + expect(parseClipboardText(JSON.stringify(broken))).toBeNull(); + }); + + it("liefert null für leeren String / primitive Werte", () => { + expect(parseClipboardText("")).toBeNull(); + expect(parseClipboardText("42")).toBeNull(); + expect(parseClipboardText("null")).toBeNull(); + expect(parseClipboardText('"nur ein String"')).toBeNull(); + }); +}); diff --git a/src/editors/elementClipboardSerialize.ts b/src/editors/elementClipboardSerialize.ts new file mode 100644 index 0000000..6958c0c --- /dev/null +++ b/src/editors/elementClipboardSerialize.ts @@ -0,0 +1,65 @@ +// OS-Zwischenablage-Serialisierung für `ElementClipboard` (Nutzer-Wunsch: +// „Element-Zwischenablage ist In-App-only — kein Copy/Paste zwischen zwei +// Fenstern/Projekten derselben App", `ElementClipboard` lebte bisher NUR als +// React-State, ohne `navigator.clipboard`-Aufruf). Reine Funktionen: +// Serialisieren zu einem markierten JSON-Text (für `navigator.clipboard. +// writeText`) + defensives Parsen zurück (für `readText`) — jeder Fehlschlag +// (fremder Text, falsche Marke, kaputtes/unvollständiges JSON — z. B. wenn +// der Nutzer zuletzt normalen Text kopiert hat) liefert `null` statt zu +// werfen, damit der Aufrufer klaglos auf die In-App-Zwischenablage zurückfällt +// (s. `useKeyboardShortcuts.ts::useElementClipboardShortcut`). +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { ElementClipboard } from "./elementClipboard"; + +const MARKER = "dossier-element-clipboard-v1"; + +interface SerializedClipboard { + __dossier: typeof MARKER; + clip: ElementClipboard; +} + +/** ElementClipboard → JSON-Text für `navigator.clipboard.writeText`. */ +export function serializeClipboardText(clip: ElementClipboard): string { + const payload: SerializedClipboard = { __dossier: MARKER, clip }; + return JSON.stringify(payload); +} + +/** Die 9 Bauteil-Arten-Felder, die eine gültige `ElementClipboard`-Form ausmachen. */ +const CLIP_ARRAY_KEYS = [ + "walls", + "drawings", + "ceilings", + "roofs", + "openings", + "stairs", + "rooms", + "extrudedSolids", + "columns", +] as const; + +/** + * JSON-Text (z. B. aus `navigator.clipboard.readText()`) → `ElementClipboard`, + * oder `null` bei irgendeinem Fehlschlag: kein JSON, fremdes Format, falsche + * Marke, oder eines der 9 Bauteil-Felder fehlt/ist kein Array (kaputte/ + * unvollständige Daten — lieber ablehnen als `pasteElementClipboard` mit + * einer verformten Struktur zum Absturz zu bringen). + */ +export function parseClipboardText(text: string): ElementClipboard | null { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return null; + } + if (!parsed || typeof parsed !== "object") return null; + if ((parsed as Partial).__dossier !== MARKER) return null; + const clip = (parsed as SerializedClipboard).clip as unknown; + if (!clip || typeof clip !== "object") return null; + const clipRecord = clip as Record; + for (const key of CLIP_ARRAY_KEYS) { + if (!Array.isArray(clipRecord[key])) return null; + } + return clip as ElementClipboard; +} diff --git a/src/editors/explode.test.ts b/src/editors/explode.test.ts new file mode 100644 index 0000000..c5a9f16 --- /dev/null +++ b/src/editors/explode.test.ts @@ -0,0 +1,153 @@ +/** + * Auflösen (Explode). Kernpunkte: ein BOGEN-Segment einer Polylinie darf beim + * Zerlegen nicht zur Sehne zusammenfallen, Stil-Eigenschaften bleiben erhalten, + * und nicht zerlegbare Formen verschwinden nicht. + */ + +import { describe, expect, it } from "vitest"; +import { explodeDrawings, explodeGeom } from "./explode"; +import { sampleProject } from "../model/sampleProject"; +import { bulgeArc } from "../geometry/bulge"; +import type { Drawing2D, Drawing2DGeom, Project } from "../model/types"; + +function withDrawing(geom: Drawing2DGeom, extra: Partial = {}): Project { + return { + ...sampleProject, + drawings2d: [ + { + id: "d1", + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom, + ...extra, + }, + ], + }; +} + +describe("explodeGeom — Polylinie", () => { + it("offene Polylinie → eine Linie je Segment", () => { + const parts = explodeGeom( + { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 3 }], closed: false }, + sampleProject, + ); + expect(parts).toHaveLength(2); + expect(parts!.every((g) => g.shape === "line")).toBe(true); + }); + + it("geschlossene Polylinie hat ein Segment MEHR (der Schluss zurück zum Start)", () => { + const parts = explodeGeom( + { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 3 }], closed: true }, + sampleProject, + ); + expect(parts).toHaveLength(3); + }); + + it("Bogen-Segment wird zu einem ECHTEN Bogen, nicht zur Sehne", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + const orig = bulgeArc(a, b, 0.6)!; + const parts = explodeGeom( + { shape: "polyline", pts: [a, b], closed: false, bulge: [0.6] }, + sampleProject, + )!; + expect(parts).toHaveLength(1); + const g = parts[0]; + expect(g.shape).toBe("arc"); + if (g.shape !== "arc") throw new Error(); + // Derselbe Kreis wie das Bogen-Segment vorher. + expect(g.center.x).toBeCloseTo(orig.center.x, 9); + expect(g.center.y).toBeCloseTo(orig.center.y, 9); + expect(g.r).toBeCloseTo(orig.r, 9); + // Die Endpunkte des Bogens sind weiterhin a und b. + const at = (ang: number) => ({ x: g.center.x + g.r * Math.cos(ang), y: g.center.y + g.r * Math.sin(ang) }); + const ends = [at(g.a0), at(g.a1)]; + const near = (p: { x: number; y: number }, q: { x: number; y: number }) => + Math.hypot(p.x - q.x, p.y - q.y) < 1e-9; + expect(ends.some((p) => near(p, a))).toBe(true); + expect(ends.some((p) => near(p, b))).toBe(true); + }); +}); + +describe("explodeGeom — Rechteck und Block", () => { + it("Rechteck → vier Linien, die den Umriss schliessen", () => { + const parts = explodeGeom( + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + sampleProject, + )!; + expect(parts).toHaveLength(4); + // Ende jeder Linie ist Anfang der nächsten (geschlossener Ring). + for (let i = 0; i < 4; i++) { + const cur = parts[i]; + const nxt = parts[(i + 1) % 4]; + if (cur.shape !== "line" || nxt.shape !== "line") throw new Error(); + expect(cur.b).toEqual(nxt.a); + } + }); + + it("Block → Teilgeometrien mit Drehung und Einfügepunkt verrechnet", () => { + const project: Project = { + ...sampleProject, + blockDefs: [ + { id: "b1", name: "Test", geom2d: [{ shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }] }, + ], + }; + // 90° gedreht, um (5,5) eingefügt: (1,0) → (5,6). + const parts = explodeGeom( + { shape: "block", blockDefId: "b1", at: { x: 5, y: 5 }, rotation: Math.PI / 2 }, + project, + )!; + expect(parts).toHaveLength(1); + const g = parts[0]; + if (g.shape !== "line") throw new Error(); + expect(g.a.x).toBeCloseTo(5, 9); + expect(g.a.y).toBeCloseTo(5, 9); + expect(g.b.x).toBeCloseTo(5, 9); + expect(g.b.y).toBeCloseTo(6, 9); + }); + + it("unbekannte Block-Definition wird nicht zerlegt (nichts geht verloren)", () => { + expect( + explodeGeom({ shape: "block", blockDefId: "weg", at: { x: 0, y: 0 }, rotation: 0 }, sampleProject), + ).toBeNull(); + }); +}); + +describe("explodeGeom — was NICHT zerlegt wird", () => { + it.each(["circle", "ellipse", "spline", "text"] as const)("%s bleibt unverändert", (shape) => { + const geoms: Record = { + circle: { shape: "circle", center: { x: 0, y: 0 }, r: 1 }, + ellipse: { shape: "ellipse", center: { x: 0, y: 0 }, rx: 2, ry: 1, rotation: 0 }, + spline: { shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }], closed: false }, + text: { shape: "text", at: { x: 0, y: 0 }, text: "A", height: 0.2, angle: 0 }, + }; + expect(explodeGeom(geoms[shape], sampleProject)).toBeNull(); + }); +}); + +describe("explodeDrawings", () => { + it("ersetzt das Original durch seine Teile und behält die Stil-Eigenschaften", () => { + const p = withDrawing( + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + { color: "#ff0000", weightMm: 0.7, dashScale: 2 }, + ); + const out = explodeDrawings(p, ["d1"]); + expect(out.drawings2d).toHaveLength(4); + expect(out.drawings2d.every((d) => d.color === "#ff0000" && d.weightMm === 0.7)).toBe(true); + expect(out.drawings2d.every((d) => d.dashScale === 2)).toBe(true); + // Neue Identitäten, keine doppelten IDs. + expect(new Set(out.drawings2d.map((d) => d.id)).size).toBe(4); + expect(out.drawings2d.some((d) => d.id === "d1")).toBe(false); + }); + + it("lässt nicht zerlegbare Elemente unangetastet (kein stiller Verlust)", () => { + const p = withDrawing({ shape: "circle", center: { x: 0, y: 0 }, r: 1 }); + expect(explodeDrawings(p, ["d1"])).toBe(p); + }); + + it("rührt nicht gewählte Elemente nicht an", () => { + const p = withDrawing({ shape: "rect", min: { x: 0, y: 0 }, max: { x: 1, y: 1 } }); + expect(explodeDrawings(p, ["andere"])).toBe(p); + }); +}); diff --git a/src/editors/explode.ts b/src/editors/explode.ts new file mode 100644 index 0000000..4744e8d --- /dev/null +++ b/src/editors/explode.ts @@ -0,0 +1,148 @@ +// Auflösen (Explode) — zerlegt zusammengesetzte 2D-Elemente in ihre Einzelteile. +// Reine Modell-Funktion, damit sie ohne Befehl/UI testbar bleibt (wie +// `editors/splitJoin.ts`). +// +// Was zerlegt wird: +// • Block-Instanz → die Teilgeometrien der Definition, mit Drehung und +// Einfügepunkt der Instanz verrechnet (dieselbe Transformation, mit der +// `generatePlan/drawing2d.ts` sie zeichnet). +// • Polylinie → ein Element je Segment: Gerade zu `line`, ein Bogen-Segment +// (`bulge`) zu einem ECHTEN `arc` — der Bogen darf beim Auflösen nicht zur +// Sehne zusammenfallen. +// • Rechteck → vier Linien. +// +// Bewusst NICHT zerlegt (kein sinnvolles „Einzelteil", das die Form erhielte): +// Kreis, Ellipse, Spline, Bezier, Text, Bemassung, Bild — sie bleiben +// unverändert stehen. Ebenso alles, was kein 2D-Element ist. + +import type { Drawing2D, Drawing2DGeom, Project, Vec2 } from "../model/types"; +import { bulgeArc } from "../geometry/bulge"; +import { uniqueId } from "../tools/types"; + +/** Teilgeometrien EINES Elements, oder `null`, wenn es nicht zerlegbar ist. */ +export function explodeGeom(geom: Drawing2DGeom, project: Project): Drawing2DGeom[] | null { + switch (geom.shape) { + case "block": { + const def = project.blockDefs?.find((b) => b.id === geom.blockDefId); + if (!def || def.geom2d.length === 0) return null; + const c = Math.cos(geom.rotation); + const s = Math.sin(geom.rotation); + const xf = (p: Vec2): Vec2 => ({ + x: geom.at.x + p.x * c - p.y * s, + y: geom.at.y + p.x * s + p.y * c, + }); + return def.geom2d.map((sub) => mapPoints(sub, xf)); + } + + case "polyline": { + const n = geom.pts.length; + if (n < 2) return null; + const segCount = geom.closed && n > 2 ? n : n - 1; + const out: Drawing2DGeom[] = []; + for (let i = 0; i < segCount; i++) { + const a = geom.pts[i]; + const b = geom.pts[(i + 1) % n]; + const arc = bulgeArc(a, b, geom.bulge?.[i] ?? 0); + if (arc) { + // Echter Bogen statt Sehne: Start-/Endwinkel aus dem Kreis, in der + // Reihenfolge, die der Schwenkrichtung entspricht (a0 → a1 läuft in + // der `arc`-Form immer gegen den Uhrzeigersinn). + const forward = arc.sweep >= 0; + out.push({ + shape: "arc", + center: arc.center, + r: arc.r, + a0: forward ? arc.a0 : arc.a1, + a1: forward ? arc.a1 : arc.a0, + }); + } else { + out.push({ shape: "line", a, b }); + } + } + return out; + } + + case "rect": { + const { min, max } = geom; + const c1 = min; + const c2 = { x: max.x, y: min.y }; + const c3 = max; + const c4 = { x: min.x, y: max.y }; + return [ + { shape: "line", a: c1, b: c2 }, + { shape: "line", a: c2, b: c3 }, + { shape: "line", a: c3, b: c4 }, + { shape: "line", a: c4, b: c1 }, + ]; + } + + default: + return null; + } +} + +/** Punkte einer Geometrie durch `fn` schicken (nur für die Block-Teilgeometrie nötig). */ +function mapPoints(geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom { + switch (geom.shape) { + case "line": + case "xline": + case "ray": + return { ...geom, a: fn(geom.a), b: fn(geom.b) }; + case "polyline": + return { ...geom, pts: geom.pts.map(fn) }; + case "rect": + case "image": + return { ...geom, min: fn(geom.min), max: fn(geom.max) }; + case "circle": + case "arc": + case "ellipse": + return { ...geom, center: fn(geom.center) }; + case "bezier": + case "spline": + case "dimension": + return { ...geom, pts: geom.pts.map(fn) }; + case "text": + case "kote": + case "detailref": + case "scalebar": + case "pointmarker": + return { ...geom, at: fn(geom.at) }; + case "block": + return { ...geom, at: fn(geom.at) }; + default: + return geom; + } +} + +/** + * Löst die angegebenen 2D-Elemente auf: jedes zerlegbare Element wird durch + * seine Einzelteile ERSETZT (gleiche Ebene/Kategorie und alle Stil- + * Übersteuerungen bleiben erhalten), nicht zerlegbare bleiben unangetastet. + * Die Reihenfolge im Array bleibt stabil — die Teile stehen an der Stelle des + * Originals, damit sich die Zeichenreihenfolge (z-Anordnung) nicht ändert. + */ +export function explodeDrawings(project: Project, ids: string[]): Project { + const wanted = new Set(ids); + let changed = false; + const next: Drawing2D[] = []; + for (const d of project.drawings2d) { + if (!wanted.has(d.id)) { + next.push(d); + continue; + } + const parts = explodeGeom(d.geom, project); + if (!parts || parts.length === 0) { + next.push(d); + continue; + } + changed = true; + for (const geom of parts) { + // Stil-Eigenschaften der Quelle übernehmen; nur Identität und Geometrie + // sind neu. `hatchId`/Füllung bleiben bewusst dran: löst man ein + // gefülltes Rechteck auf, tragen die Linien sie zwar wirkungslos mit, + // aber es geht nichts verloren, falls der Nutzer sie wieder schliesst. + next.push({ ...d, id: uniqueId("dr2d"), geom }); + } + } + return changed ? { ...project, drawings2d: next } : project; +} diff --git a/src/editors/matchProps.test.ts b/src/editors/matchProps.test.ts new file mode 100644 index 0000000..ae813f9 --- /dev/null +++ b/src/editors/matchProps.test.ts @@ -0,0 +1,86 @@ +/** „Eigenschaften übertragen" für 2D-Elemente. */ + +import { describe, expect, it } from "vitest"; +import { applyDrawingStyle, readDrawingStyle } from "./matchProps"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Project } from "../model/types"; + +function proj(...ds: Partial[]): Project { + return { + ...sampleProject, + drawings2d: ds.map((d, i) => ({ + id: `d${i}`, + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + ...d, + })) as Drawing2D[], + }; +} +const at = (p: Project, i: number) => p.drawings2d[i]; + +describe("readDrawingStyle", () => { + it("liest nur gesetzte Stil-Felder", () => { + const p = proj({ color: "#ff0000", weightMm: 0.5 }); + expect(readDrawingStyle(at(p, 0))).toEqual({ color: "#ff0000", weightMm: 0.5 }); + }); + + it("nimmt Identität, Form und EBENE bewusst NICHT mit", () => { + const p = proj({ color: "#00ff00" }); + const style = readDrawingStyle(at(p, 0)) as Record; + for (const k of ["id", "type", "geom", "levelId", "categoryCode"]) { + expect(style[k]).toBeUndefined(); + } + }); +}); + +describe("applyDrawingStyle", () => { + it("überträgt das Aussehen auf die Ziele", () => { + const p = proj({ color: "#ff0000", weightMm: 0.7, dashScale: 2 }, {}, {}); + const out = applyDrawingStyle(p, ["d1", "d2"], readDrawingStyle(at(p, 0))); + for (const i of [1, 2]) { + expect(at(out, i).color).toBe("#ff0000"); + expect(at(out, i).weightMm).toBe(0.7); + expect(at(out, i).dashScale).toBe(2); + } + }); + + it("Form, Ebene und Identität des Ziels bleiben unangetastet", () => { + const p = proj( + { color: "#ff0000" }, + { geom: { shape: "circle", center: { x: 5, y: 5 }, r: 3 }, categoryCode: "99" }, + ); + const out = applyDrawingStyle(p, ["d1"], readDrawingStyle(at(p, 0))); + expect(at(out, 1).id).toBe("d1"); + expect(at(out, 1).geom).toEqual({ shape: "circle", center: { x: 5, y: 5 }, r: 3 }); + expect(at(out, 1).categoryCode).toBe("99"); + }); + + it("ENTFERNT am Ziel, was die Quelle nicht hat — sonst sähe es anders aus als das Vorbild", () => { + const p = proj({ color: "#ff0000" }, { color: "#0000ff", hatchId: "solid", opacity: 0.4 }); + const out = applyDrawingStyle(p, ["d1"], readDrawingStyle(at(p, 0))); + expect(at(out, 1).color).toBe("#ff0000"); + expect(at(out, 1).hatchId).toBeUndefined(); + expect(at(out, 1).opacity).toBeUndefined(); + }); + + it("überträgt auch die By-Layer/By-Object-Quellen (sonst löste sich das Aussehen anders auf)", () => { + const p = proj({ foregroundSource: "layer", hatchSource: "layer" }, {}); + const out = applyDrawingStyle(p, ["d1"], readDrawingStyle(at(p, 0))); + expect(at(out, 1).foregroundSource).toBe("layer"); + expect(at(out, 1).hatchSource).toBe("layer"); + }); + + it("der Schraffur-URSPRUNG wird nicht mitgenommen (Ortsbezug, kein Aussehen)", () => { + const p = proj({ hatchId: "h", hatchOrigin: { x: 9, y: 9 } }, {}); + const out = applyDrawingStyle(p, ["d1"], readDrawingStyle(at(p, 0))); + expect(at(out, 1).hatchId).toBe("h"); + expect(at(out, 1).hatchOrigin).toBeUndefined(); + }); + + it("leere Zielliste lässt das Projekt unverändert", () => { + const p = proj({ color: "#ff0000" }); + expect(applyDrawingStyle(p, [], readDrawingStyle(at(p, 0)))).toBe(p); + }); +}); diff --git a/src/editors/matchProps.ts b/src/editors/matchProps.ts new file mode 100644 index 0000000..d5419a4 --- /dev/null +++ b/src/editors/matchProps.ts @@ -0,0 +1,102 @@ +// „Eigenschaften übertragen" für 2D-Elemente (Match Properties) — reine +// Modell-Funktionen, damit sie ohne UI testbar bleiben. +// +// Übertragen wird ausschliesslich das AUSSEHEN, nie Identität, Lage oder Form: +// Farbe/Stift, Strichstärke, Linienstil und dessen Massstab, Füllung +// (Schraffur samt Platzierung, Vorder-/Hintergrund, Vollton), Transparenz, +// Linienenden — plus die By-Layer/By-Object-Quellen, weil ein kopiertes +// Aussehen sonst je nach Quelle anders aufgelöst würde. +// +// NICHT übertragen: `id`, `type`, `geom` (Form), `levelId` (Zeichnungsebene) +// und `categoryCode` (Ebene) — die Ebene ist Organisation, nicht Aussehen; wer +// sie mitnehmen wollte, verschöbe das Element ungewollt in eine andere Ebene. + +import type { Drawing2D, Project } from "../model/types"; + +/** Die übertragbaren Stil-Felder eines 2D-Elements. */ +export type DrawingStyle = Pick< + Drawing2D, + | "lineStyleId" + | "hatchId" + | "foreground" + | "background" + | "foregroundPenId" + | "backgroundPenId" + | "color" + | "colorPenId" + | "dashScale" + | "hatchAngleDeg" + | "hatchScale" + | "opacity" + | "endMarks" + | "fillColor" + | "weightMm" + | "foregroundSource" + | "backgroundSource" + | "strokeWeightSource" + | "hatchSource" +>; + +/** + * Feldnamen des Stils. Bewusst als Liste statt „alles ausser X": kommt ein + * neues Stil-Feld dazu, fällt beim Ergänzen hier auf, dass es auch übertragen + * werden sollte — bei einer Negativliste würde es still mitkopiert, auch wenn + * es gar kein Stil ist. + */ +const STYLE_KEYS = [ + "lineStyleId", + "hatchId", + "foreground", + "background", + "foregroundPenId", + "backgroundPenId", + "color", + "colorPenId", + "dashScale", + "hatchAngleDeg", + "hatchScale", + "opacity", + "endMarks", + "fillColor", + "weightMm", + "foregroundSource", + "backgroundSource", + "strokeWeightSource", + "hatchSource", +] as const satisfies readonly (keyof DrawingStyle)[]; + +/** Liest den Stil eines Elements heraus (nur gesetzte Felder). */ +export function readDrawingStyle(d: Drawing2D): DrawingStyle { + const style: Record = {}; + for (const k of STYLE_KEYS) { + if (d[k] !== undefined) style[k] = d[k]; + } + return style as DrawingStyle; +} + +/** + * Überträgt einen Stil auf die genannten Elemente. Felder, die die Quelle NICHT + * gesetzt hatte, werden am Ziel ENTFERNT — sonst bliebe z. B. eine alte + * Schraffur stehen, obwohl die Quelle keine hat, und das Ergebnis sähe anders + * aus als das Vorbild. + * + * Der Schraffur-URSPRUNG wird bewusst nicht mitgenommen: er ist ein + * Ortsbezug (ein Ankerpunkt im Modell), kein Aussehen — am Ziel läge das + * Muster sonst an einer sinnlosen Stelle. + */ +export function applyDrawingStyle(project: Project, ids: string[], style: DrawingStyle): Project { + const wanted = new Set(ids); + if (wanted.size === 0) return project; + return { + ...project, + drawings2d: project.drawings2d.map((d) => { + if (!wanted.has(d.id)) return d; + const next: Record = { ...d }; + for (const k of STYLE_KEYS) { + if (style[k] === undefined) delete next[k]; + else next[k] = style[k]; + } + return next as unknown as Drawing2D; + }), + }; +} diff --git a/src/export/exportDxf.arcs.test.ts b/src/export/exportDxf.arcs.test.ts new file mode 100644 index 0000000..91be46a --- /dev/null +++ b/src/export/exportDxf.arcs.test.ts @@ -0,0 +1,88 @@ +/** + * DXF-Export gezeichneter Kreise/Bögen. Beide Primitive (`drawingCircle`/ + * `drawingArc`) landeten früher gar nicht im DXF — der Writer konnte CIRCLE + * und ARC längst, im Primitiv-Switch fehlten nur die Zweige. Seit Polylinien- + * Bögen als echte Bögen in den Plan gehen (statt tesselliert), hängt daran + * auch, ob ein Bogen in AutoCAD/Vectorworks als BOGEN ankommt oder als Kette + * von Geraden. + */ + +import { describe, expect, it } from "vitest"; +import { buildPlanDxf } from "./exportDxf"; +import { sampleProject } from "../model/sampleProject"; +import type { Plan } from "../plan/generatePlan"; + +/** Minimaler Plan mit genau einem Primitiv. */ +function planWith(primitives: Plan["primitives"]): Plan { + return { primitives, bounds: { minX: 0, minY: 0, maxX: 10, maxY: 10 } } as Plan; +} + +/** Zählt, wie oft ein DXF-Entity-Typ als eigene Gruppe (0/TYP) vorkommt. */ +function countEntities(dxf: string, type: string): number { + return dxf.split(/\r?\n/).filter((l, i, all) => l.trim() === "0" && all[i + 1]?.trim() === type) + .length; +} + +const code = sampleProject.layers[0].code; + +describe("buildPlanDxf — gezeichnete Kreise/Bögen", () => { + it("drawingCircle → CIRCLE-Entity", () => { + const dxf = buildPlanDxf( + planWith([ + { + kind: "drawingCircle", + center: { x: 1, y: 2 }, + r: 3, + fill: "none", + stroke: "#000000", + weightMm: 0.18, + categoryCode: code, + } as Plan["primitives"][number], + ]), + sampleProject, + ); + expect(countEntities(dxf, "CIRCLE")).toBe(1); + }); + + it("drawingArc → ARC-Entity (Winkel in Grad, CCW wie im Plan)", () => { + const dxf = buildPlanDxf( + planWith([ + { + kind: "drawingArc", + center: { x: 0, y: 0 }, + r: 2, + a0: 0, + a1: Math.PI / 2, + stroke: "#000000", + weightMm: 0.18, + categoryCode: code, + } as Plan["primitives"][number], + ]), + sampleProject, + ); + expect(countEntities(dxf, "ARC")).toBe(1); + // Start-/Endwinkel (DXF-Gruppencodes 50/51) in Grad. + expect(dxf).toMatch(/\n\s*50\r?\n\s*0(\.0+)?\r?\n/); + expect(dxf).toMatch(/\n\s*51\r?\n\s*90(\.0+)?\r?\n/); + }); + + it("ein Bogen bleibt EIN Entity — keine Kette von LINEs", () => { + const dxf = buildPlanDxf( + planWith([ + { + kind: "drawingArc", + center: { x: 0, y: 0 }, + r: 2, + a0: 0, + a1: Math.PI, + stroke: "#000000", + weightMm: 0.18, + categoryCode: code, + } as Plan["primitives"][number], + ]), + sampleProject, + ); + expect(countEntities(dxf, "ARC")).toBe(1); + expect(countEntities(dxf, "LINE")).toBe(0); + }); +}); diff --git a/src/export/exportDxf.gradient.test.ts b/src/export/exportDxf.gradient.test.ts new file mode 100644 index 0000000..cda27ad --- /dev/null +++ b/src/export/exportDxf.gradient.test.ts @@ -0,0 +1,69 @@ +/** + * DXF-Export von Verlauf-Schraffuren (`HatchStyle.kind === "gradient"`). + * DXF trägt keine echten Farbverläufe (wie bereits bei Bild-Schraffuren + * akzeptiert) — der Export muss auf die reine Umriss-Polylinie zurückfallen + * und darf KEINE (aus dem stehengebliebenen `pattern`-Feld abgeleiteten) + * Musterlinien mehr ausgeben. + */ + +import { describe, expect, it } from "vitest"; +import { buildPlanDxf } from "./exportDxf"; +import { sampleProject } from "../model/sampleProject"; +import type { Plan } from "../plan/generatePlan"; +import type { HatchRender } from "../plan/generatePlan/shared"; + +function planWith(primitives: Plan["primitives"]): Plan { + return { primitives, bounds: { minX: 0, minY: 0, maxX: 10, maxY: 10 } } as Plan; +} + +function countEntities(dxf: string, type: string): number { + return dxf.split(/\r?\n/).filter((l, i, all) => l.trim() === "0" && all[i + 1]?.trim() === type).length; +} + +const SQUARE = [ + { x: 0, y: 0 }, + { x: 4, y: 0 }, + { x: 4, y: 4 }, + { x: 0, y: 4 }, +]; + +function polyWith(hatchOver: Partial = {}): Plan["primitives"][number] { + return { + kind: "polygon", + pts: SQUARE, + fill: "#eeeeee", + stroke: "#111111", + strokeWidthMm: 0.25, + hatch: { + pattern: "crosshatch", // würde OHNE gradient-Ausschluss ein Kreuzmuster erzeugen + scale: 1, + angle: 0, + color: "#123456", + lineWeight: 0.13, + dash: null, + ...hatchOver, + }, + } as Plan["primitives"][number]; +} + +describe("buildPlanDxf — Verlauf-Schraffur", () => { + it("vektor+crosshatch: erzeugt Musterlinien (Gegenprobe)", () => { + const dxf = buildPlanDxf(planWith([polyWith()]), sampleProject); + expect(countEntities(dxf, "LINE")).toBeGreaterThan(0); + expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // nur der Umriss + }); + + it("gradient: KEINE Musterlinien, nur die Umriss-Polylinie", () => { + const dxf = buildPlanDxf( + planWith([ + polyWith({ + kind: "gradient", + gradient: { color1: "#ffffff", color2: "#000000", angle: 45, type: "linear" }, + }), + ]), + sampleProject, + ); + expect(countEntities(dxf, "LINE")).toBe(0); + expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // Umriss bleibt erhalten + }); +}); diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index bf97833..65e31cb 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -135,6 +135,18 @@ function emitPrimitive( emitArc(dxf, p, layer); break; + // Gezeichnete Kreise/Bögen (2D-Elemente) waren bisher gar nicht im DXF — + // der Writer kann beides längst, es fehlte nur der Zweig. `drawingArc` + // läuft per Konvention immer CCW von a0 nach a1 (s. planView/primitives), + // genau wie DXF-Bögen; daher direkte Grad-Umrechnung ohne Tausch. + case "drawingCircle": + dxf.addCircle(layer, p.center, p.r); + break; + + case "drawingArc": + dxf.addArc(layer, p.center, p.r, (p.a0 * 180) / Math.PI, (p.a1 * 180) / Math.PI); + break; + case "polygon": { const pts = p.pts; if (pts.length < 2) break; @@ -143,13 +155,15 @@ function emitPrimitive( dxf.addPolyline(layer, pts, true); // Schraffur als geklippte Linien (optional). Vollfüllung/„none" tragen keine // sichtbaren Musterlinien → wir geben nur echte Muster (nicht solid/none) aus. - // Bild-Schraffur (kind==="image"): DXF trägt keine Rasterbilder → - // FALLBACK ohne Musterlinien (nur die Umriss-Polylinie oben). Als - // Folge-Arbeit dokumentiert. Random-Vektor: deterministische Streu-Striche + // Bild-/Verlauf-Schraffur (kind==="image"/"gradient"): DXF trägt weder + // Rasterbilder noch (hier) echte Farbverläufe → FALLBACK ohne + // Musterlinien (nur die Umriss-Polylinie oben). Als Folge-Arbeit + // dokumentiert. Random-Vektor: deterministische Streu-Striche // (Modell-Meter, identischer Seed wie Bildschirm/PDF). if ( includeHatches && p.hatch.kind !== "image" && + p.hatch.kind !== "gradient" && p.hatch.pattern !== "none" && p.hatch.pattern !== "solid" ) { diff --git a/src/export/exportSvg.ts b/src/export/exportSvg.ts new file mode 100644 index 0000000..bb748e4 --- /dev/null +++ b/src/export/exportSvg.ts @@ -0,0 +1,54 @@ +// SVG-Export des Grundrisses — Nutzer-Wunsch: „Kein SVG-Export. Nur DXF- und +// Vektor-PDF-Dialog existieren, obwohl `sceneToPrintSvg` intern längst +// druckgenaues SVG baut (für den PDF-Pfad) — wird nie als eigenständiger +// Download angeboten." Reine Serialisierung DESSELBEN Druck-SVG, das +// `exportPdf.ts` ohnehin schon baut (identische Quelle wie Bildschirm/PDF, +// s. dortiger Kopfkommentar) — nur ohne den Umweg über jsPDF/svg2pdf. +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { Plan } from "../plan/generatePlan"; +import { planToRenderScene } from "../plan/toRenderScene"; +import { sceneToPrintSvg } from "./sceneToPrintSvg"; +import { pageSizeMm } from "./exportPdf"; +import type { Orientation, PaperFormat } from "./exportPdf"; + +export interface ExportSvgOptions { + /** Massstab-Nenner N (1:N) — dieselbe Bedeutung wie beim PDF-Export. */ + scaleDenominator: number; + paper: PaperFormat; + orientation: Orientation; + /** Dateiname des Downloads (ohne/inkl. .svg). */ + fileName?: string; +} + +/** + * Baut das papier-mm-bemasste Druck-SVG als String (fertig zum Speichern/ + * Einbetten). Reine Funktion, kein Download — s. {@link savePlanSvg}. + */ +export function buildPlanSvg(plan: Plan, opts: ExportSvgOptions): string { + const { w: pageW, h: pageH } = pageSizeMm(opts.paper, opts.orientation); + const scene = planToRenderScene(plan, opts.scaleDenominator); + const print = sceneToPrintSvg(scene, { + scaleDenominator: opts.scaleDenominator, + pageWidthMm: pageW, + pageHeightMm: pageH, + marginMm: 10, + }); + return new XMLSerializer().serializeToString(print.svg); +} + +/** Baut das SVG und löst den Download aus (Browser-Blob, wie `savePlanDxf`). */ +export function savePlanSvg(plan: Plan, opts: ExportSvgOptions): void { + const text = buildPlanSvg(plan, opts); + const name = (opts.fileName ?? "grundriss").replace(/\.svg$/i, ""); + const blob = new Blob([text], { type: "image/svg+xml" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${name}.svg`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} diff --git a/src/export/planToPrintSvg.ts b/src/export/planToPrintSvg.ts index 02d6c5e..6a989d1 100644 --- a/src/export/planToPrintSvg.ts +++ b/src/export/planToPrintSvg.ts @@ -220,7 +220,12 @@ function appendPrimitive( map: Mapper, mmPerM: number, ): void { - const opacity = p.greyed ? "0.3" : undefined; + // Gedimmt (0.3) und Objekt-Transparenz multiplizieren sich; Bilder tragen + // ihre eigene Deckkraft separat (s. dortiger Zweig). + const objOpacity = p.kind === "drawingImage" ? 1 : (p.opacity ?? 1); + const dim = p.greyed ? 0.3 : 1; + const combined = dim * Math.max(0, objOpacity); + const opacity = combined < 1 ? String(combined) : undefined; switch (p.kind) { case "polygon": appendPolygon(svg, p, map, mmPerM, opacity); @@ -256,6 +261,29 @@ function appendPrimitive( svg.appendChild(node); break; } + case "drawingCircle": { + const c = map(p.center); + const el = document.createElementNS(SVG_NS, "circle"); + el.setAttribute("cx", String(round(c.x))); + el.setAttribute("cy", String(round(c.y))); + el.setAttribute("r", String(round(p.r * mmPerM))); + el.setAttribute("fill", p.fill && p.fill !== "none" ? p.fill : "none"); + el.setAttribute("stroke", p.stroke); + el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); + if (p.dash && p.dash.length) { + el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); + if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); + } + if (opacity) el.setAttribute("opacity", opacity); + svg.appendChild(el); + break; + } + case "drawingArc": { + const node = drawingArcNode(p, map, mmPerM); + if (opacity) node.setAttribute("opacity", opacity); + svg.appendChild(node); + break; + } case "drawingText": { const node = drawingTextNode(p, map, mmPerM); if (node) { @@ -516,6 +544,39 @@ function arcNode( return el; } +/** + * `drawingArc` → glatter SVG-Bogen. Konvention wie im Bildschirm-Renderer + * (`planView/primitives.tsx`): die Winkel laufen im MODELL immer gegen den + * Uhrzeigersinn von `a0` nach `a1`; da die Ziel-Y-Achse gespiegelt ist, wird + * daraus am Papier ein Uhrzeigersinn-Bogen (sweep-flag 1). `large-arc` aus + * der normierten Spannweite. + */ +function drawingArcNode( + p: Extract, + map: Mapper, + mmPerM: number, +): SVGElement { + const TAU = Math.PI * 2; + const from = map({ x: p.center.x + p.r * Math.cos(p.a0), y: p.center.y + p.r * Math.sin(p.a0) }); + const to = map({ x: p.center.x + p.r * Math.cos(p.a1), y: p.center.y + p.r * Math.sin(p.a1) }); + const r = p.r * mmPerM; + const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU; + const largeArc = sweep > Math.PI ? 1 : 0; + const el = document.createElementNS(SVG_NS, "path"); + el.setAttribute( + "d", + `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 ${largeArc} 1 ${round(to.x)} ${round(to.y)}`, + ); + el.setAttribute("fill", "none"); + el.setAttribute("stroke", p.stroke); + el.setAttribute("stroke-width", String(quantizePen(p.weightMm))); + if (p.dash && p.dash.length) { + el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" ")); + if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round"); + } + return el; +} + /** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */ function round(v: number): number { return Math.round(v * 1000) / 1000; diff --git a/src/geometry/bulge.test.ts b/src/geometry/bulge.test.ts index ff06eaa..12fbc0d 100644 --- a/src/geometry/bulge.test.ts +++ b/src/geometry/bulge.test.ts @@ -4,7 +4,16 @@ */ import { describe, it, expect } from "vitest"; -import { bulgeArc, bulgeArcPoints, bulgeFromSagittaPoint } from "./bulge"; +import { + arcFromStartEndDirection, + arcFromStartEndRadius, + arcThroughPoints, + bulgeArc, + bulgeArcPoints, + bulgeFromSagittaPoint, + bulgeThroughPoint, +} from "./bulge"; +import type { Vec2 } from "../model/types"; describe("bulgeArc / bulgeArcPoints", () => { it("bulge 0 (oder fehlend) → Gerade, keine Bogen-Tessellation", () => { @@ -72,3 +81,191 @@ describe("bulgeFromSagittaPoint — Umkehrung für die Griff-Interaktion", () => expect(bulgeFromSagittaPoint(a, b, { x: 2, y: 0 })).toBeCloseTo(0, 9); }); }); + +describe("bulgeThroughPoint — Drei-Punkt-Bogen (unabhängig vom Vorgänger-Segment)", () => { + it("Halbkreis über der Sehne: Durchgangspunkt im Scheitel", () => { + const b = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 2 }, { x: 4, y: 0 }); + // Halbkreis → |bulge| = 1 (Δ = 180°, tan(45°) = 1); Wölbung nach +Y + // liegt LINKS von a→b, also positiv. + expect(b).toBeCloseTo(1, 9); + }); + + it("Durchgangspunkt auf der anderen Seite kehrt das Vorzeichen um", () => { + const b = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: -2 }, { x: 4, y: 0 }); + expect(b).toBeCloseTo(-1, 9); + }); + + it("der erzeugte Bogen läuft tatsächlich durch den Durchgangspunkt", () => { + const a = { x: 0, y: 0 }; + const through = { x: 3, y: 1 }; + const bb = { x: 5, y: -2 }; + const bulge = bulgeThroughPoint(a, through, bb); + const arc = bulgeArc(a, bb, bulge)!; + // Der Durchgangspunkt liegt auf dem Kreis … + expect(Math.hypot(through.x - arc.center.x, through.y - arc.center.y)).toBeCloseTo(arc.r, 9); + // … und innerhalb der tatsächlich durchlaufenen Spanne. + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const rel = arc.sweep >= 0 + ? norm(Math.atan2(through.y - arc.center.y, through.x - arc.center.x) - arc.a0) + : norm(arc.a0 - Math.atan2(through.y - arc.center.y, through.x - arc.center.x)); + expect(rel).toBeLessThanOrEqual(Math.abs(arc.sweep) + 1e-9); + }); + + it("kollineare Punkte → gerade (kein Kreis)", () => { + expect(bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 5, y: 0 })).toBe(0); + }); + + it("die Grösse hängt NUR von den drei Punkten ab (unabhängig vom Startpunkt der Kette)", () => { + // Dieselbe relative Geometrie an anderer Stelle ⇒ identischer Bulge. + const b1 = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }); + const b2 = bulgeThroughPoint({ x: 100, y: 50 }, { x: 102, y: 51 }, { x: 104, y: 50 }); + expect(b2).toBeCloseTo(b1, 12); + }); +}); + +describe("arcThroughPoints — Drei-Punkt-Bogen als {center,r,a0,a1} (commands/cmds/arc.ts)", () => { + it("Viertelkreis (0°→90° via 45°) liefert Mittelpunkt/Radius/Winkel exakt", () => { + const a = { x: 1, y: 0 }; + const through = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; // 45° + const b = { x: 0, y: 1 }; + const arc = arcThroughPoints(a, through, b)!; + expect(arc).not.toBeNull(); + expect(arc.center.x).toBeCloseTo(0, 9); + expect(arc.center.y).toBeCloseTo(0, 9); + expect(arc.r).toBeCloseTo(1, 9); + expect(arc.a0).toBeCloseTo(0, 9); + expect(arc.a1).toBeCloseTo(Math.PI / 2, 9); + }); + + it("a0/a1 laufen IMMER CCW und decken den Durchgangspunkt ab, unabhängig von der Klickreihenfolge (a,through,b) vs (b,through,a)", () => { + const a = { x: 1, y: 0 }; + const through = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; + const b = { x: 0, y: 1 }; + const forward = arcThroughPoints(a, through, b)!; + const backward = arcThroughPoints(b, through, a)!; + expect(backward.center.x).toBeCloseTo(forward.center.x, 9); + expect(backward.center.y).toBeCloseTo(forward.center.y, 9); + expect(backward.r).toBeCloseTo(forward.r, 9); + expect(backward.a0).toBeCloseTo(forward.a0, 9); + expect(backward.a1).toBeCloseTo(forward.a1, 9); + }); + + it("Start/End/Durchgangspunkt liegen alle auf dem Kreis, Durchgangspunkt innerhalb [a0,a1]", () => { + const a = { x: 0, y: 0 }; + const through = { x: 3, y: 1 }; + const b = { x: 5, y: -2 }; + const arc = arcThroughPoints(a, through, b)!; + const onCircle = (p: { x: number; y: number }) => + Math.hypot(p.x - arc.center.x, p.y - arc.center.y); + expect(onCircle(a)).toBeCloseTo(arc.r, 9); + expect(onCircle(b)).toBeCloseTo(arc.r, 9); + expect(onCircle(through)).toBeCloseTo(arc.r, 9); + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + const sweep = norm(arc.a1 - arc.a0); + const toThrough = norm(Math.atan2(through.y - arc.center.y, through.x - arc.center.x) - arc.a0); + expect(toThrough).toBeLessThanOrEqual(sweep + 1e-9); + }); + + it("kollineare Punkte → null (kein Kreis)", () => { + expect(arcThroughPoints({ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 5, y: 0 })).toBeNull(); + }); +}); + +describe("arcFromStartEndRadius — Start/Ende/Radius (commands/cmds/arc.ts, dritte Methode)", () => { + const onCircle = (arc: { center: Vec2; r: number }, p: Vec2) => + Math.hypot(p.x - arc.center.x, p.y - arc.center.y); + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + + it("Halbkreis exakt bei r = halbe Sehnenlänge (Grenzfall)", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + const arc = arcFromStartEndRadius(a, b, 2, { x: 2, y: 5 })!; + expect(arc).not.toBeNull(); + expect(arc.r).toBeCloseTo(2, 9); + expect(onCircle(arc, a)).toBeCloseTo(2, 9); + expect(onCircle(arc, b)).toBeCloseTo(2, 9); + expect(norm(arc.a1 - arc.a0)).toBeCloseTo(Math.PI, 6); // exakt 180° + }); + + it("wölbt sich zur cursor-nahen Seite (near oberhalb → Bogenscheitel oberhalb der Sehne)", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + const arc = arcFromStartEndRadius(a, b, 3, { x: 2, y: 5 })!; + const mid = arc.a0 + norm(arc.a1 - arc.a0) / 2; + const apex = { x: arc.center.x + arc.r * Math.cos(mid), y: arc.center.y + arc.r * Math.sin(mid) }; + expect(apex.y).toBeGreaterThan(0); + }); + + it("wölbt sich zur ANDEREN Seite, wenn `near` unterhalb der Sehne liegt", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + const arc = arcFromStartEndRadius(a, b, 3, { x: 2, y: -5 })!; + const mid = arc.a0 + norm(arc.a1 - arc.a0) / 2; + const apex = { x: arc.center.x + arc.r * Math.cos(mid), y: arc.center.y + arc.r * Math.sin(mid) }; + expect(apex.y).toBeLessThan(0); + }); + + it("liefert immer den KLEINEREN Bogen (Sehnenwinkel ≤ 180°)", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + const arc = arcFromStartEndRadius(a, b, 10, { x: 2, y: 1 })!; + expect(norm(arc.a1 - arc.a0)).toBeLessThanOrEqual(Math.PI + 1e-9); + }); + + it("liefert null, wenn der Radius kleiner als die halbe Sehnenlänge ist", () => { + expect(arcFromStartEndRadius({ x: 0, y: 0 }, { x: 4, y: 0 }, 1, { x: 2, y: 1 })).toBeNull(); + }); + + it("liefert null bei entarteter Sehne (a≈b)", () => { + expect(arcFromStartEndRadius({ x: 1, y: 1 }, { x: 1, y: 1 }, 2, { x: 2, y: 2 })).toBeNull(); + }); +}); + +describe("arcFromStartEndDirection — Start/Ende/Tangentenrichtung (commands/cmds/arc.ts, vierte Methode)", () => { + const onCircle = (arc: { center: Vec2; r: number }, p: Vec2) => + Math.hypot(p.x - arc.center.x, p.y - arc.center.y); + + it("Viertelkreis: Tangente bei (1,0) nach +y führt zum Bogen bis (0,1)", () => { + const a = { x: 1, y: 0 }; + const b = { x: 0, y: 1 }; + const dir = { x: 1, y: 1 }; // von a aus Richtung +y (tangential zum Einheitskreis bei a) + const arc = arcFromStartEndDirection(a, b, dir)!; + expect(arc).not.toBeNull(); + expect(arc.center.x).toBeCloseTo(0, 6); + expect(arc.center.y).toBeCloseTo(0, 6); + expect(arc.r).toBeCloseTo(1, 6); + expect(onCircle(arc, a)).toBeCloseTo(1, 9); + expect(onCircle(arc, b)).toBeCloseTo(1, 9); + }); + + it("Bogen-Tangente bei a zeigt tatsächlich in Richtung `dir`, nicht rückwärts", () => { + const a = { x: 1, y: 0 }; + const b = { x: 0, y: 1 }; + const dir = { x: 1, y: 1 }; + const arc = arcFromStartEndDirection(a, b, dir)!; + // CCW-Tangente bei a0 (Ableitung von (cos,sin) nach wachsendem Winkel). + const tangentCCW = { x: -Math.sin(arc.a0), y: Math.cos(arc.a0) }; + const wantedDir = { x: dir.x - a.x, y: dir.y - a.y }; + const dot = tangentCCW.x * wantedDir.x + tangentCCW.y * wantedDir.y; + expect(dot).toBeGreaterThan(0); + }); + + it("entgegengesetzte Tangentenrichtung liefert den KOMPLEMENTÄREN Bogen (gleicher Kreis, andere Seite)", () => { + const a = { x: 1, y: 0 }; + const b = { x: 0, y: 1 }; + const forward = arcFromStartEndDirection(a, b, { x: 1, y: 1 })!; + const backward = arcFromStartEndDirection(a, b, { x: 1, y: -1 })!; + expect(backward.center.x).toBeCloseTo(forward.center.x, 6); + expect(backward.center.y).toBeCloseTo(forward.center.y, 6); + expect(backward.r).toBeCloseTo(forward.r, 6); + // Unterschiedlicher Schwenk (a0/a1 vertauscht bzw. andere Bogenseite). + expect(backward.a0).not.toBeCloseTo(forward.a0, 3); + }); + + it("liefert null bei entarteter Tangentenrichtung (dir≈a)", () => { + expect(arcFromStartEndDirection({ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 0 })).toBeNull(); + }); +}); diff --git a/src/geometry/bulge.ts b/src/geometry/bulge.ts index 5216cbc..4d5ee27 100644 --- a/src/geometry/bulge.ts +++ b/src/geometry/bulge.ts @@ -11,6 +11,7 @@ // eine einzige inverse Winkelfunktion aus bulge ableiten. import type { Vec2 } from "../model/types"; +import { lineIntersect } from "../model/geometry"; const EPS = 1e-9; @@ -109,11 +110,68 @@ export function bulgePointAt(a: Vec2, b: Vec2, bulge: number, t: number): Vec2 { return pts[Math.max(0, Math.min(pts.length - 1, idx))]; } +/** + * Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der + * klassische Drei-Punkt-Bogen. Anders als die Tangenten-Variante hängt er NUR + * von diesen drei Punkten ab, nicht vom vorherigen Segment: Radius und + * Wölbung sind damit pro Segment frei wählbar (Nutzer-Anforderung). + * + * Liegen die drei Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis — + * dann 0 (gerade). + */ +export function bulgeThroughPoint(a: Vec2, through: Vec2, b: Vec2): number { + // Umkreismittelpunkt über die Schnittpunkt-Formel der Mittelsenkrechten. + const d = 2 * (a.x * (through.y - b.y) + through.x * (b.y - a.y) + b.x * (a.y - through.y)); + if (Math.abs(d) < EPS) return 0; + const a2 = a.x * a.x + a.y * a.y; + const t2 = through.x * through.x + through.y * through.y; + const b2 = b.x * b.x + b.y * b.y; + const center = { + x: (a2 * (through.y - b.y) + t2 * (b.y - a.y) + b2 * (a.y - through.y)) / d, + y: (a2 * (b.x - through.x) + t2 * (a.x - b.x) + b2 * (through.x - a.x)) / d, + }; + const r = Math.hypot(a.x - center.x, a.y - center.y); + if (r < EPS) return 0; + const ang = (p: Vec2) => Math.atan2(p.y - center.y, p.x - center.x); + const TAU = Math.PI * 2; + const norm = (x: number) => ((x % TAU) + TAU) % TAU; + // Schwenkrichtung ist die, bei der `through` unterwegs passiert wird. + const aFrom = ang(a); + const ccwToThrough = norm(ang(through) - aFrom); + const ccwToB = norm(ang(b) - aFrom); + const sweepSign: 1 | -1 = ccwToThrough <= ccwToB ? 1 : -1; + return bulgeBetweenAngles(center, r, aFrom, ang(b), sweepSign); +} + /** Punkt auf einem Kreis (center, r) beim Winkel `a` (Radiant). */ export function pointOnCircle(center: Vec2, r: number, a: number): Vec2 { return { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) }; } +/** + * Kreisbogen-Parameter (Mittelpunkt/Radius/Start-/Endwinkel) durch drei Punkte + * `a`→`through`→`b` — der klassische Drei-Punkt-Bogen, hier direkt als + * `{center,r,a0,a1}` statt als `bulge` (für Werkzeuge, die einen eigenständigen + * `{shape:"arc"}` erzeugen, z. B. `commands/cmds/arc.ts`, statt ein + * Polylinien-Segment). `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von + * a0 nach a1 läuft (Konvention von `{shape:"arc"}`, s. dort) — anders als + * `bulgeThroughPoint`, dessen Vorzeichen die Sehnen-Richtung a→b behält. + * `null` bei (nahezu) kollinearen Punkten (kein Kreis). + */ +export function arcThroughPoints( + a: Vec2, + through: Vec2, + b: Vec2, +): { center: Vec2; r: number; a0: number; a1: number } | null { + const bulge = bulgeThroughPoint(a, through, b); + if (Math.abs(bulge) < EPS) return null; + const arc = bulgeArc(a, b, bulge); + if (!arc) return null; + return arc.sweep < 0 + ? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 } + : { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 }; +} + /** * Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` * zu `aTo`, in der durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, @@ -139,3 +197,85 @@ export function bulgeBetweenAngles( const M = pointOnCircle(center, r, mid); return bulgeFromSagittaPoint(P, Q, M); } + +/** + * Kreisbogen-Parameter durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius + * `r` — die zweite fehlende Bogen-Konstruktionsmethode aus der Recherche + * „Grösster Hebel" (`commands/cmds/arc.ts`, Methode „Start-Ende-Radius"). + * `near` (typischerweise der Cursor) entscheidet, auf welche Seite der Sehne + * sich der Bogen wölbt — analog zu einem gezogenen Bulge-Griff. Liefert + * immer den KLEINEREN der beiden möglichen Bögen (Sehnenwinkel ≤ 180°): der + * Radius allein legt zwei Kreise fest (Zentrum auf einer der beiden Seiten + * der Sehne), aber erst zusammen mit „welcher Bogen dieses Kreises" ergäbe + * sich sonst eine dritte, unnötige Mehrdeutigkeit — der kleinere Bogen ist + * die für eine Zieh-Geste erwartbare, stetige Wahl (grosser Radius ⇒ flacher + * Bogen, kleiner Radius (nahe der halben Sehnenlänge) ⇒ Halbkreis). + * `null`, wenn `r` kleiner als die halbe Sehnenlänge ist (kein Kreis möglich) + * oder die Sehne entartet (a≈b). + */ +export function arcFromStartEndRadius( + a: Vec2, + b: Vec2, + r: number, + near: Vec2, +): { center: Vec2; r: number; a0: number; a1: number } | null { + const dx = b.x - a.x, dy = b.y - a.y; + const chord = Math.hypot(dx, dy); + if (chord < EPS) return null; + const h = chord / 2; + if (r < h - EPS) return null; + const rr = Math.max(r, h); + const s = rr - Math.sqrt(Math.max(0, rr * rr - h * h)); // Sagitta des kleineren Bogens + const ux = dx / chord, uy = dy / chord; + const nx = -uy, ny = ux; // Links-Normale von a→b, wie `bulgeArc` + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; + const sideSign = (near.x - mx) * nx + (near.y - my) * ny >= 0 ? 1 : -1; + const bulge = (sideSign * s) / h; + const arc = bulgeArc(a, b, bulge); + if (!arc) return null; + return arc.sweep < 0 + ? { center: arc.center, r: arc.r, a0: arc.a1, a1: arc.a0 } + : { center: arc.center, r: arc.r, a0: arc.a0, a1: arc.a1 }; +} + +/** + * Kreisbogen-Parameter durch zwei Endpunkte `a`→`b`, tangential zu einer bei + * `a` vorgegebenen Richtung (`dir`, ein Punkt AUF dem Tangentenstrahl, nicht + * zwingend auf dem Bogen selbst) — dritte fehlende Bogen-Konstruktions- + * methode. Der Kreismittelpunkt steht per Definition senkrecht zur Tangente + * bei `a` UND auf der Mittelsenkrechten von a-b — beide Geraden geschnitten + * (`lineIntersect`) ergeben ihn eindeutig, ohne Fallunterscheidung. Die + * Schwenkrichtung (CCW/CW von a0 nach a1) wird so gewählt, dass die + * Bogen-Tangente bei a tatsächlich in Richtung `dir` zeigt (nicht rückwärts). + * `null` bei entarteter Tangente (`dir`≈`a`) oder wenn die Tangente exakt + * entlang der Sehne a-b zeigt (Mittelsenkrechte und Tangenten-Normale + * parallel — kein eindeutiger Kreis, Grenzfall „Gerade"). + */ +export function arcFromStartEndDirection( + a: Vec2, + b: Vec2, + dir: Vec2, +): { center: Vec2; r: number; a0: number; a1: number } | null { + const tx = dir.x - a.x, ty = dir.y - a.y; + const tLen = Math.hypot(tx, ty); + if (tLen < EPS) return null; + const ux = tx / tLen, uy = ty / tLen; + const tangentNormal = { x: -uy, y: ux }; // senkrecht zur Tangente bei a + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + const chordNormal = { x: -(b.y - a.y), y: b.x - a.x }; // senkrecht zur Sehne a-b + const center = lineIntersect(a, tangentNormal, mid, chordNormal); + if (!center) return null; + const r = Math.hypot(a.x - center.x, a.y - center.y); + if (r < EPS) return null; + const a0raw = Math.atan2(a.y - center.y, a.x - center.x); + const a1raw = Math.atan2(b.y - center.y, b.x - center.x); + // CCW-Tangentenrichtung bei a0raw ist die Ableitung von (cos,sin) nach + // wachsendem Winkel: (−sin,cos). Zeigt sie NICHT in Richtung (ux,uy), muss + // der Bogen stattdessen CW laufen (a0/a1 vertauscht, wie `arcThroughPoints` + // bei negativem `sweep`). + const tangentCCW = { x: -Math.sin(a0raw), y: Math.cos(a0raw) }; + const matchesCCW = tangentCCW.x * ux + tangentCCW.y * uy >= 0; + return matchesCCW + ? { center, r, a0: a0raw, a1: a1raw } + : { center, r, a0: a1raw, a1: a0raw }; +} diff --git a/src/geometry/kernel2d.break.test.ts b/src/geometry/kernel2d.break.test.ts new file mode 100644 index 0000000..67ab84f --- /dev/null +++ b/src/geometry/kernel2d.break.test.ts @@ -0,0 +1,84 @@ +/** + * `nearestOnPolyline`/`breakCurve` — Grundlage des BREAK-Befehls (entfernt + * den Abschnitt ZWISCHEN zwei Positionen auf einer offenen Punktfolge). + */ +import { describe, it, expect } from "vitest"; +import { breakCurve, nearestOnPolyline } from "./kernel2d"; +import type { Vec2 } from "../model/types"; + +describe("nearestOnPolyline", () => { + it("findet die nächste Position auf einer geraden Linie", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }]; + const hit = nearestOnPolyline(pts, false, { x: 3, y: 1 }); + expect(hit).not.toBeNull(); + expect(hit!.edgeIndex).toBe(0); + expect(hit!.t).toBeCloseTo(0.3, 6); + }); + + it("wählt die richtige Kante bei mehreren Segmenten", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 5 }]; + const hit = nearestOnPolyline(pts, false, { x: 5, y: 3 }); + expect(hit).not.toBeNull(); + expect(hit!.edgeIndex).toBe(1); + expect(hit!.t).toBeCloseTo(0.6, 6); + }); + + it("klemmt t auf [0,1] (Klick jenseits eines Endpunkts)", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }]; + const hit = nearestOnPolyline(pts, false, { x: 20, y: 0 }); + expect(hit!.t).toBe(1); + }); + + it("liefert null bei < 2 Punkten", () => { + expect(nearestOnPolyline([{ x: 0, y: 0 }], false, { x: 0, y: 0 })).toBeNull(); + }); +}); + +describe("breakCurve", () => { + const line: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }]; + + it("entfernt den Abschnitt zwischen zwei Punkten auf einer geraden Linie", () => { + const hit1 = nearestOnPolyline(line, false, { x: 3, y: 0 })!; + const hit2 = nearestOnPolyline(line, false, { x: 7, y: 0 })!; + const pieces = breakCurve(line, hit1, hit2); + expect(pieces.length).toBe(2); + expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 3, y: 0 }]); + expect(pieces[1]).toEqual([{ x: 7, y: 0 }, { x: 10, y: 0 }]); + }); + + it("Klick-Reihenfolge ist irrelevant (Positionen werden intern sortiert)", () => { + const hit1 = nearestOnPolyline(line, false, { x: 7, y: 0 })!; // zuerst der SPÄTERE Punkt geklickt + const hit2 = nearestOnPolyline(line, false, { x: 3, y: 0 })!; + const pieces = breakCurve(line, hit1, hit2); + expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 3, y: 0 }]); + expect(pieces[1]).toEqual([{ x: 7, y: 0 }, { x: 10, y: 0 }]); + }); + + it("Bruch nahe einem Endpunkt liefert nur EIN Reststück (das andere fällt zu kurz aus)", () => { + const hit1 = nearestOnPolyline(line, false, { x: 0, y: 0 })!; + const hit2 = nearestOnPolyline(line, false, { x: 6, y: 0 })!; + const pieces = breakCurve(line, hit1, hit2); + expect(pieces.length).toBe(1); + expect(pieces[0]).toEqual([{ x: 6, y: 0 }, { x: 10, y: 0 }]); + }); + + it("funktioniert über mehrere Segmente einer offenen Polylinie hinweg", () => { + const poly: Vec2[] = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 5 }, { x: 10, y: 5 }]; + const hit1 = nearestOnPolyline(poly, false, { x: 2, y: 0 })!; // auf Segment 0 + const hit2 = nearestOnPolyline(poly, false, { x: 8, y: 5 })!; // auf Segment 2 + const pieces = breakCurve(poly, hit1, hit2); + expect(pieces.length).toBe(2); + expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }]); + expect(pieces[1]).toEqual([{ x: 8, y: 5 }, { x: 10, y: 5 }]); + }); + + it("beide Punkte auf derselben Kante trennen sauber, ohne die übrigen Punkte zu verlieren", () => { + const poly: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }]; + const hit1 = nearestOnPolyline(poly, false, { x: 4, y: 0 })!; + const hit2 = nearestOnPolyline(poly, false, { x: 6, y: 0 })!; + const pieces = breakCurve(poly, hit1, hit2); + expect(pieces.length).toBe(2); + expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }]); + expect(pieces[1]).toEqual([{ x: 6, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }]); + }); +}); diff --git a/src/geometry/kernel2d.ts b/src/geometry/kernel2d.ts index 53814e8..8f69b4d 100644 --- a/src/geometry/kernel2d.ts +++ b/src/geometry/kernel2d.ts @@ -884,6 +884,64 @@ export function circleCircleIntersect( return [add(mid, scale(n, h)), add(mid, scale(n, -h))]; } +// ── Tangente-Tangente-Radius (Apollonius-Spezialfall) ─────────────────────── + +/** Ein Tangentialobjekt für `tangentCircleCenters`: Gerade (durch a/b, unendlich gedacht) oder Kreis. */ +export type TangentTarget = { kind: "line"; a: Vec2; b: Vec2 } | { kind: "circle"; center: Vec2; r: number }; + +/** Der geometrische Ort aller Mittelpunkte von Kreisen mit Radius `r`, die `t` berühren. */ +function tangentLoci(t: TangentTarget, r: number): TangentTarget[] { + if (t.kind === "line") { + const [a1, b1] = offsetSegment(t.a, t.b, r); + const [a2, b2] = offsetSegment(t.a, t.b, -r); + return [ + { kind: "line", a: a1, b: b1 }, + { kind: "line", a: a2, b: b2 }, + ]; + } + // Kreis: zwei Fälle sind geometrisch gültig — äussere Berührung (Radien + // addieren sich) und innere Berührung (Radien-Differenz, ein Kreis liegt im + // anderen). Beide werden als Kandidaten geliefert; welcher plausibel ist, + // entscheidet der Aufrufer über einen Referenzpunkt (Klickposition). + const out: TangentTarget[] = [{ kind: "circle", center: t.center, r: t.r + r }]; + const inner = Math.abs(t.r - r); + if (inner > EPS) out.push({ kind: "circle", center: t.center, r: inner }); + return out; +} + +function intersectLoci(l1: TangentTarget, l2: TangentTarget): Vec2[] { + if (l1.kind === "line") { + if (l2.kind === "line") { + const p = lineIntersect(l1.a, sub(l1.b, l1.a), l2.a, sub(l2.b, l2.a)); + return p ? [p] : []; + } + return lineCircleIntersect(l1.a, l1.b, l2.center, l2.r); + } + if (l2.kind === "line") return lineCircleIntersect(l2.a, l2.b, l1.center, l1.r); + return circleCircleIntersect(l1.center, l1.r, l2.center, l2.r); +} + +/** + * Alle geometrisch gültigen Mittelpunkt-Kandidaten für einen Kreis mit + * gegebenem Radius `r`, der tangential an BEIDE `t1` und `t2` liegt + * (Tangente-Tangente-Radius / TTR-Konstruktion, Spezialfall des Apollonius- + * Problems mit bekanntem Radius statt drei tangentialen Objekten). Jedes + * Tangentialobjekt hat 1-2 gültige „Loci" (Gerade: beide Seiten; Kreis: + * innere/äussere Berührung) — alle Loci-Paare werden geschnitten, das + * Ergebnis ist UNSORTIERT/undedupliziert. Der Aufrufer wählt über einen + * Referenzpunkt (typischerweise die Klickpunkte, mit denen die beiden + * Objekte gewählt wurden) den plausiblen Kandidaten aus. + */ +export function tangentCircleCenters(t1: TangentTarget, t2: TangentTarget, r: number): Vec2[] { + const out: Vec2[] = []; + for (const l1 of tangentLoci(t1, r)) { + for (const l2 of tangentLoci(t2, r)) { + out.push(...intersectLoci(l1, l2)); + } + } + return out; +} + // ── Polygon-Fläche / Wicklung ─────────────────────────────────────────────── /** Vorzeichenbehaftete Polygonfläche (Shoelace); >0 = CCW, <0 = CW. */ @@ -1170,6 +1228,56 @@ export function removeSegmentWithBulge( : { pts: rightPts, closed: false, bulge: rightBulge }; } +/** Position auf einer OFFENEN Kurve: Kantenindex + Parameter (0..1) auf dieser Kante. */ +export interface CurveHit { + edgeIndex: number; + t: number; +} + +/** + * Nächste Position auf einer (offenen ODER geschlossenen) Punktfolge zu `pt` — + * Kantenindex + geklemmter Parameter. `null` bei < 2 Punkten. Grundlage für + * BREAK (zwei Klicks → zwei Positionen auf DERSELBEN Kurve). + */ +export function nearestOnPolyline(pts: Vec2[], closed: boolean, pt: Vec2): CurveHit | null { + const n = pts.length; + if (n < 2) return null; + const edgeCount = closed ? n : n - 1; + let best: CurveHit | null = null; + let bestD = Infinity; + for (let i = 0; i < edgeCount; i++) { + const a = pts[i]; + const b = pts[(i + 1) % n]; + const t = Math.max(0, Math.min(1, projectParam(pt, a, b))); + const d = dist(pt, lerp(a, b, t)); + if (d < bestD) { + bestD = d; + best = { edgeIndex: i, t }; + } + } + return best; +} + +/** + * Entfernt den Abschnitt ZWISCHEN zwei Positionen auf einer OFFENEN Kurve + * (AutoCADs BREAK, Zwei-Punkt-Variante) — Klick-Reihenfolge ist irrelevant, + * die Positionen werden nach Kanten-Fortschritt sortiert. Liefert bis zu ZWEI + * Reststücke (vor der ersten, nach der zweiten Position); liegen beide + * Positionen auf demselben Rand (Kurvenanfang/-ende), kann ein Stück leer + * ausfallen. GESCHLOSSENE Kurven werden hier bewusst NICHT unterstützt (die + * Klick-Reihenfolge würde dort bestimmen, welcher der beiden Ring-Bögen + * übrig bleibt — eigener, grösserer Scope, s. PENDENZEN.md). + */ +export function breakCurve(pts: Vec2[], hit1: CurveHit, hit2: CurveHit): Vec2[][] { + const posOf = (h: CurveHit) => h.edgeIndex + h.t; + const [lo, hi] = posOf(hit1) <= posOf(hit2) ? [hit1, hit2] : [hit2, hit1]; + const p1 = lerp(pts[lo.edgeIndex], pts[lo.edgeIndex + 1], lo.t); + const p2 = lerp(pts[hi.edgeIndex], pts[hi.edgeIndex + 1], hi.t); + const left = dedupeConsecutive([...pts.slice(0, lo.edgeIndex + 1), p1]); + const right = dedupeConsecutive([p2, ...pts.slice(hi.edgeIndex + 1)]); + return [left, right].filter((s) => s.length >= 2); +} + /** Ein Schnitt-Treffer auf einer Ziel-Kante: Kantenindex + Parameter + Punkt. */ interface EdgeHit { edge: number; diff --git a/src/geometry/kernel2d.ttr.test.ts b/src/geometry/kernel2d.ttr.test.ts new file mode 100644 index 0000000..c1ebe74 --- /dev/null +++ b/src/geometry/kernel2d.ttr.test.ts @@ -0,0 +1,121 @@ +// Tests für `tangentCircleCenters` (Tangente-Tangente-Radius-Konstruktion), +// getrennt von `kernel2d.parity.test.ts` (dort werden nur die bereits vor +// dieser Session bestehenden Funktionen gegen die DXF-Referenzimplementierung +// geprüft). + +import { describe, it, expect } from "vitest"; +import { tangentCircleCenters, type TangentTarget } from "./kernel2d"; +import type { Vec2 } from "../model/types"; + +const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); + +/** Prüft, dass `center` mit Radius `r` tangential (Abstand == r) an `t` liegt. */ +function isTangent(center: Vec2, r: number, t: TangentTarget): boolean { + if (t.kind === "line") { + const dx = t.b.x - t.a.x, dy = t.b.y - t.a.y; + const len = Math.hypot(dx, dy); + const cross = ((center.x - t.a.x) * dy - (center.y - t.a.y) * dx) / len; + return Math.abs(Math.abs(cross) - r) < 1e-6; + } + const d = dist(center, t.center); + // Äussere ODER innere Berührung. + return Math.abs(d - (t.r + r)) < 1e-6 || Math.abs(d - Math.abs(t.r - r)) < 1e-6; +} + +describe("tangentCircleCenters — zwei Geraden", () => { + it("zwei senkrechte Geraden, Radius 2 → vier Kandidaten (je ein Quadrant)", () => { + const l1: TangentTarget = { kind: "line", a: { x: -10, y: 0 }, b: { x: 10, y: 0 } }; // X-Achse + const l2: TangentTarget = { kind: "line", a: { x: 0, y: -10 }, b: { x: 0, y: 10 } }; // Y-Achse + const cands = tangentCircleCenters(l1, l2, 2); + expect(cands.length).toBe(4); + // Ein Kandidat pro Quadrant, jeweils bei (±2, ±2). + const quadrants = [ + { x: 2, y: 2 }, + { x: 2, y: -2 }, + { x: -2, y: 2 }, + { x: -2, y: -2 }, + ]; + for (const q of quadrants) { + expect(cands.some((c) => dist(c, q) < 1e-9)).toBe(true); + } + for (const c of cands) { + expect(isTangent(c, 2, l1)).toBe(true); + expect(isTangent(c, 2, l2)).toBe(true); + } + }); + + it("parallele Geraden, Abstand ≠ 2*r → geometrisch unlösbar (ein Kreis tangential an beide Parallelen MUSS Durchmesser = Abstand haben), keine Kandidaten", () => { + const l1: TangentTarget = { kind: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }; + const l2: TangentTarget = { kind: "line", a: { x: 0, y: 4 }, b: { x: 10, y: 4 } }; + // Abstand 4, Zielradius 3 (Durchmesser 6 ≠ 4) → keine Lösung. + expect(tangentCircleCenters(l1, l2, 3)).toEqual([]); + }); + + it("parallele Geraden, Abstand GENAU 2*r → degenerierter Fall (unendlich viele Lösungen entlang der Linie): bekannte Einschränkung, liefert KEINE Kandidaten statt unendlich vieler", () => { + const l1: TangentTarget = { kind: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }; + const l2: TangentTarget = { kind: "line", a: { x: 0, y: 4 }, b: { x: 10, y: 4 } }; + // Abstand 4 = 2*r bei r=2 → jede x-Position auf y=2 wäre tangential an beide; + // `tangentCircleCenters` schneidet nur Geraden-PAARE (lineIntersect scheitert + // an zusammenfallenden/parallelen Geraden) und liefert hier bewusst nichts, + // statt eine beliebige der unendlich vielen Lösungen zu erraten. + expect(tangentCircleCenters(l1, l2, 2)).toEqual([]); + }); +}); + +describe("tangentCircleCenters — Gerade + Kreis", () => { + it("X-Achse + Kreis (Mittelpunkt (0,6), r=3), Zielradius 2 → Kandidaten in der Lücke, tangential an beide", () => { + // Lücke zwischen Achse und Kreis-Unterkante (y=3) ist 3 — bei Zielradius 2 + // (Durchmesser 4 > Lücke 3) passt ein Kreis, der beide von aussen berührt. + const line: TangentTarget = { kind: "line", a: { x: -10, y: 0 }, b: { x: 10, y: 0 } }; + const circle: TangentTarget = { kind: "circle", center: { x: 0, y: 6 }, r: 3 }; + const cands = tangentCircleCenters(line, circle, 2); + expect(cands.length).toBeGreaterThan(0); + for (const c of cands) { + expect(isTangent(c, 2, line)).toBe(true); + expect(isTangent(c, 2, circle)).toBe(true); + } + // Erwartet (rechnerisch): (±3, 2) — tangential an y=0 (Abstand 2) und an + // den Kreis (Abstand zu (0,6) = sqrt(9+16) = 5 = 3+2). + expect(cands.some((c) => Math.abs(c.x - 3) < 1e-9 && Math.abs(c.y - 2) < 1e-9)).toBe(true); + expect(cands.some((c) => Math.abs(c.x + 3) < 1e-9 && Math.abs(c.y - 2) < 1e-9)).toBe(true); + }); +}); + +describe("tangentCircleCenters — zwei Kreise", () => { + it("zwei getrennte Kreise, Zielradius verbindet beide von aussen (äussere Berührung)", () => { + // Loci-Radien 2+8=10 je Seite, Mittelpunkt-Abstand 16 ≤ 10+10 → lösbar, + // symmetrische Schnittpunkte bei (0, ±6) (10² = 8² + 6²). + const c1: TangentTarget = { kind: "circle", center: { x: -8, y: 0 }, r: 2 }; + const c2: TangentTarget = { kind: "circle", center: { x: 8, y: 0 }, r: 2 }; + const cands = tangentCircleCenters(c1, c2, 8); + expect(cands.length).toBeGreaterThan(0); + for (const c of cands) { + expect(isTangent(c, 8, c1)).toBe(true); + expect(isTangent(c, 8, c2)).toBe(true); + } + // Symmetrische Konfiguration: je ein Kandidat oberhalb/unterhalb der X-Achse bei x≈0. + expect(cands.some((c) => Math.abs(c.x) < 1e-6 && Math.abs(c.y - 6) < 1e-9)).toBe(true); + expect(cands.some((c) => Math.abs(c.x) < 1e-6 && Math.abs(c.y + 6) < 1e-9)).toBe(true); + }); + + it("ein kleiner Kreis INNERHALB eines grossen → innere Berührung liefert Kandidaten", () => { + const outer: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 10 }; + const inner: TangentTarget = { kind: "circle", center: { x: 3, y: 0 }, r: 2 }; + // Zielkreis mit r=4, tangential von innen an `outer` und von aussen an `inner`. + const cands = tangentCircleCenters(outer, inner, 4); + expect(cands.length).toBeGreaterThan(0); + for (const c of cands) { + expect(isTangent(c, 4, outer)).toBe(true); + expect(isTangent(c, 4, inner)).toBe(true); + } + }); + + it("konzentrische Kreise gleichen Radius (innere Loci kollabieren) → keine Endlosschleife, endliches Ergebnis", () => { + const c1: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 5 }; + const c2: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 5 }; + const cands = tangentCircleCenters(c1, c2, 2); + // Konzentrisch → circleCircleIntersect liefert für die äussere Loci-Kombination + // nichts (gleicher Mittelpunkt, `d < EPS`); Funktion muss dennoch sauber terminieren. + expect(Array.isArray(cands)).toBe(true); + }); +}); diff --git a/src/geometry/polylinePoint.test.ts b/src/geometry/polylinePoint.test.ts new file mode 100644 index 0000000..b17e65d --- /dev/null +++ b/src/geometry/polylinePoint.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vitest"; +import { nearestPolylineTarget, toleranceFor } from "./polylinePoint"; + +const L = { + pts: [ + { x: 0, y: 0 }, + { x: 4, y: 0 }, + { x: 4, y: 3 }, + ], + closed: false, +}; + +describe("nearestPolylineTarget", () => { + it("nahe an einem Eckpunkt → Eckpunkt (gewinnt gegen die anliegenden Segmente)", () => { + const hit = nearestPolylineTarget(L, { x: 4.02, y: 0.02 }, 0.5); + expect(hit).toMatchObject({ kind: "vertex", index: 1 }); + }); + + it("mitten auf einem Segment → Segment samt Lotfusspunkt", () => { + const hit = nearestPolylineTarget(L, { x: 2, y: 0.1 }, 0.5); + expect(hit).toMatchObject({ kind: "segment", segIndex: 0 }); + if (hit?.kind === "segment") { + expect(hit.at.x).toBeCloseTo(2, 9); + expect(hit.at.y).toBeCloseTo(0, 9); + } + }); + + it("ausserhalb der Toleranz → null (keine Überraschungs-Aktion im Menü)", () => { + expect(nearestPolylineTarget(L, { x: 2, y: 9 }, 0.5)).toBeNull(); + }); + + it("offene Polylinie hat KEIN Schluss-Segment, geschlossene schon", () => { + const p = { x: 2, y: 1.5 }; + expect(nearestPolylineTarget(L, p, 0.3)).toBeNull(); + const closed = nearestPolylineTarget({ ...L, closed: true }, p, 0.3); + expect(closed).toMatchObject({ kind: "segment", segIndex: 2 }); + }); +}); + +describe("toleranceFor", () => { + it("skaliert mit der Grösse des Elements, mit sinnvoller Untergrenze", () => { + expect(toleranceFor(L)).toBeCloseTo(0.1, 9); // Diagonale 5 m × 2 % + const tiny = { pts: [{ x: 0, y: 0 }, { x: 0.1, y: 0 }], closed: false }; + expect(toleranceFor(tiny)).toBe(0.05); + }); +}); diff --git a/src/geometry/polylinePoint.ts b/src/geometry/polylinePoint.ts new file mode 100644 index 0000000..0afb84e --- /dev/null +++ b/src/geometry/polylinePoint.ts @@ -0,0 +1,79 @@ +// Trefferbestimmung für das Stützpunkt-Kontextmenü einer Polylinie: meint ein +// Klick einen vorhandenen ECKPUNKT (→ löschen) oder ein SEGMENT (→ Punkt +// einfügen)? Rein geometrisch, ohne Zoom-/Pixelbezug — der Toleranzradius +// kommt vom Aufrufer (s. `toleranceFor`), damit dieselbe Logik auch in Tests +// ohne Ansicht nutzbar bleibt. +// +// Bogen-Segmente (`bulge`) werden bewusst über ihre SEHNE gemessen: für die +// Frage „welches Segment ist gemeint" reicht das, und der eingefügte Punkt +// landet ohnehin exakt auf dem Bogen (s. `projectSlice.insertDrawingPoint`). + +import type { Vec2 } from "../model/types"; + +export type PolylineTarget = + | { kind: "vertex"; index: number; dist: number } + | { kind: "segment"; segIndex: number; at: Vec2; dist: number }; + +interface PolylineGeom { + pts: Vec2[]; + closed: boolean; +} + +/** Lotfusspunkt von `p` auf die Strecke a→b (auf die Strecke geklemmt). */ +function projectOnSegment(a: Vec2, b: Vec2, p: Vec2): { at: Vec2; dist: number } { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + const t = len2 < 1e-12 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)); + const at = { x: a.x + dx * t, y: a.y + dy * t }; + return { at, dist: Math.hypot(p.x - at.x, p.y - at.y) }; +} + +/** + * Toleranz in Modell-Metern, abgeleitet aus der Ausdehnung der Polylinie + * selbst (2 % der Bounding-Box-Diagonale, mindestens 5 cm) — dadurch + * zoom-unabhängig und bei kleinen wie grossen Elementen brauchbar, ohne dass + * das Kontextmenü den Massstab der Ansicht kennen muss. + */ +export function toleranceFor(g: PolylineGeom): number { + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (const p of g.pts) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + if (!Number.isFinite(minX)) return 0.05; + return Math.max(0.05, Math.hypot(maxX - minX, maxY - minY) * 0.02); +} + +/** + * Nächstes Ziel zum Klickpunkt `p`, oder `null`, wenn nichts innerhalb + * `maxDist` liegt. Ein Eckpunkt gewinnt gegen ein Segment, sobald er + * innerhalb der Toleranz liegt — sonst liesse sich ein Punkt, der ja immer + * auch auf zwei Segmenten liegt, nie zuverlässig treffen. + */ +export function nearestPolylineTarget( + g: PolylineGeom, + p: Vec2, + maxDist: number, +): PolylineTarget | null { + let best: PolylineTarget | null = null; + g.pts.forEach((v, index) => { + const dist = Math.hypot(p.x - v.x, p.y - v.y); + if (dist <= maxDist && (!best || dist < best.dist)) best = { kind: "vertex", index, dist }; + }); + if (best) return best; + + const n = g.pts.length; + const segCount = g.closed && n > 2 ? n : n - 1; + for (let i = 0; i < segCount; i++) { + const a = g.pts[i]; + const b = g.pts[(i + 1) % n]; + const { at, dist } = projectOnSegment(a, b, p); + if (dist <= maxDist && (!best || dist < best.dist)) { + best = { kind: "segment", segIndex: i, at, dist }; + } + } + return best; +} diff --git a/src/geometry/revisionCloud.test.ts b/src/geometry/revisionCloud.test.ts new file mode 100644 index 0000000..f5d70d1 --- /dev/null +++ b/src/geometry/revisionCloud.test.ts @@ -0,0 +1,67 @@ +/** + * `revisionCloudPts` — wandelt eine geklickte Punktfolge in eine + * Beulen-Kontur (Revisionswolke) um. + */ +import { describe, it, expect } from "vitest"; +import { revisionCloudPts, REVCLOUD_BULGE } from "./revisionCloud"; +import { bulgeArcPoints } from "./bulge"; +import type { Vec2 } from "../model/types"; + +describe("revisionCloudPts", () => { + it("liefert null bei < 2 Punkten", () => { + expect(revisionCloudPts([{ x: 0, y: 0 }], false, 0.3)).toBeNull(); + }); + + it("ein einzelnes offenes Segment wird in ~len/targetArcLen Beulen zerlegt", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 3, y: 0 }]; + const res = revisionCloudPts(pts, false, 0.5)!; + expect(res).not.toBeNull(); + // 3m Länge / 0.5m Ziel-Bogenlänge ≈ 6 Beulen. + expect(res.bulge.length).toBe(6); + expect(res.bulge.every((b) => b === REVCLOUD_BULGE)).toBe(true); + // Erster und letzter Punkt der expandierten Kontur = Start/Ende der Eingabe. + expect(res.pts[0]).toEqual({ x: 0, y: 0 }); + expect(res.pts[res.pts.length - 1]).toEqual({ x: 3, y: 0 }); + }); + + it("mehrere Segmente werden nahtlos aneinandergehängt (keine doppelten Zwischenpunkte)", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }]; + const res = revisionCloudPts(pts, false, 1)!; + // Der mittlere Eingabepunkt (2,0) muss GENAU EINMAL in der expandierten + // Kontur vorkommen (nicht doppelt vom Ende des ersten UND Anfang des + // zweiten Segments). + const occurrences = res.pts.filter((p) => p.x === 2 && p.y === 0).length; + expect(occurrences).toBe(1); + }); + + it("geschlossene Kontur: kein doppelter Schlusspunkt", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]; + const res = revisionCloudPts(pts, true, 1)!; + // Der letzte Punkt der expandierten Kontur darf NICHT (0,0) sein (das + // wäre der Startpunkt erneut) — der Ring schliesst sich implizit über + // die geschlossene Interpretation, nicht über einen doppelten Punkt. + const last = res.pts[res.pts.length - 1]; + expect(last).not.toEqual({ x: 0, y: 0 }); + // Bulge-Array hat genau so viele Einträge wie Punkte (Schluss-Segment + // pts[last]→pts[0] eingerechnet, wie bei jeder geschlossenen Polylinie). + expect(res.bulge.length).toBe(res.pts.length); + }); + + it("jede Beule liegt exakt auf einem Kreisbogen mit dem erwarteten bulge (Rückwärtsprobe)", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }]; + const res = revisionCloudPts(pts, false, 1)!; + // Genau 2 Beulen bei 2m/1m Ziel-Länge. + expect(res.pts.length).toBe(3); // Start + 2 Zwischenpunkte + for (let i = 0; i < res.pts.length - 1; i++) { + const arcPts = bulgeArcPoints(res.pts[i], res.pts[i + 1], res.bulge[i]); + // Ein echter Bogen (bulge≠0) tesselliert zu MEHR als 2 Punkten. + expect(arcPts.length).toBeGreaterThan(2); + } + }); + + it("sehr kurzes Segment (kürzer als die Ziel-Bogenlänge) ergibt genau EINE Beule", () => { + const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 0.1, y: 0 }]; + const res = revisionCloudPts(pts, false, 1)!; + expect(res.bulge.length).toBe(1); + }); +}); diff --git a/src/geometry/revisionCloud.ts b/src/geometry/revisionCloud.ts new file mode 100644 index 0000000..9d1c35e --- /dev/null +++ b/src/geometry/revisionCloud.ts @@ -0,0 +1,83 @@ +// Revisionswolke (Nutzer-Wunsch: „Keine Revisionswolken/Markup-Werkzeuge") — +// wandelt eine geklickte (Polylinien-artige) Punktfolge in eine „ausgebeulte" +// Kontur um: jedes gerade Segment zwischen zwei aufeinanderfolgenden Punkten +// wird in mehrere gleich lange Teilstücke zerlegt, die JEWEILS als +// Kreisbogen („Beule") statt als Gerade gezeichnet werden — die klassische +// CAD-Revisionswolke. +// +// Bewusst KEIN neuer Shape-Typ: das Ergebnis ist eine ganz normale +// `Drawing2DGeom["polyline"]` mit `bulge` (DXF-Konvention, s. `bulge.ts`) — +// erbt dadurch Rendering/Snapping/Griffe/Export/Transformieren komplett vom +// bereits vorhandenen Polylinien-Pfad, exakt wie bei `polygon.ts`/den +// gerundeten Ecken von `rect.ts`. +// +// Alle Beulen bulgen in die GLEICHE Richtung relativ zur jeweiligen +// Segment-Zeichenrichtung (positives `bulge` = links von a→b, s. bulge.ts) — +// bei einem GEGEN den Uhrzeigersinn geklickten geschlossenen Zug zeigen sie +// dadurch nach AUSSEN (die übliche Optik). Die Umlaufrichtung wird bewusst +// NICHT automatisch erkannt/korrigiert (eigener, grösserer Scope) — zeichnet +// der Nutzer im Uhrzeigersinn, zeigen die Beulen nach innen; einfach in der +// anderen Richtung klicken behebt das. + +import type { Vec2 } from "../model/types"; + +const EPS = 1e-9; + +/** + * `bulge`-Wert EINER Beule — `tan(Δ/4)` für einen Öffnungswinkel Δ ≈ 100° + * (Δ = 4·atan(0.42)): sichtbar, aber nicht übertrieben rund — der übliche + * REVCLOUD-Look. + */ +export const REVCLOUD_BULGE = 0.42; + +const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); +const lerp = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }); + +/** + * Zerlegt EIN gerades Segment a→b in `n` gleich lange Beulen (Ziel-Bogenlänge + * `targetArcLen`, mindestens 1 Beule). Liefert die neuen Zwischenpunkte OHNE + * den Startpunkt `a` (der gehört dem Aufrufer/vorherigen Segment) UND die + * `n` Bulge-Werte für die `n` neuen Teilsegmente. + */ +function expandSegment(a: Vec2, b: Vec2, targetArcLen: number): { pts: Vec2[]; bulge: number[] } { + const len = dist(a, b); + if (len < EPS) return { pts: [], bulge: [] }; + const n = Math.max(1, Math.round(len / Math.max(targetArcLen, EPS))); + const pts: Vec2[] = []; + const bulge: number[] = []; + for (let i = 1; i <= n; i++) { + pts.push(lerp(a, b, i / n)); + bulge.push(REVCLOUD_BULGE); + } + return { pts, bulge }; +} + +/** + * Wandelt eine geklickte Punktfolge (offen ODER geschlossen) in die volle + * Revisionswolken-Kontur um: alle geraden Segmente (inkl. Schluss-Segment bei + * `closed`) werden zu Beulen-Ketten der Ziel-Bogenlänge `targetArcLen` + * expandiert. Liefert `null` bei < 2 Punkten (nichts zu zeichnen). + */ +export function revisionCloudPts( + points: Vec2[], + closed: boolean, + targetArcLen: number, +): { pts: Vec2[]; bulge: number[] } | null { + if (points.length < 2) return null; + const segCount = closed ? points.length : points.length - 1; + const outPts: Vec2[] = [points[0]]; + const outBulge: number[] = []; + for (let s = 0; s < segCount; s++) { + const a = points[s]; + const b = points[(s + 1) % points.length]; + const { pts, bulge } = expandSegment(a, b, targetArcLen); + outPts.push(...pts); + outBulge.push(...bulge); + } + // Geschlossen: das letzte expandierte Segment endet exakt am Startpunkt + // (points[0]) — der doppelte Schlusspunkt fällt weg (der Ring schliesst + // sich implizit über `closed:true`, wie bei jeder anderen Polylinie). + if (closed) outPts.pop(); + if (outPts.length < 2) return null; + return { pts: outPts, bulge: outBulge }; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 03eb2b1..65cb529 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -178,6 +178,8 @@ export const de = { "tool.line": "Linie", "tool.xline": "Konstruktionslinie", "tool.xline.hint": "Konstruktionslinie: zwei Punkte legen die Richtung fest (unendlich verlängert)", + "tool.ray": "Strahl", + "tool.ray.hint": "Strahl: Anker setzen, dann Richtungspunkt (nur einseitig unendlich verlängert)", "tool.block": "Block einfügen", "tool.block.hint": "Block einfügen: aktive Definition per Option wählen, dann Einfügepunkt klicken", "tool.polyline": "Polylinie", @@ -198,6 +200,16 @@ export const de = { "tool.dimension.hint": "Bemassung: Punkte wie Polylinie klicken (ab Punkt 3 auf einer Geraden), Doppelklick/Enter beendet, dann Lage der Masslinie (Massketten in einer Geste)", "tool.kote": "Höhenkote", "tool.kote.hint": "Höhenkote: Punkt setzen, dann Höhenwert eintippen (Art umschaltbar: OK/UK, fertig/roh)", + "tool.detailref": "Detail-/Schnitt-Verweis", + "tool.detailref.hint": "Detail-/Schnitt-Verweis: Punkt setzen — Bezeichner/Blattverknüpfung danach im Attribute-Panel", + "tool.scalebar": "Massstabsbalken", + "tool.scalebar.hint": "Massstabsbalken: Punkt setzen (linke untere Ecke) — Segmentlänge/-anzahl per Option", + "tool.revcloud": "Revisionswolke", + "tool.revcloud.hint": "Revisionswolke: Punkte wie Polylinie klicken, Enter beendet offen, Klick nahe Start oder \"Schliessen\" schliesst", + "tool.pointmarker": "Punktmarker", + "tool.pointmarker.hint": "Punktmarker: Punkt setzen — Kreuz-in-Kreis-Symbol markiert einen Referenzpunkt", + "tool.wipeout": "Maskenregion", + "tool.wipeout.hint": "Maskenregion: Punkte wie Polylinie klicken, Klick nahe Start oder Enter (ab 3 Punkten) schliesst und deckt darunterliegende Zeichnung ab", "tool.text": "Text", "tool.text.hint": "Text: Ankerpunkt setzen, dann Text eintippen", "tool.leader": "Vorführungspfeil", @@ -262,10 +274,14 @@ export const de = { "snap.center": "Kreismitte/Quadranten (0/90/180/270°)", "snap.intersection": "Schnittpunkt", "snap.onEdge": "Auf Kante (Lot)", + "snap.perpendicular": "Senkrecht zum letzten Punkt", + "snap.tangent": "Tangential an Kreis/Bogen", + "snap.parallel": "Parallel zu Referenz (kurz auf Linie verweilen)", "snap.grid": "Raster", "snap.ortho": "Ortho (Shift)", "snap.gridSize": "Rasterweite (m)", - "snap.angleStep": "Winkelraster", + "snap.showGrid": "Raster anzeigen", + "snap.angleStep": "Winkelraster (°)", "snap.commonAngles": "Gängige Winkel", "snap.commonAngleTolerance": "Winkeltoleranz (°)", "snap.hoverDivideDelayMs": "Hover-Verzögerung (ms)", @@ -343,6 +359,32 @@ export const de = { "attr.grayscale": "Graustufen", "attr.lineStyle": "Linienstil", "attr.lineStyle.none": "Standard", + "attr.dashScale": "Strichmuster-Massstab", + "attr.hatch.angle": "Schraffur-Winkel", + "attr.hatch.scale": "Schraffur-Massstab", + "attr.hatch.origin": "Schraffur-Ursprung", + "attr.hatch.fromStyle": "aus Stil", + "attr.hatch.origin.corner": "an Ecke setzen", + "attr.hatch.origin.reset": "zurücksetzen", + "attr.hatch.origin.hint": "Setzt das Musterraster auf die untere linke Ecke dieses Objekts (statt auf den Modellursprung).", + "attr.ends.section": "Linienenden", + "attr.ends.start": "Anfang", + "attr.ends.end": "Ende", + "attr.ends.size": "Grösse (mm)", + "attr.ends.none": "keines", + "attr.ends.arrow": "Pfeil", + "attr.ends.arrowOpen": "Pfeil offen", + "attr.ends.dot": "Punkt", + "attr.ends.tick": "Schrägstrich", + "attr.ends.square": "Quadrat", + "attr.dim.section": "Bemassung", + "attr.dim.gap": "Abstand Hilfslinie (mm)", + "attr.dim.overshoot": "Überstand (mm)", + "attr.dim.tick": "Massstrich-Länge (mm)", + "attr.dim.textHeight": "Schrifthöhe (mm)", + "attr.dim.lineWeight": "Masslinie (mm)", + "attr.dim.extWeight": "Hilfslinie (mm)", + "attr.dim.tickWeight": "Massstrich (mm)", "attr.fill": "Füllung", "attr.fillColor": "Füllfarbe", "attr.clearFill": "Füllfarbe entfernen", @@ -587,6 +629,8 @@ export const de = { "objinfo.opening.lintelLines.innen": "Innen", "objinfo.opening.lintelLines.aussen": "Außen", "objinfo.opening.lintelLines.beide": "Beide", + "objinfo.opening.detailLevel": "Detailstufe", + "objinfo.detailLevel.view": "Ansicht (Standard)", "objinfo.opening.frameLine": "Rahmen (Schnitt)", "objinfo.opening.frameViewLine": "Rahmen (Aufsicht)", "objinfo.opening.sashLine": "Fenster (Flügel/Sprossen)", @@ -627,6 +671,12 @@ export const de = { "objinfo.room.editStamp": "Stempel bearbeiten …", // ── Extrusions-Attribute (truck-Integration, Object-Info-Panel) ───────── "objinfo.sectionLine.section": "Schnittlinie", + "objinfo.detailRef.section": "Detail-/Schnitt-Verweis", + "objinfo.detailRef.label": "Bezeichner", + "objinfo.detailRef.sheet": "Blatt", + "objinfo.detailRef.sheet.none": "Kein Verweis", + "objinfo.detailRef.sheetLabel": "Blattname (manuell)", + "objinfo.detailRef.sheetLabel.hint": "z. B. \"A-102\"", "objinfo.sectionLine.kind.section": "Schnitt", "objinfo.sectionLine.kind.elevation": "Ansicht", "objinfo.sectionLine.name": "Name", @@ -647,7 +697,10 @@ export const de = { "objinfo.extrudedSolid.floor": "Geschoss", "objinfo.rotate": "Drehen", "objinfo.drawing.length": "Länge", + "objinfo.drawing.angle": "Winkel", "objinfo.drawing.radius": "Radius", + "objinfo.drawing.startAngle": "Startwinkel", + "objinfo.drawing.endAngle": "Endwinkel", "objinfo.wall.floorAboveNone": "Kein oberes Geschoss", "levels.addFloor": "+ Geschoss", "levels.addSection": "+ Schnitt", @@ -703,6 +756,12 @@ export const de = { "ctx.copyProps": "Eigenschaften kopieren", "ctx.pasteProps": "Eigenschaften einfügen", "ctx.pasteProps.disabled": "Zwischenablage leer — zuerst „Eigenschaften kopieren“.", + "ctx.lock": "Sperren", + "ctx.unlock": "Entsperren", + "ctx.noPrint": "Nicht drucken", + "ctx.print": "Drucken", + "ctx.insertPoint": "Punkt einfügen", + "ctx.deletePoint": "Punkt löschen", "ctx.delete": "Löschen", "ctx.delete.lastLayer": "Die letzte Ebene kann nicht gelöscht werden.", "ctx.delete.lastLevel": "Die letzte Zeichnungsebene kann nicht gelöscht werden.", @@ -777,6 +836,7 @@ export const de = { "default.componentName": "Neues Bauteil", "default.hatchName": "Neue Schraffur", "default.lineStyleName": "Neuer Linienstil", + "default.textStyleName": "Neuer Textstil", "default.hatchNone": "Ohne", "default.copySuffixLevel": "{name} Kopie", "default.copySuffixLayer": "{name} KOPIE", @@ -790,9 +850,11 @@ export const de = { "default.stairTypeName": "Neuer Treppentyp", "default.penName": "Neuer Stift", "default.penSetName": "Neuer Stiftsatz", + "default.customPaletteName": "Meine Farben", // ── Warnungen (Lösch-Schutz) ───────────────────────────────────────────── "alert.layerInUse": "Ebene „{code} {name}\" wird von Bauteilen verwendet und kann nicht gelöscht werden.", + "alert.polylineMinPoints": "Zu wenige Punkte — eine Polylinie braucht mindestens zwei, eine geschlossene drei.", "alert.penSetIsActive": "Stiftsatz „{name}\" ist aktiv und kann nicht gelöscht werden — zuerst einen anderen Stiftsatz aktivieren.", "alert.componentInUse": "Bauteil „{name}\" wird von einem Wandtyp verwendet und kann nicht gelöscht werden.", "alert.hatchInUse": "Schraffur „{name}\" wird von einem Bauteil verwendet und kann nicht gelöscht werden.", @@ -836,6 +898,18 @@ export const de = { "resources.pens.seedStandard.hint": "Ersetzt die Stift-Liste durch 255 prozedural erzeugte Stifte (klassische CAD-Nummerierung: 1-9 Grundfarben, 10-249 Farbtonstufen, 250-255 Graukeil) + einen neuen aktiven Stiftsatz mit diesen Farben.", "resources.delete.penSet": "Stiftsatz „{name}\" löschen", "resources.delete.pen": "Stift „{name}\" löschen", + "resources.tab.palettes": "Paletten", + "resources.palettes.hint": "Legt fest, welche Farbpaletten im Farbfeld erscheinen. Eigene Paletten füllst du direkt im Farbfeld über die „+\"-Zelle.", + "resources.palettes.builtin": "Mitgelieferte Paletten", + "resources.palettes.custom": "Eigene Paletten", + "resources.palettes.countHint": "{count} Farben", + "resources.palettes.add": "Palette", + "resources.palettes.empty": "Noch keine eigene Palette.", + "resources.palettes.placeholder": "Palettenname", + "resources.palettes.visible": "Im Farbfeld zeigen", + "resources.palettes.visible.hint": "Ausgeblendete Paletten bleiben erhalten, erscheinen aber nicht in der Bank-Leiste des Farbfelds.", + "resources.palettes.noColors": "Noch keine Farben in dieser Palette.", + "resources.delete.customPalette": "Palette „{name}\" löschen", // Grafische Overrides (Regel-Engine). "resources.overrides.hint": @@ -898,6 +972,8 @@ export const de = { "resources.field.leafCount": "Flügelzahl", "resources.field.leafStyle": "Blattausführung", "resources.field.glazingRatio": "Glasanteil", + "resources.field.panelCols": "Kassetten horizontal", + "resources.field.panelRows": "Kassetten vertikal", "resources.field.frameThickness": "Zargenstärke (m)", "resources.field.frameDepth": "Zargentiefe (m)", "resources.field.defaultWidth": "Lichtbreite (m)", @@ -1009,6 +1085,16 @@ export const de = { "pen.weightHint": "Stärke: {weight} mm", "pen.customColor": "Andere Farbe …", "pen.hexHint": "Hex-Farbwert (#rrggbb)", + "pen.paletteSimple": "Einfach", + "pen.ralHint": "RAL Classic — Näherungswerte für den Bildschirm, nicht farbverbindlich. Für Ausschreibung/Bemusterung gilt die offizielle RAL-Karte.", + "colorMixer.spectrum": "Spektrum", + "colorMixer.cmykHint": "Vereinfachte Bildschirm-Umrechnung ohne Druck-Farbmanagement (ICC-Profil).", + "colorMixer.cmykHintIcc": "Echtes ICC-Farbmanagement (macOS ColorSync, Generic CMYK Profile) — relative farbmetrische Wiedergabe.", + "pen.paletteCustom": "Eigene", + "pen.newPalette": "Neue Palette", + "pen.saveColor": "Diese Farbe speichern", + "pen.removeColor": "Aus Palette entfernen", + "pen.customEmpty": "Noch keine Farben — mit „Diese Farbe speichern\" die aktuelle Mischer-Farbe ablegen.", // 3D-Material (PBR) — Bibliotheks-Auswahl + Upload. "material.assign": "Material …", @@ -1096,6 +1182,12 @@ export const de = { "resources.seg.addGap": "+ Lücke", "resources.hatchKind.vector": "Vektor", "resources.hatchKind.image": "Bild", + "resources.hatchKind.gradient": "Verlauf", + "resources.field.gradientType": "Verlauf-Art", + "resources.field.gradientColor1": "Farbe 1", + "resources.field.gradientColor2": "Farbe 2", + "resources.gradientType.linear": "Linear", + "resources.gradientType.radial": "Radial", "resources.lines.parallel": "Parallel", "resources.lines.random": "Zufällig", "resources.lineKind.dash": "Strich", @@ -1123,6 +1215,20 @@ export const de = { "resources.delete.lineStyle": "Linienstil „{name}\" löschen", "resources.texture.empty": "—", + // Textstile. + "resources.tab.textStyles": "Textstile", + "resources.textStyles.hint": "Benannte Formatierungs-Vorlagen (Schrift/Grösse/fett/kursiv/unterstrichen/Farbe) — über die Text-Formatier-Gruppe der Oberleiste auf eine Auswahl anwendbar. Anwenden kopiert die Werte einmalig (keine laufende Kopplung).", + "resources.textStyles.empty": "Noch keine Textstile.", + "resources.textStyles.placeholder": "Textstil", + "resources.textStyles.previewText": "Beispieltext Aa", + "resources.textStyles.defaultFont": "Standard", + "resources.delete.textStyle": "Textstil „{name}\" löschen", + "resources.field.font": "Schriftart", + "resources.field.size": "Grösse (pt)", + "resources.field.bold": "Fett", + "resources.field.italic": "Kursiv", + "resources.field.underline": "Unterstrichen", + // Strichmuster. "dash.solid": "Durchgezogen", "dash.dashed": "Gestrichelt", @@ -1183,12 +1289,16 @@ export const de = { "cmd.stair.auftrittField": "Auftritt", "cmd.line.label": "Linie", "cmd.line.start": "Startpunkt der Linie:", - "cmd.line.end": "Endpunkt der Linie:", + "cmd.line.end": "Endpunkt (Enter beendet die Kette):", "cmd.xline.label": "Konstruktionslinie", "cmd.xline.start": "Startpunkt:", "cmd.xline.end": "Richtungspunkt:", + "cmd.ray.label": "Strahl", + "cmd.ray.start": "Anker:", + "cmd.ray.end": "Richtungspunkt:", "cmd.block.label": "Block einfügen", "cmd.block.point": "Einfügepunkt:", + "cmd.block.rotate": "Drehwinkel + Grösse (Abstand = Faktor; Klick auf denselben Punkt = 0°/1×):", "cmd.block.def": "Symbol", "cmd.defblock.label": "Block definieren", "cmd.defblock.base": "Basispunkt:", @@ -1197,32 +1307,63 @@ export const de = { "cmd.polyline.next": "Nächster Punkt:", "cmd.polyline.close": "Schliessen", "cmd.polyline.undo": "Zurück", + "cmd.polyline.tangentOpt": "Tangential", + "cmd.polyline.arcThrough": "Durchgangspunkt:", + "cmd.polyline.arcOpt": "Bogen", "cmd.polyline.closedOpt": "Geschlossen", "cmd.rect.label": "Rechteck", "cmd.rect.first": "Erste Ecke:", "cmd.rect.second": "Gegenüberliegende Ecke:", "cmd.rect.method": "Methode", + "cmd.rect.radius": "Eck-Radius", "cmd.rect.center": "Mittelpunkt:", "cmd.rect.corner": "Ecke:", "cmd.rect.baseEnd": "Zweite Ecke (Basiskante):", "cmd.rect.rise": "Höhe:", "cmd.circle.label": "Kreis", + "cmd.circle.method": "Methode", "cmd.circle.center": "Mittelpunkt:", "cmd.circle.radius": "Radius:", + "cmd.circle.diameterStart": "Erster Punkt (Durchmesser):", + "cmd.circle.diameterEnd": "Zweiter Punkt (Durchmesser):", + "cmd.circle.threeFirst": "Erster Punkt:", + "cmd.circle.ttrFirst": "Erstes Tangentenobjekt wählen (Linie/Kreis):", + "cmd.circle.ttrSecond": "Zweites Tangentenobjekt wählen (Linie/Kreis):", + "cmd.circle.threeSecond": "Zweiter Punkt:", + "cmd.circle.threeThird": "Dritter Punkt:", "cmd.arc.label": "Bogen", + "cmd.arc.method": "Methode", "cmd.arc.center": "Mittelpunkt:", "cmd.arc.start": "Startpunkt (Radius + Startwinkel):", "cmd.arc.end": "Endpunkt (Endwinkel):", + "cmd.arc.threeStart": "Startpunkt:", + "cmd.arc.through": "Durchgangspunkt:", + "cmd.arc.threeEnd": "Endpunkt:", + "cmd.arc.serStart": "Startpunkt:", + "cmd.arc.serEnd": "Endpunkt:", + "cmd.arc.radius": "Radius:", + "cmd.arc.sedStart": "Startpunkt:", + "cmd.arc.sedEnd": "Endpunkt:", + "cmd.arc.direction": "Richtung (Tangente bei Start):", "cmd.ellipse.label": "Ellipse", + "cmd.ellipse.method": "Methode", "cmd.ellipse.corner1": "Erste Ecke:", "cmd.ellipse.corner2": "Gegenüberliegende Ecke:", + "cmd.ellipse.axisCenter": "Zentrum:", + "cmd.ellipse.major": "Hauptachse:", + "cmd.ellipse.minor": "Nebenachse:", "cmd.polygon.label": "Vieleck", "cmd.polygon.center": "Mittelpunkt:", "cmd.polygon.radius": "Radius:", "cmd.polygon.sides": "Ecken", + "cmd.polygon.mode": "Modus", + "cmd.polygon.construct": "Konstruktion", + "cmd.polygon.edgeStart": "Erster Kantenpunkt:", + "cmd.polygon.edgeEnd": "Zweiter Kantenpunkt:", "cmd.spline.label": "Spline", "cmd.spline.start": "Startpunkt:", "cmd.spline.next": "Nächster Punkt ( Schliessen Zurück ):", + "cmd.spline.curveMode": "Modus", "cmd.bezier.label": "Bezier", "cmd.bezier.start": "Startpunkt:", "cmd.bezier.c1": "Griff 1:", @@ -1237,6 +1378,22 @@ export const de = { "cmd.dimension.finish": "Fertig", "cmd.kote.label": "Höhenkote", "cmd.kote.point": "Punkt:", + "cmd.detailref.label": "Detail-/Schnitt-Verweis", + "cmd.detailref.point": "Punkt:", + "cmd.scalebar.label": "Massstabsbalken", + "cmd.scalebar.point": "Punkt (linke untere Ecke):", + "cmd.scalebar.length": "Segmentlänge", + "cmd.scalebar.segments": "Segmente", + "cmd.revcloud.label": "Revisionswolke", + "cmd.revcloud.start": "Startpunkt:", + "cmd.revcloud.next": "Nächster Punkt ( Schliessen ):", + "cmd.revcloud.close": "Schliessen", + "cmd.revcloud.arcSize": "Beulengrösse", + "cmd.pointmarker.label": "Punktmarker", + "cmd.pointmarker.point": "Punkt:", + "cmd.wipeout.label": "Maskenregion", + "cmd.wipeout.start": "Startpunkt:", + "cmd.wipeout.next": "Nächster Punkt:", "cmd.kote.value": "Höhenwert ( Art ):", "cmd.kote.kind.okFertig": "OK fertig", "cmd.kote.kind.ukFertig": "UK fertig", @@ -1246,7 +1403,9 @@ export const de = { "cmd.text.label": "Text", "cmd.text.point": "Ankerpunkt:", "cmd.leader.label": "Vorführungspfeil", + "cmd.leader.bends": "Knicke", "cmd.leader.target": "Zielpunkt:", + "cmd.leader.bend": "Knickpunkt:", "cmd.leader.anchor": "Textanker:", "cmd.textpath.label": "Text entlang Pfad", "cmd.textpath.start": "Pfadpunkt:", @@ -1271,6 +1430,26 @@ export const de = { "objinfo.measure.angle": "Winkel", "objinfo.measure.hint": "Klick = Punkt · Rechtsklick = neuer Pfad · Esc = Ende", "transform.needSelection": "Erst Objekte wählen, dann drehen.", + "cmd.align.label": "Ausrichten", + "cmd.align.prompt": "Kante bzw. Achse wählen:", + "cmd.align.left": "links", + "cmd.align.centerX": "zentriert", + "cmd.align.right": "rechts", + "cmd.align.top": "oben", + "cmd.align.centerY": "mittig", + "cmd.align.bottom": "unten", + "cmd.align.distX": "waagrecht verteilen", + "cmd.align.distY": "senkrecht verteilen", + "cmd.explode.label": "Auflösen", + "cmd.scale.label": "Skalieren", + "cmd.scale.base": "Basispunkt:", + "cmd.scale.factor": "Faktor oder Referenzlänge (Punkt):", + "cmd.scale.target": "Neue Länge:", + "cmd.scale.empty": "Nichts gewählt (erst Objekte wählen).", + "cmd.rotate.base": "Drehpunkt:", + "cmd.rotate.angle": "Winkel (Grad) oder Referenzpunkt:", + "cmd.rotate.target": "Neue Richtung:", + "cmd.rotate.empty": "Nichts gewählt (erst Objekte wählen).", "cmd.mirror.label": "Spiegeln", "cmd.mirror.first": "Erster Punkt der Spiegelachse:", "cmd.mirror.second": "Zweiter Punkt der Spiegelachse:", @@ -1281,8 +1460,11 @@ export const de = { "cmd.copy.target": "Zielpunkt (Enter beendet):", "cmd.copy.empty": "Nichts gewählt (erst Objekte wählen).", "cmd.array.label": "Feld", + "cmd.array.kind": "Art", "cmd.array.base": "Basispunkt:", "cmd.array.target": "Zielpunkt ( Anzahl ):", + "cmd.array.center": "Zentrum:", + "cmd.array.polarAngle": "Winkel je Kopie ( Anzahl ):", "cmd.array.count": "Anzahl", "cmd.offset.label": "Versatz", "cmd.offset.pick": "Kurve wählen:", @@ -1294,6 +1476,9 @@ export const de = { // Trim (Quick-Trim): auf den wegzuschneidenden Abschnitt klicken; wiederholend. "cmd.trim.label": "Stutzen", "cmd.trim.pick": "Abschnitt zum Wegschneiden anklicken (Esc beendet):", + "cmd.break.label": "Unterbrechen", + "cmd.break.p1": "Erster Punkt (auf einer Linie/offenen Polylinie):", + "cmd.break.p2": "Zweiter Punkt:", // Extend: Gegenstück zu Trim — verlängert eine offene Kurve bis zur nächsten anderen Kurve. "cmd.extend.label": "Verlängern", "cmd.extend.pick": "Kurve nahe dem zu verlängernden Ende anklicken (Esc beendet):", @@ -1394,6 +1579,9 @@ export const de = { "import.dwg.loading": "DWG wird gelesen …", "import.dwg.hint": "DWG konnte nicht gelesen werden. Wandle die Datei alternativ mit dem gratis ODA File Converter in DXF um und importiere die DXF-Datei.", + "import.loading.heading": "DXF-Datei", + "import.loading.hint": + "DXF wird gelesen … Bei sehr grossen Dateien (z. B. ein Kataster-Import einer ganzen Stadt) kann das einen Moment dauern.", "import.confirm": "Importieren", "import.cancel": "Abbrechen", "import.badge.floor": "Geschoss", @@ -1402,7 +1590,9 @@ export const de = { "import.badge.drawing": "Zeichnung", // ── PDF-Export ─────────────────────────────────────────────────────────── - "export.title": "PDF exportieren", + "export.title": "PDF/SVG exportieren", + "export.confirmSvg": "Als SVG", + "export.confirmPdf": "Als PDF", "export.close": "Schließen", "export.plan": "Plan", "export.scale": "Massstab", @@ -1410,6 +1600,8 @@ export const de = { "export.orientation": "Ausrichtung", "export.orientation.portrait": "Hochformat", "export.orientation.landscape": "Querformat", + "export.scale.customPlaceholder": "Freitext (z. B. 1:75 oder 75)", + "export.selectionOnly": "Nur Auswahl exportieren ({count} Element(e))", "export.warnFit": "Der Plan passt im gewählten Massstab nicht ganz auf das Blatt — größeres Format oder kleineren Massstab wählen.", "export.confirm": "Exportieren", @@ -1449,6 +1641,13 @@ export const de = { "lock.forceOpen": "Trotzdem erzwingen", "lock.forceOpenWarning": "Achtung: Öffnet zum Schreiben, obwohl eine andere Instanz die Datei hält — Änderungen können sich gegenseitig überschreiben.", + + // ── Ungespeicherte Änderungen (Neu/Öffnen würde sie verwerfen) ────────── + "unsaved.title": "Ungespeicherte Änderungen", + "unsaved.message": + "Das aktuelle Projekt hat ungespeicherte Änderungen. Vor dem Fortfahren speichern?", + "unsaved.save": "Speichern", + "unsaved.discard": "Nicht speichern", "exportSave.title": "Exportieren", "exportSave.format": "Format", "exportSave.filename": "Dateiname", @@ -1480,6 +1679,9 @@ export const de = { "topbar.settings": "Einstellungen", "topbar.settings.hint": "Einstellungen öffnen (Darstellungsfarben, Projekt)", "settings.title": "Einstellungen", + "settings.tab.general": "Allgemein", + "settings.tab.shortcuts": "Tastenkürzel", + "settings.tab.update": "Update", "settings.section.workspace": "Arbeitsumgebung", "settings.section.display": "Darstellung", "settings.theme": "Erscheinungsbild", @@ -1495,6 +1697,61 @@ export const de = { "settings.referenceElevation": "Referenzhöhe EG (m ü. M.)", "settings.referenceElevation.hint": "Nur gespeichert — wird noch nicht verwendet. Folgt für Terrain-Draping/reale Höhen relativ zum Erdgeschoss.", + "settings.section.shortcuts": "Befehlszeilen-Kürzel (Tipp-Alias)", + "settings.shortcuts.hint": + "Eigene Kürzel für die Befehlszeile — ein eigenes Kürzel überschreibt (nur für dich) ein eingebautes mit demselben Buchstaben, falls es eins gibt.", + "settings.shortcuts.remove": "Entfernen", + "settings.shortcuts.newKey": "Kürzel", + "settings.shortcuts.pickCommand": "Befehl wählen…", + "settings.shortcuts.add": "Hinzufügen", + + "settings.section.keyboardShortcuts": "Tastenkombinationen", + "settings.keyboardShortcuts.hint": + "Echte Tastenkombinationen (Ctrl/Cmd+…) für die wichtigsten Aktionen — frei umbelegbar. Zum Ändern auf »Ändern« klicken und die neue Kombination drücken.", + "settings.keyboardShortcuts.change": "Ändern", + "settings.keyboardShortcuts.reset": "Zurücksetzen", + "settings.keyboardShortcuts.resetAll": "Alle zurücksetzen", + "settings.keyboardShortcuts.recording": "Kombination drücken … (Esc bricht ab)", + "settings.keyboardShortcuts.conflict": "Kollidiert mit »{action}« — trotzdem übernehmen?", + "settings.keyboardShortcuts.conflictConfirm": "Übernehmen", + "settings.keyboardShortcuts.reserved": + "Diese Taste ist fest für die Werkzeug-Steuerung reserviert und kann nicht vergeben werden.", + "settings.keyboardShortcuts.category.general": "Allgemein", + "settings.keyboardShortcuts.category.selection": "Auswahl", + "settings.keyboardShortcuts.category.edit": "Bearbeiten", + "settings.keyboardShortcuts.category.boolean": "Boolesche Operationen", + "settings.keyboardShortcuts.category.transform": "Transformieren", + "settings.keyboardShortcuts.category.group": "Gruppieren", + "settings.keyboardShortcuts.category.tools": "Werkzeuge", + + "shortcut.undo": "Rückgängig", + "shortcut.redo": "Wiederholen", + "shortcut.selectAll": "Alles auswählen", + "shortcut.deleteSelection": "Auswahl löschen", + "shortcut.split": "Teilen", + "shortcut.join": "Verbinden", + "shortcut.copyElements": "Kopieren", + "shortcut.pasteElements": "Einfügen", + "shortcut.booleanUnion": "Vereinigung", + "shortcut.booleanDifference": "Subtraktion", + "shortcut.booleanIntersection": "Schnitt", + "shortcut.transformMove": "Bewegen", + "shortcut.transformMirror": "Spiegeln", + "shortcut.transformRotate": "Drehen", + "shortcut.measure": "Messen", + "shortcut.group": "Gruppieren", + "shortcut.ungroup": "Gruppe auflösen", + "shortcut.toolText": "Werkzeug: Text", + "shortcut.toolLine": "Werkzeug: Linie", + "shortcut.toolCircle": "Werkzeug: Kreis", + "shortcut.toolRect": "Werkzeug: Rechteck", + "shortcut.toolPolyline": "Werkzeug: Polylinie", + "shortcut.toolWall": "Werkzeug: Wand", + "shortcut.toolCeiling": "Werkzeug: Decke", + "shortcut.toolWindow": "Werkzeug: Fenster", + "shortcut.toolDoor": "Werkzeug: Tür", + "shortcut.toolRoom": "Werkzeug: Raum", + "settings.section.update": "Update", "settings.update.autoCheck": "Automatisch nach Updates suchen", "settings.update.snooze.active": "Aktiv", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 8aefd9a..87e9f33 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -176,6 +176,8 @@ export const en: Record = { "tool.line": "Line", "tool.xline": "Construction Line", "tool.xline.hint": "Construction line: two points set the direction (extended infinitely)", + "tool.ray": "Ray", + "tool.ray.hint": "Ray: set the anchor, then a direction point (extended infinitely on one side only)", "tool.block": "Insert Block", "tool.block.hint": "Insert block: pick the active definition via the option, then click the insertion point", "tool.polyline": "Polyline", @@ -196,6 +198,16 @@ export const en: Record = { "tool.dimension.hint": "Dimension: click points like a polyline (point 3+ snaps to a straight line), double-click/Enter finishes, then set the dimension line position (chains in one gesture)", "tool.kote": "Elevation mark", "tool.kote.hint": "Elevation mark: set a point, then type the height value (type toggle: top/bottom, finished/raw)", + "tool.detailref": "Detail/section reference", + "tool.detailref.hint": "Detail/section reference: set a point — label/sheet link afterwards in the Attributes panel", + "tool.scalebar": "Scale bar", + "tool.scalebar.hint": "Scale bar: set a point (bottom-left corner) — segment length/count via option", + "tool.revcloud": "Revision cloud", + "tool.revcloud.hint": "Revision cloud: click points like a polyline, Enter finishes open, clicking near start or \"Close\" closes it", + "tool.pointmarker": "Point marker", + "tool.pointmarker.hint": "Point marker: set a point — a cross-in-circle symbol marks a reference point", + "tool.wipeout": "Mask region", + "tool.wipeout.hint": "Mask region: click points like a polyline, clicking near start or Enter (3+ points) closes and covers the drawing underneath", "tool.text": "Text", "tool.text.hint": "Text: set anchor point, then type the text", "tool.leader": "Leader", @@ -260,10 +272,14 @@ export const en: Record = { "snap.center": "Circle center/quadrants (0/90/180/270°)", "snap.intersection": "Intersection", "snap.onEdge": "On edge (perp.)", + "snap.perpendicular": "Perpendicular to last point", + "snap.tangent": "Tangent to circle/arc", + "snap.parallel": "Parallel to reference (hover a line briefly)", "snap.grid": "Grid", "snap.ortho": "Ortho (Shift)", "snap.gridSize": "Grid size (m)", - "snap.angleStep": "Angle step", + "snap.showGrid": "Show grid", + "snap.angleStep": "Angle step (°)", "snap.commonAngles": "Common angles", "snap.commonAngleTolerance": "Angle tolerance (°)", "snap.hoverDivideDelayMs": "Hover delay (ms)", @@ -341,6 +357,32 @@ export const en: Record = { "attr.grayscale": "Grayscale", "attr.lineStyle": "Line style", "attr.lineStyle.none": "Default", + "attr.dashScale": "Line pattern scale", + "attr.hatch.angle": "Hatch angle", + "attr.hatch.scale": "Hatch scale", + "attr.hatch.origin": "Hatch origin", + "attr.hatch.fromStyle": "from style", + "attr.hatch.origin.corner": "snap to corner", + "attr.hatch.origin.reset": "reset", + "attr.hatch.origin.hint": "Anchors the pattern grid at this object\u2019s lower-left corner instead of the model origin.", + "attr.ends.section": "Line ends", + "attr.ends.start": "Start", + "attr.ends.end": "End", + "attr.ends.size": "Size (mm)", + "attr.ends.none": "None", + "attr.ends.arrow": "Arrow", + "attr.ends.arrowOpen": "Arrow open", + "attr.ends.dot": "Dot", + "attr.ends.tick": "Tick", + "attr.ends.square": "Square", + "attr.dim.section": "Dimension", + "attr.dim.gap": "Extension gap (mm)", + "attr.dim.overshoot": "Overshoot (mm)", + "attr.dim.tick": "Tick length (mm)", + "attr.dim.textHeight": "Text height (mm)", + "attr.dim.lineWeight": "Dimension line (mm)", + "attr.dim.extWeight": "Extension line (mm)", + "attr.dim.tickWeight": "Tick (mm)", "attr.fill": "Fill", "attr.fillColor": "Fill color", "attr.clearFill": "Remove fill color", @@ -585,6 +627,8 @@ export const en: Record = { "objinfo.opening.lintelLines.innen": "Inside", "objinfo.opening.lintelLines.aussen": "Outside", "objinfo.opening.lintelLines.beide": "Both", + "objinfo.opening.detailLevel": "Detail level", + "objinfo.detailLevel.view": "View (default)", "objinfo.opening.frameLine": "Frame (cut)", "objinfo.opening.frameViewLine": "Frame (view)", "objinfo.opening.sashLine": "Window (sash/muntins)", @@ -623,6 +667,12 @@ export const en: Record = { "objinfo.room.editStamp": "Edit stamp …", // ── Extruded solid attributes (truck integration, object info panel) ──── "objinfo.sectionLine.section": "Section line", + "objinfo.detailRef.section": "Detail/section reference", + "objinfo.detailRef.label": "Label", + "objinfo.detailRef.sheet": "Sheet", + "objinfo.detailRef.sheet.none": "No link", + "objinfo.detailRef.sheetLabel": "Sheet name (manual)", + "objinfo.detailRef.sheetLabel.hint": "e.g. \"A-102\"", "objinfo.sectionLine.kind.section": "Section", "objinfo.sectionLine.kind.elevation": "Elevation", "objinfo.sectionLine.name": "Name", @@ -643,7 +693,10 @@ export const en: Record = { "objinfo.extrudedSolid.floor": "Floor", "objinfo.rotate": "Rotate", "objinfo.drawing.length": "Length", + "objinfo.drawing.angle": "Angle", "objinfo.drawing.radius": "Radius", + "objinfo.drawing.startAngle": "Start angle", + "objinfo.drawing.endAngle": "End angle", "levels.addFloor": "+ Floor", "levels.addSection": "+ Section", "levels.addElevation": "+ Elevation", @@ -698,6 +751,12 @@ export const en: Record = { "ctx.copyProps": "Copy properties", "ctx.pasteProps": "Paste properties", "ctx.pasteProps.disabled": "Clipboard empty — first use “Copy properties”.", + "ctx.lock": "Lock", + "ctx.unlock": "Unlock", + "ctx.noPrint": "Don't print", + "ctx.print": "Print", + "ctx.insertPoint": "Insert point", + "ctx.deletePoint": "Delete point", "ctx.delete": "Delete", "ctx.delete.lastLayer": "The last layer cannot be deleted.", "ctx.delete.lastLevel": "The last drawing level cannot be deleted.", @@ -771,6 +830,7 @@ export const en: Record = { "default.componentName": "New component", "default.hatchName": "New hatch", "default.lineStyleName": "New line style", + "default.textStyleName": "New text style", "default.hatchNone": "None", "default.copySuffixLevel": "{name} copy", "default.copySuffixLayer": "{name} COPY", @@ -784,9 +844,11 @@ export const en: Record = { "default.stairTypeName": "New stair type", "default.penName": "New pen", "default.penSetName": "New pen set", + "default.customPaletteName": "My Colors", // Alerts. "alert.layerInUse": "Layer “{code} {name}” is used by components and cannot be deleted.", + "alert.polylineMinPoints": "Too few points — a polyline needs at least two, a closed one three.", "alert.penSetIsActive": "Pen set “{name}” is active and cannot be deleted — activate another pen set first.", "alert.componentInUse": "Component “{name}” is used by a wall type and cannot be deleted.", "alert.hatchInUse": "Hatch “{name}” is used by a component and cannot be deleted.", @@ -830,6 +892,18 @@ export const en: Record = { "resources.pens.seedStandard.hint": "Replaces the pen list with 255 procedurally generated pens (classic CAD numbering: 1-9 base colors, 10-249 hue steps, 250-255 grey wedge) plus a new active pen set with these colors.", "resources.delete.penSet": "Delete pen set “{name}”", "resources.delete.pen": "Delete pen “{name}”", + "resources.tab.palettes": "Palettes", + "resources.palettes.hint": "Controls which color palettes appear in the color field. Fill your own palettes straight from the color field via the “+” cell.", + "resources.palettes.builtin": "Bundled palettes", + "resources.palettes.custom": "Custom palettes", + "resources.palettes.countHint": "{count} colors", + "resources.palettes.add": "Palette", + "resources.palettes.empty": "No custom palette yet.", + "resources.palettes.placeholder": "Palette name", + "resources.palettes.visible": "Show in color field", + "resources.palettes.visible.hint": "Hidden palettes are kept but do not appear in the color field’s bank bar.", + "resources.palettes.noColors": "No colors in this palette yet.", + "resources.delete.customPalette": "Delete palette “{name}”", // Graphic overrides (rule engine). "resources.overrides.hint": @@ -892,6 +966,8 @@ export const en: Record = { "resources.field.leafCount": "Leaf count", "resources.field.leafStyle": "Leaf style", "resources.field.glazingRatio": "Glazing ratio", + "resources.field.panelCols": "Panels across", + "resources.field.panelRows": "Panels down", "resources.field.frameThickness": "Frame thickness (m)", "resources.field.frameDepth": "Frame depth (m)", "resources.field.defaultWidth": "Clear width (m)", @@ -1002,6 +1078,16 @@ export const en: Record = { "pen.weightHint": "Weight: {weight} mm", "pen.customColor": "Other color …", "pen.hexHint": "Hex color value (#rrggbb)", + "pen.paletteSimple": "Simple", + "pen.ralHint": "RAL Classic — approximate on-screen values, not color-binding. The official RAL fan deck governs for tendering/sampling.", + "colorMixer.spectrum": "Spectrum", + "colorMixer.cmykHint": "Simplified on-screen conversion, no print color management (ICC profile).", + "colorMixer.cmykHintIcc": "Real ICC color management (macOS ColorSync, Generic CMYK Profile) — relative colorimetric rendering.", + "pen.paletteCustom": "Custom", + "pen.newPalette": "New palette", + "pen.saveColor": "Save this color", + "pen.removeColor": "Remove from palette", + "pen.customEmpty": "No colors yet — use “Save this color” to store the current mixer color.", // 3D material (PBR) — built-in library + upload. "material.assign": "Material …", @@ -1088,6 +1174,12 @@ export const en: Record = { "resources.seg.addGap": "+ Gap", "resources.hatchKind.vector": "Vector", "resources.hatchKind.image": "Image", + "resources.hatchKind.gradient": "Gradient", + "resources.field.gradientType": "Gradient type", + "resources.field.gradientColor1": "Color 1", + "resources.field.gradientColor2": "Color 2", + "resources.gradientType.linear": "Linear", + "resources.gradientType.radial": "Radial", "resources.lines.parallel": "Parallel", "resources.lines.random": "Random", "resources.lineKind.dash": "Dash", @@ -1113,6 +1205,20 @@ export const en: Record = { "resources.delete.lineStyle": "Delete line style “{name}”", "resources.texture.empty": "—", + // Text styles. + "resources.tab.textStyles": "Text styles", + "resources.textStyles.hint": "Named formatting presets (font/size/bold/italic/underline/color) — applicable to a selection via the text formatting group on the toolbar. Applying copies the values once (no live coupling).", + "resources.textStyles.empty": "No text styles yet.", + "resources.textStyles.placeholder": "Text style", + "resources.textStyles.previewText": "Sample text Aa", + "resources.textStyles.defaultFont": "Default", + "resources.delete.textStyle": "Delete text style “{name}”", + "resources.field.font": "Font", + "resources.field.size": "Size (pt)", + "resources.field.bold": "Bold", + "resources.field.italic": "Italic", + "resources.field.underline": "Underline", + "dash.solid": "Solid", "dash.dashed": "Dashed", "dash.dotted": "Dotted", @@ -1172,12 +1278,16 @@ export const en: Record = { "cmd.stair.auftrittField": "Tread depth", "cmd.line.label": "Line", "cmd.line.start": "Start of line:", - "cmd.line.end": "End of line:", + "cmd.line.end": "End point (Enter to finish):", "cmd.xline.label": "Construction Line", "cmd.xline.start": "Start point:", "cmd.xline.end": "Direction point:", + "cmd.ray.label": "Ray", + "cmd.ray.start": "Anchor:", + "cmd.ray.end": "Direction point:", "cmd.block.label": "Insert Block", "cmd.block.point": "Insertion point:", + "cmd.block.rotate": "Rotation angle + size (distance = factor; click the same point for 0°/1×):", "cmd.block.def": "Symbol", "cmd.defblock.label": "Define Block", "cmd.defblock.base": "Base point:", @@ -1186,32 +1296,63 @@ export const en: Record = { "cmd.polyline.next": "Next point:", "cmd.polyline.close": "Close", "cmd.polyline.undo": "Undo", + "cmd.polyline.tangentOpt": "Tangential", + "cmd.polyline.arcThrough": "Point on arc:", + "cmd.polyline.arcOpt": "Arc", "cmd.polyline.closedOpt": "Closed", "cmd.rect.label": "Rectangle", "cmd.rect.first": "First corner:", "cmd.rect.second": "Opposite corner:", "cmd.rect.method": "Method", + "cmd.rect.radius": "Corner radius", "cmd.rect.center": "Center:", "cmd.rect.corner": "Corner:", "cmd.rect.baseEnd": "Second corner (base edge):", "cmd.rect.rise": "Height:", "cmd.circle.label": "Circle", + "cmd.circle.method": "Method", "cmd.circle.center": "Center:", "cmd.circle.radius": "Radius:", + "cmd.circle.diameterStart": "First point (diameter):", + "cmd.circle.diameterEnd": "Second point (diameter):", + "cmd.circle.threeFirst": "First point:", + "cmd.circle.ttrFirst": "Select first tangent object (line/circle):", + "cmd.circle.ttrSecond": "Select second tangent object (line/circle):", + "cmd.circle.threeSecond": "Second point:", + "cmd.circle.threeThird": "Third point:", "cmd.arc.label": "Arc", + "cmd.arc.method": "Method", "cmd.arc.center": "Center:", "cmd.arc.start": "Start point (radius + start angle):", "cmd.arc.end": "End point (end angle):", + "cmd.arc.threeStart": "Start point:", + "cmd.arc.through": "Through point:", + "cmd.arc.threeEnd": "End point:", + "cmd.arc.serStart": "Start point:", + "cmd.arc.serEnd": "End point:", + "cmd.arc.radius": "Radius:", + "cmd.arc.sedStart": "Start point:", + "cmd.arc.sedEnd": "End point:", + "cmd.arc.direction": "Direction (tangent at start):", "cmd.ellipse.label": "Ellipse", + "cmd.ellipse.method": "Method", "cmd.ellipse.corner1": "First corner:", "cmd.ellipse.corner2": "Opposite corner:", + "cmd.ellipse.axisCenter": "Center:", + "cmd.ellipse.major": "Major axis:", + "cmd.ellipse.minor": "Minor axis:", "cmd.polygon.label": "Polygon", "cmd.polygon.center": "Center:", "cmd.polygon.radius": "Radius:", "cmd.polygon.sides": "Sides", + "cmd.polygon.mode": "Mode", + "cmd.polygon.construct": "Construction", + "cmd.polygon.edgeStart": "First edge point:", + "cmd.polygon.edgeEnd": "Second edge point:", "cmd.spline.label": "Spline", "cmd.spline.start": "Start point:", "cmd.spline.next": "Next point ( Close Undo ):", + "cmd.spline.curveMode": "Mode", "cmd.bezier.label": "Bezier", "cmd.bezier.start": "Start point:", "cmd.bezier.c1": "Handle 1:", @@ -1226,6 +1367,22 @@ export const en: Record = { "cmd.dimension.finish": "Finish", "cmd.kote.label": "Elevation mark", "cmd.kote.point": "Point:", + "cmd.detailref.label": "Detail/section reference", + "cmd.detailref.point": "Point:", + "cmd.scalebar.label": "Scale bar", + "cmd.scalebar.point": "Point (bottom-left corner):", + "cmd.scalebar.length": "Segment length", + "cmd.scalebar.segments": "Segments", + "cmd.revcloud.label": "Revision cloud", + "cmd.revcloud.start": "Start point:", + "cmd.revcloud.next": "Next point ( Close ):", + "cmd.revcloud.close": "Close", + "cmd.revcloud.arcSize": "Arc size", + "cmd.pointmarker.label": "Point marker", + "cmd.pointmarker.point": "Point:", + "cmd.wipeout.label": "Mask region", + "cmd.wipeout.start": "Start point:", + "cmd.wipeout.next": "Next point:", "cmd.kote.value": "Height value ( Type ):", "cmd.kote.kind.okFertig": "Top, finished", "cmd.kote.kind.ukFertig": "Bottom, finished", @@ -1235,7 +1392,9 @@ export const en: Record = { "cmd.text.label": "Text", "cmd.text.point": "Anchor point:", "cmd.leader.label": "Leader", + "cmd.leader.bends": "Bends", "cmd.leader.target": "Target point:", + "cmd.leader.bend": "Bend point:", "cmd.leader.anchor": "Text anchor:", "cmd.textpath.label": "Text on Path", "cmd.textpath.start": "Path point:", @@ -1259,6 +1418,26 @@ export const en: Record = { "objinfo.measure.angle": "Angle", "objinfo.measure.hint": "Click = point · right-click = new path · Esc = end", "transform.needSelection": "Select objects first, then rotate.", + "cmd.align.label": "Align", + "cmd.align.prompt": "Choose edge or axis:", + "cmd.align.left": "Left", + "cmd.align.centerX": "Center", + "cmd.align.right": "Right", + "cmd.align.top": "Top", + "cmd.align.centerY": "Middle", + "cmd.align.bottom": "Bottom", + "cmd.align.distX": "Distribute horizontally", + "cmd.align.distY": "Distribute vertically", + "cmd.explode.label": "Explode", + "cmd.scale.label": "Scale", + "cmd.scale.base": "Base point:", + "cmd.scale.factor": "Factor or reference length (point):", + "cmd.scale.target": "New length:", + "cmd.scale.empty": "Nothing selected (select objects first).", + "cmd.rotate.base": "Base point:", + "cmd.rotate.angle": "Angle (degrees) or reference point:", + "cmd.rotate.target": "New direction:", + "cmd.rotate.empty": "Nothing selected (select objects first).", "cmd.mirror.label": "Mirror", "cmd.mirror.first": "First point of mirror axis:", "cmd.mirror.second": "Second point of mirror axis:", @@ -1269,8 +1448,11 @@ export const en: Record = { "cmd.copy.target": "Target point (Enter to finish):", "cmd.copy.empty": "Nothing selected (select objects first).", "cmd.array.label": "Array", + "cmd.array.kind": "Kind", "cmd.array.base": "Base point:", "cmd.array.target": "Target point ( Count ):", + "cmd.array.center": "Center:", + "cmd.array.polarAngle": "Angle per copy ( Count ):", "cmd.array.count": "Count", "cmd.offset.label": "Offset", "cmd.offset.pick": "Select curve:", @@ -1282,6 +1464,9 @@ export const en: Record = { // Trim (quick-trim): click the part to cut away; repeats until Esc. "cmd.trim.label": "Trim", "cmd.trim.pick": "Click the part to trim away (Esc to finish):", + "cmd.break.label": "Break", + "cmd.break.p1": "First point (on a line/open polyline):", + "cmd.break.p2": "Second point:", // Extend: counterpart to Trim — extends an open curve to the next other curve. "cmd.extend.label": "Extend", "cmd.extend.pick": "Click the curve near the end to extend (Esc to finish):", @@ -1382,6 +1567,9 @@ export const en: Record = { "import.dwg.loading": "Reading DWG …", "import.dwg.hint": "DWG could not be read. Alternatively, convert the file to DXF with the free ODA File Converter, then import the DXF.", + "import.loading.heading": "DXF file", + "import.loading.hint": + "Reading DXF … this can take a moment for very large files (e.g. a cadastral import of an entire city).", "import.confirm": "Import", "import.cancel": "Cancel", "import.badge.floor": "Floor", @@ -1390,7 +1578,9 @@ export const en: Record = { "import.badge.drawing": "Drawing", // PDF export. - "export.title": "Export PDF", + "export.title": "Export PDF/SVG", + "export.confirmSvg": "As SVG", + "export.confirmPdf": "As PDF", "export.close": "Close", "export.plan": "Plan", "export.scale": "Scale", @@ -1398,6 +1588,8 @@ export const en: Record = { "export.orientation": "Orientation", "export.orientation.portrait": "Portrait", "export.orientation.landscape": "Landscape", + "export.scale.customPlaceholder": "Custom (e.g. 1:75 or 75)", + "export.selectionOnly": "Export selection only ({count} element(s))", "export.warnFit": "At the chosen scale the plan does not fully fit the sheet — pick a larger format or a smaller scale.", "export.confirm": "Export", @@ -1436,6 +1628,13 @@ export const en: Record = { "lock.forceOpen": "Force open anyway", "lock.forceOpenWarning": "Warning: opens for writing even though another instance holds the file — changes may overwrite each other.", + + // Unsaved changes (New/Open would discard them). + "unsaved.title": "Unsaved changes", + "unsaved.message": + "The current project has unsaved changes. Save before continuing?", + "unsaved.save": "Save", + "unsaved.discard": "Don't save", "exportSave.title": "Export", "exportSave.format": "Format", "exportSave.filename": "File name", @@ -1467,6 +1666,9 @@ export const en: Record = { "topbar.settings": "Settings", "topbar.settings.hint": "Open settings (display colors, project)", "settings.title": "Settings", + "settings.tab.general": "General", + "settings.tab.shortcuts": "Keyboard shortcuts", + "settings.tab.update": "Update", "settings.section.workspace": "Workspace", "settings.section.display": "Display", "settings.theme": "Appearance", @@ -1482,6 +1684,61 @@ export const en: Record = { "settings.referenceElevation": "Ground floor reference elevation (m a.s.l.)", "settings.referenceElevation.hint": "Stored only — not used yet. Terrain draping / real-world elevations relative to the ground floor will follow.", + "settings.section.shortcuts": "Command-line shortcuts (typed alias)", + "settings.shortcuts.hint": + "Your own command-line shortcuts — a custom shortcut overrides (for you only) a built-in one with the same letter, if there is one.", + "settings.shortcuts.remove": "Remove", + "settings.shortcuts.newKey": "Shortcut", + "settings.shortcuts.pickCommand": "Pick a command…", + "settings.shortcuts.add": "Add", + + "settings.section.keyboardShortcuts": "Keyboard shortcuts", + "settings.keyboardShortcuts.hint": + "Real keyboard shortcuts (Ctrl/Cmd+…) for the most important actions — freely rebindable. Click \"Change\" and press the new combination.", + "settings.keyboardShortcuts.change": "Change", + "settings.keyboardShortcuts.reset": "Reset", + "settings.keyboardShortcuts.resetAll": "Reset all", + "settings.keyboardShortcuts.recording": "Press a combination… (Esc cancels)", + "settings.keyboardShortcuts.conflict": "Conflicts with \"{action}\" — use it anyway?", + "settings.keyboardShortcuts.conflictConfirm": "Use anyway", + "settings.keyboardShortcuts.reserved": + "This key is permanently reserved for tool control and can't be assigned.", + "settings.keyboardShortcuts.category.general": "General", + "settings.keyboardShortcuts.category.selection": "Selection", + "settings.keyboardShortcuts.category.edit": "Edit", + "settings.keyboardShortcuts.category.boolean": "Boolean operations", + "settings.keyboardShortcuts.category.transform": "Transform", + "settings.keyboardShortcuts.category.group": "Grouping", + "settings.keyboardShortcuts.category.tools": "Tools", + + "shortcut.undo": "Undo", + "shortcut.redo": "Redo", + "shortcut.selectAll": "Select all", + "shortcut.deleteSelection": "Delete selection", + "shortcut.split": "Split", + "shortcut.join": "Join", + "shortcut.copyElements": "Copy", + "shortcut.pasteElements": "Paste", + "shortcut.booleanUnion": "Union", + "shortcut.booleanDifference": "Difference", + "shortcut.booleanIntersection": "Intersection", + "shortcut.transformMove": "Move", + "shortcut.transformMirror": "Mirror", + "shortcut.transformRotate": "Rotate", + "shortcut.measure": "Measure", + "shortcut.group": "Group", + "shortcut.ungroup": "Ungroup", + "shortcut.toolText": "Tool: Text", + "shortcut.toolLine": "Tool: Line", + "shortcut.toolCircle": "Tool: Circle", + "shortcut.toolRect": "Tool: Rectangle", + "shortcut.toolPolyline": "Tool: Polyline", + "shortcut.toolWall": "Tool: Wall", + "shortcut.toolCeiling": "Tool: Ceiling", + "shortcut.toolWindow": "Tool: Window", + "shortcut.toolDoor": "Tool: Door", + "shortcut.toolRoom": "Tool: Room", + "settings.section.update": "Update", "settings.update.autoCheck": "Check for updates automatically", "settings.update.snooze.active": "Active", diff --git a/src/io/dxfParser.worker.ts b/src/io/dxfParser.worker.ts new file mode 100644 index 0000000..035fe35 --- /dev/null +++ b/src/io/dxfParser.worker.ts @@ -0,0 +1,39 @@ +// Web-Worker-Einstiegspunkt für `parseDxf` — lagert die eigentliche Parse- +// Arbeit AUSSERHALB des Haupt-Threads aus, damit die UI bei sehr grossen +// Dateien (ein Kataster-DXF für eine ganze Stadt kann mehrere hundert MB mit +// Millionen Entities sein) nicht einfriert. `parseDxf` selbst ist komplett +// synchron (dxf-parser hat keine Chunk-/Progress-API) — bisher lief das direkt +// im Haupt-Thread (`useProjectFileActions.ts::openImportForFile`), was die App +// für die gesamte Parse-Dauer blockierte. Nutzer-Report 2026-10-08. +// +// Einfaches Einmal-Protokoll (ein Worker wird pro Import frisch erzeugt und +// danach terminiert, s. `dxfParserAsync.ts`): +// → { type: "parse", text: string } +// ← { type: "result", result: DxfImportResult } | { type: "error", message: string } +// +// `parseDxf` selbst ist "three-frei" (reine Datentransformation, keine DOM- +// Zugriffe) und läuft daher unverändert im Worker-Kontext — s. Kopfkommentar +// dort. + +import { parseDxf } from "./dxfParser"; +import type { DxfImportResult } from "./dxfParser"; + +export type DxfWorkerRequest = { type: "parse"; text: string }; +export type DxfWorkerResponse = + | { type: "result"; result: DxfImportResult } + | { type: "error"; message: string }; + +self.onmessage = (e: MessageEvent) => { + if (e.data?.type !== "parse") return; + try { + const result = parseDxf(e.data.text); + const response: DxfWorkerResponse = { type: "result", result }; + (self as unknown as Worker).postMessage(response); + } catch (err) { + const response: DxfWorkerResponse = { + type: "error", + message: err instanceof Error ? err.message : String(err), + }; + (self as unknown as Worker).postMessage(response); + } +}; diff --git a/src/io/dxfParserAsync.ts b/src/io/dxfParserAsync.ts new file mode 100644 index 0000000..d6f25ff --- /dev/null +++ b/src/io/dxfParserAsync.ts @@ -0,0 +1,41 @@ +// Asynchroner Wrapper um `parseDxf` über einen Web Worker +// (`dxfParser.worker.ts`) — hält den Haupt-Thread/die UI reaktionsfähig, auch +// bei sehr grossen DXF-Dateien (Kataster-Import einer ganzen Stadt, Nutzer- +// Report 2026-10-08: 400 MB liessen die App vorher für die GESAMTE Parse- +// Dauer einfrieren). Reiner Transport — die Parse-Logik bleibt unverändert +// in `dxfParser.ts` (dort weiterhin synchron direkt aufrufbar/testbar, z. B. +// für kleinere Importe oder Unit-Tests ohne Worker-Umgebung). +// +// Bewusst EIN Worker pro Import-Aufruf (nicht dauerhaft gepoolt) — DXF-Importe +// sind seltene, einmalige Aktionen, kein Hochfrequenz-Pfad; der Start-Overhead +// eines frischen Workers ist gegenüber der Parse-Dauer einer grossen Datei +// vernachlässigbar. +// +// `new Worker(new URL(...), { type: "module" })` ist Vites eingebautes Worker- +// Muster (funktioniert in Dev UND Build identisch, kein vite.config-Eintrag +// nötig) — kein Browser-Global, daher ohne dediziertes Unit-Test (Vitest läuft +// im "node"-Environment ohne `Worker`-Global, s. `vitest.config.ts`); dieselbe +// Bestes-Bemühen-Haltung wie bei anderem browser-API-gebundenem Code in diesem +// Projekt (z. B. `saveFile.ts`). + +import type { DxfImportResult } from "./dxfParser"; +import type { DxfWorkerRequest, DxfWorkerResponse } from "./dxfParser.worker"; + +export function parseDxfAsync(text: string): Promise { + return new Promise((resolve, reject) => { + const worker = new Worker(new URL("./dxfParser.worker.ts", import.meta.url), { + type: "module", + }); + worker.onmessage = (e: MessageEvent) => { + worker.terminate(); + if (e.data.type === "result") resolve(e.data.result); + else reject(new Error(e.data.message)); + }; + worker.onerror = (e) => { + worker.terminate(); + reject(new Error(e.message || "DXF-Import (Worker) fehlgeschlagen")); + }; + const req: DxfWorkerRequest = { type: "parse", text }; + worker.postMessage(req); + }); +} diff --git a/src/menus/contextMenu.tsx b/src/menus/contextMenu.tsx index ad13571..fb7dbdf 100644 --- a/src/menus/contextMenu.tsx +++ b/src/menus/contextMenu.tsx @@ -8,7 +8,8 @@ // Kommentare deutsch (CONVENTIONS.md). import { t } from "../i18n"; -import type { LayerCategory, Project } from "../model/types"; +import { nearestPolylineTarget, toleranceFor } from "../geometry/polylinePoint"; +import type { LayerCategory, Project, Vec2 } from "../model/types"; import { flattenCategories } from "../model/types"; import { findCategory } from "../state/projectSlice"; import { MenuIcon } from "../ui/ContextMenu"; @@ -18,7 +19,7 @@ import type { ContextMenuItem } from "../ui/ContextMenu"; export type MenuState = | { kind: "layer"; code: string; x: number; y: number } | { kind: "level"; id: string; x: number; y: number } - | { kind: "plan"; wallId: string | null; x: number; y: number } + | { kind: "plan"; wallId: string | null; model: Vec2; x: number; y: number } | { kind: "viewport"; wallId: string | null; x: number; y: number } | null; @@ -71,12 +72,43 @@ export interface MenuActions { union: () => void; difference: () => void; intersect: () => void; - /** Anzahl aktuell selektierter 2D-Zeichnungselemente (z-Anordnen-Menü). */ + /** Anzahl aktuell selektierter 2D-Zeichnungselemente (z-Anordnen-Menü + + * „Eigenschaften übertragen"). */ drawingSelectionCount: number; bringToFront: () => void; bringForward: () => void; sendBackward: () => void; sendToBack: () => void; + /** + * Einzeln selektierte Polylinie (2D) — Grundlage für „Punkt einfügen/ + * löschen" im Grundriss-Kontextmenü. `null`, wenn nichts oder etwas + * anderes selektiert ist; dann entfallen die beiden Einträge. + */ + selectedPolyline: { id: string; pts: Vec2[]; closed: boolean } | null; + /** Ob eine Element-Stil-Zwischenablage gefüllt ist (aktiviert „Einfügen"). */ + hasDrawingStyleClipboard: boolean; + /** Kopiert das Aussehen des ERSTEN gewählten 2D-Elements. */ + copyDrawingStyle: () => void; + /** Überträgt das kopierte Aussehen auf alle gewählten 2D-Elemente. */ + pasteDrawingStyle: () => void; + insertPolylinePoint: (id: string, segIndex: number, pt: Vec2) => void; + deletePolylinePoint: (id: string, index: number) => void; + /** Anzahl aktuell selektierter Elemente ÜBER ALLE Arten (Wand/2D/Decke/ + * Raum/Treppe/Stütze/Dach/Öffnung) — Grundlage für „Sperren"/„Entsperren". */ + lockableSelectionCount: number; + /** Sind ALLE aktuell gewählten Elemente bereits gesperrt? Bestimmt Label/Icon. */ + selectionAllLocked: boolean; + /** Sperrt/entsperrt die gesamte aktuelle Auswahl in einem Zug. */ + toggleSelectionLock: () => void; + /** + * Sind ALLE aktuell gewählten 2D-Zeichnungen bereits `noPrint`? Bestimmt + * Label/Icon von „Nicht drucken"/„Drucken" — nur `Drawing2D` kennt das + * Feld (Nutzer-Wunsch „Kein 'nicht druckend'-Flag"), daher an + * `drawingSelectionCount` gekoppelt statt einer eigenen Zählung. + */ + selectionAllNoPrint: boolean; + /** Setzt/löscht `noPrint` für die gesamte aktuelle 2D-Auswahl in einem Zug. */ + toggleSelectionNoPrint: () => void; } /** @@ -94,7 +126,7 @@ export function buildMenuItems( case "level": return levelMenuItems(menu.id, a); case "plan": - return planMenuItems(menu.wallId, a); + return planMenuItems(menu.wallId, menu.model, a); case "viewport": return viewportMenuItems(menu.wallId, a); } @@ -225,8 +257,79 @@ function levelMenuItems(id: string, a: MenuActions): ContextMenuItem[] { */ function planMenuItems( wallId: string | null, + model: Vec2, a: MenuActions, ): ContextMenuItem[] { + // Stützpunkt-Einträge NUR, wenn genau eine Polylinie selektiert ist UND der + // Rechtsklick nahe genug an ihr liegt (sonst würde „Punkt löschen" einen + // weit entfernten, nicht gemeinten Eckpunkt treffen). + const poly = a.selectedPolyline; + const target = poly ? nearestPolylineTarget(poly, model, toleranceFor(poly)) : null; + const pointItems: ContextMenuItem[] = []; + if (poly && target?.kind === "segment") { + pointItems.push({ + label: t("ctx.insertPoint"), + icon: , + onClick: () => a.insertPolylinePoint(poly.id, target.segIndex, target.at), + }); + } + if (poly && target?.kind === "vertex") { + const min = poly.closed ? 4 : 3; + const enabled = poly.pts.length >= min; + pointItems.push({ + label: t("ctx.deletePoint"), + icon: , + disabled: !enabled, + title: enabled ? undefined : t("alert.polylineMinPoints"), + onClick: () => a.deletePolylinePoint(poly.id, target.index), + }); + } + // Eigenschaften übertragen — dasselbe Muster wie im Ebenen-Menü, nur für + // 2D-Elemente. Kopieren ab einem gewählten Element, Einfügen sobald etwas + // in der Zwischenablage liegt. + const styleItems: ContextMenuItem[] = + a.drawingSelectionCount >= 1 + ? [ + { + label: t("ctx.copyProps"), + icon: , + onClick: a.copyDrawingStyle, + }, + { + label: t("ctx.pasteProps"), + icon: , + disabled: !a.hasDrawingStyleClipboard, + title: a.hasDrawingStyleClipboard ? undefined : t("ctx.pasteProps.disabled"), + onClick: a.pasteDrawingStyle, + }, + ] + : []; + + // Objekt sperren/entsperren — wirkt auf die GANZE aktuelle Auswahl (nicht + // nur 2D-Zeichnungen wie `styleItems`/`arrangeItems`), ein Undo-Schritt. + const lockItems: ContextMenuItem[] = + a.lockableSelectionCount >= 1 + ? [ + { + label: a.selectionAllLocked ? t("ctx.unlock") : t("ctx.lock"), + icon: , + onClick: a.toggleSelectionLock, + }, + ] + : []; + + // Nicht drucken/Drucken — nur für die 2D-Auswahl (`Drawing2D.noPrint`). + const noPrintItems: ContextMenuItem[] = + a.drawingSelectionCount >= 1 + ? [ + { + label: a.selectionAllNoPrint ? t("ctx.print") : t("ctx.noPrint"), + icon: , + onClick: a.toggleSelectionNoPrint, + }, + ] + : []; + // Boolean-Einträge (Vereinigen/Subtrahieren/Schneiden) auf die 2D-Auswahl. // Aktiv ab 2 geschlossenen Flächen; sonst deaktiviert mit erklärendem Tooltip. const boolEnabled = a.closedSelectionCount >= 2; @@ -293,6 +396,14 @@ function planMenuItems( if (wallId) { return [ + ...pointItems, + ...(pointItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...styleItems, + ...(styleItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...lockItems, + ...(lockItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...noPrintItems, + ...(noPrintItems.length ? [{ divider: true } as ContextMenuItem] : []), { label: t("ctx.fitSelection"), icon: , @@ -316,6 +427,14 @@ function planMenuItems( ]; } return [ + ...pointItems, + ...(pointItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...styleItems, + ...(styleItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...lockItems, + ...(lockItems.length ? [{ divider: true } as ContextMenuItem] : []), + ...noPrintItems, + ...(noPrintItems.length ? [{ divider: true } as ContextMenuItem] : []), ...booleanItems, { divider: true }, ...arrangeItems, diff --git a/src/menus/useContextMenuState.ts b/src/menus/useContextMenuState.ts index 86ea5df..40832bb 100644 --- a/src/menus/useContextMenuState.ts +++ b/src/menus/useContextMenuState.ts @@ -7,6 +7,7 @@ import { useState } from "react"; import type { EditorState, MenuState } from "./contextMenu"; +import type { DrawingStyle } from "../editors/matchProps"; export function useContextMenuState() { // Eigenschaften-Zwischenablage des Ebenen-Kontextmenüs (Farbe + Linienstärke). @@ -14,6 +15,12 @@ export function useContextMenuState() { color: string; lw: number; } | null>(null); + // Eigenschaften-Zwischenablage „Eigenschaften übertragen" (2D-Element- + // Kontextmenü) — dasselbe Muster wie `layerClipboard`, nur der Stil eines + // 2D-Elements statt Farbe+Strichstärke einer Ebene. + const [drawingStyleClipboard, setDrawingStyleClipboard] = useState( + null, + ); // Offenes Kontextmenü (genau eines) — Quelle bestimmt die Einträge. const [menu, setMenu] = useState(null); // Offener Inline-Editor (Ebene bzw. Geschoss) — aus einem Menüpunkt geöffnet. @@ -36,6 +43,8 @@ export function useContextMenuState() { return { layerClipboard, setLayerClipboard, + drawingStyleClipboard, + setDrawingStyleClipboard, menu, setMenu, editor, diff --git a/src/model/color.test.ts b/src/model/color.test.ts new file mode 100644 index 0000000..7d5c7ca --- /dev/null +++ b/src/model/color.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it } from "vitest"; +import { + cmykToRgb, + hexToRgb, + hslToRgb, + hsvToRgb, + rgbToCmyk, + rgbToHex, + rgbToHsl, + rgbToHsv, + MATERIAL_PALETTE, + RAL_CLASSIC, + TANGO_PALETTE, +} from "./color"; + +describe("hexToRgb/rgbToHex", () => { + it("löst 6-stelliges Hex korrekt auf", () => { + expect(hexToRgb("#ff0000")).toEqual({ r: 255, g: 0, b: 0 }); + expect(hexToRgb("#00ff80")).toEqual({ r: 0, g: 255, b: 128 }); + }); + + it("löst 3-stelliges Kurz-Hex auf", () => { + expect(hexToRgb("#f00")).toEqual({ r: 255, g: 0, b: 0 }); + }); + + it("rgbToHex ist die Umkehrung von hexToRgb (Rundreise)", () => { + for (const hex of ["#123456", "#abcdef", "#000000", "#ffffff"]) { + expect(rgbToHex(hexToRgb(hex))).toBe(hex); + } + }); + + it("rgbToHex klammert ausserhalb 0..255", () => { + expect(rgbToHex({ r: -10, g: 300, b: 128 })).toBe("#00ff80"); + }); +}); + +describe("rgbToCmyk/cmykToRgb", () => { + it("Schwarz → k=100, c=m=y=0", () => { + expect(rgbToCmyk({ r: 0, g: 0, b: 0 })).toEqual({ c: 0, m: 0, y: 0, k: 100 }); + }); + + it("Weiss → alle 0", () => { + expect(rgbToCmyk({ r: 255, g: 255, b: 255 })).toEqual({ c: 0, m: 0, y: 0, k: 0 }); + }); + + it("Reinrot → kein Cyan, k=0", () => { + const cmyk = rgbToCmyk({ r: 255, g: 0, b: 0 }); + expect(cmyk.c).toBe(0); + expect(cmyk.k).toBe(0); + expect(cmyk.m).toBe(100); + expect(cmyk.y).toBe(100); + }); + + it("Rundreise RGB → CMYK → RGB bleibt (nach Rundung) nah am Original", () => { + for (const rgb of [ + { r: 200, g: 100, b: 50 }, + { r: 10, g: 200, b: 230 }, + { r: 128, g: 128, b: 128 }, + ]) { + const back = cmykToRgb(rgbToCmyk(rgb)); + expect(Math.abs(back.r - rgb.r)).toBeLessThanOrEqual(3); + expect(Math.abs(back.g - rgb.g)).toBeLessThanOrEqual(3); + expect(Math.abs(back.b - rgb.b)).toBeLessThanOrEqual(3); + } + }); +}); + +describe("RAL_CLASSIC", () => { + it("jeder Eintrag hat eindeutigen Code + gültiges 6-stelliges Hex", () => { + const seen = new Set(); + for (const ral of RAL_CLASSIC) { + expect(seen.has(ral.code)).toBe(false); + seen.add(ral.code); + expect(ral.hex).toMatch(/^#[0-9a-fA-F]{6}$/); + expect(ral.name.length).toBeGreaterThan(0); + } + }); + + it("enthält eine substanzielle Auswahl über alle RAL-Klassen (1000er-9000er)", () => { + const groups = new Set(RAL_CLASSIC.map((r) => r.code[0])); + for (const g of ["1", "2", "3", "4", "5", "6", "7", "8", "9"]) { + expect(groups.has(g)).toBe(true); + } + expect(RAL_CLASSIC.length).toBeGreaterThan(100); + }); +}); + +describe("TANGO_PALETTE", () => { + it("27 Einträge (9 Farbfamilien × 3 Helligkeitsstufen), alle gültiges Hex", () => { + expect(TANGO_PALETTE.length).toBe(27); + for (const c of TANGO_PALETTE) { + expect(c.hex).toMatch(/^#[0-9a-fA-F]{6}$/); + expect(c.name.length).toBeGreaterThan(0); + } + }); + + it("keine doppelten Hex-Werte", () => { + const seen = new Set(TANGO_PALETTE.map((c) => c.hex.toLowerCase())); + expect(seen.size).toBe(TANGO_PALETTE.length); + }); +}); + +describe("MATERIAL_PALETTE", () => { + it("19 Farbfamilien × 3 Stufen (100/500/900), alle gültiges Hex", () => { + expect(MATERIAL_PALETTE.length).toBe(57); + for (const c of MATERIAL_PALETTE) { + expect(c.hex).toMatch(/^#[0-9a-fA-F]{6}$/); + expect(c.name).toMatch(/ (100|500|900)$/); + } + }); + + it("keine doppelten Hex-Werte", () => { + const seen = new Set(MATERIAL_PALETTE.map((c) => c.hex.toLowerCase())); + expect(seen.size).toBe(MATERIAL_PALETTE.length); + }); +}); + +describe("rgbToHsl/hslToRgb", () => { + it("Grundfarben haben die erwarteten Farbtöne", () => { + expect(rgbToHsl({ r: 255, g: 0, b: 0 })).toEqual({ h: 0, s: 100, l: 50 }); + expect(rgbToHsl({ r: 0, g: 255, b: 0 }).h).toBe(120); + expect(rgbToHsl({ r: 0, g: 0, b: 255 }).h).toBe(240); + }); + + it("unbunte Farben: Sättigung 0 (Farbton ist dort undefiniert)", () => { + expect(rgbToHsl({ r: 255, g: 255, b: 255 })).toEqual({ h: 0, s: 0, l: 100 }); + expect(rgbToHsl({ r: 0, g: 0, b: 0 })).toEqual({ h: 0, s: 0, l: 0 }); + expect(rgbToHsl({ r: 128, g: 128, b: 128 }).s).toBe(0); + }); + + it("Rundreise RGB → HSL → RGB bleibt nah am Original", () => { + for (const rgb of [ + { r: 200, g: 100, b: 50 }, + { r: 10, g: 200, b: 230 }, + { r: 128, g: 128, b: 128 }, + { r: 0, g: 0, b: 0 }, + ]) { + const back = hslToRgb(rgbToHsl(rgb)); + expect(Math.abs(back.r - rgb.r)).toBeLessThanOrEqual(3); + expect(Math.abs(back.g - rgb.g)).toBeLessThanOrEqual(3); + expect(Math.abs(back.b - rgb.b)).toBeLessThanOrEqual(3); + } + }); +}); + +describe("rgbToHsv/hsvToRgb", () => { + it("Reinrot ist h=0, s=100, v=100; Schwarz hat v=0", () => { + expect(rgbToHsv({ r: 255, g: 0, b: 0 })).toEqual({ h: 0, s: 100, v: 100 }); + expect(rgbToHsv({ r: 0, g: 0, b: 0 })).toEqual({ h: 0, s: 0, v: 0 }); + }); + + it("Rundreise RGB → HSV → RGB bleibt nah am Original", () => { + for (const rgb of [ + { r: 200, g: 100, b: 50 }, + { r: 10, g: 200, b: 230 }, + { r: 255, g: 255, b: 255 }, + ]) { + const back = hsvToRgb(rgbToHsv(rgb)); + expect(Math.abs(back.r - rgb.r)).toBeLessThanOrEqual(3); + expect(Math.abs(back.g - rgb.g)).toBeLessThanOrEqual(3); + expect(Math.abs(back.b - rgb.b)).toBeLessThanOrEqual(3); + } + }); + + it("HSV und HSL stimmen im Farbton überein", () => { + const rgb = { r: 40, g: 180, b: 90 }; + expect(rgbToHsv(rgb).h).toBe(rgbToHsl(rgb).h); + }); +}); diff --git a/src/model/color.ts b/src/model/color.ts new file mode 100644 index 0000000..a0cb824 --- /dev/null +++ b/src/model/color.ts @@ -0,0 +1,464 @@ +// Farbraum-Hilfsfunktionen (Hex↔RGB↔CMYK) + eine kuratierte RAL-Classic- +// Auswahl — Grundlage für den Mischer/die Paletten im Farbfeld +// (`ui/ColorMixer.tsx`, `ui/FreeColorPicker.tsx`). Reine Konvertierungen, +// keine Bibliothek. +// +// CMYK ist hier eine VEREINFACHTE Bildschirm-Umrechnung (naive R/G/B↔C/M/Y/K- +// Formel ohne ICC-Profil/Druckkalibrierung) — für die Mischer-Vorschau am +// Bildschirm ausreichend, aber NICHT farbverbindlich für den Druck (dafür +// bräuchte es echtes Farbmanagement, das diese App nicht betreibt). +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +export interface Rgb { + r: number; + g: number; + b: number; +} +export interface Cmyk { + c: number; + m: number; + y: number; + k: number; +} + +/** "#rrggbb" oder "#rgb" → {r,g,b} (0..255). Ungültige Eingaben ergeben Schwarz. */ +export function hexToRgb(hex: string): Rgb { + const h = hex.replace("#", "").trim(); + const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h; + const n = parseInt(full, 16); + if (full.length !== 6 || Number.isNaN(n)) return { r: 0, g: 0, b: 0 }; + return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 }; +} + +/** {r,g,b} (0..255, wird geklammert) → "#rrggbb". */ +export function rgbToHex({ r, g, b }: Rgb): string { + const clamp = (v: number) => Math.max(0, Math.min(255, Math.round(v))); + const toHex = (v: number) => clamp(v).toString(16).padStart(2, "0"); + return `#${toHex(r)}${toHex(g)}${toHex(b)}`; +} + +/** RGB (0..255) → CMYK (0..100, gerundet). Reine Bildschirm-Näherung, s. Modul-Kommentar. */ +export function rgbToCmyk({ r, g, b }: Rgb): Cmyk { + const rn = r / 255; + const gn = g / 255; + const bn = b / 255; + const k = 1 - Math.max(rn, gn, bn); + if (k >= 1) return { c: 0, m: 0, y: 0, k: 100 }; + const c = (1 - rn - k) / (1 - k); + const m = (1 - gn - k) / (1 - k); + const y = (1 - bn - k) / (1 - k); + return { + c: Math.round(c * 100), + m: Math.round(m * 100), + y: Math.round(y * 100), + k: Math.round(k * 100), + }; +} + +/** CMYK (0..100) → RGB (0..255, unklammert — Aufrufer nutzt i. d. R. {@link rgbToHex}, das klammert). */ +export function cmykToRgb({ c, m, y, k }: Cmyk): Rgb { + const cn = c / 100; + const mn = m / 100; + const yn = y / 100; + const kn = k / 100; + return { + r: 255 * (1 - cn) * (1 - kn), + g: 255 * (1 - mn) * (1 - kn), + b: 255 * (1 - yn) * (1 - kn), + }; +} + +/** Farbton 0..360, Sättigung/Helligkeit 0..100 (UI-Bereiche, nicht 0..1). */ +export interface Hsl { + h: number; + s: number; + l: number; +} +/** Farbton 0..360, Sättigung/Hellwert 0..100 (HSV/HSB). */ +export interface Hsv { + h: number; + s: number; + v: number; +} + +/** + * RGB → HSL. Bei unbunten Farben (Grau/Schwarz/Weiss) ist der Farbton + * mathematisch UNDEFINIERT und wird hier 0 — die UI hält den zuletzt + * eingestellten Farbton deshalb in einem eigenen Puffer, sonst würde der + * Regler beim Ziehen nach Schwarz/Weiss auf Rot zurückspringen + * (s. `ui/ColorMixer.tsx`). + */ +export function rgbToHsl({ r, g, b }: Rgb): Hsl { + const rn = r / 255; + const gn = g / 255; + const bn = b / 255; + const max = Math.max(rn, gn, bn); + const min = Math.min(rn, gn, bn); + const d = max - min; + const l = (max + min) / 2; + let h = 0; + if (d !== 0) { + if (max === rn) h = ((gn - bn) / d) % 6; + else if (max === gn) h = (bn - rn) / d + 2; + else h = (rn - gn) / d + 4; + h *= 60; + if (h < 0) h += 360; + } + const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1)); + return { h: Math.round(h), s: Math.round(s * 100), l: Math.round(l * 100) }; +} + +/** HSL → RGB (Kanäle 0..255, ungerundet — Aufrufer nutzt i. d. R. {@link rgbToHex}). */ +export function hslToRgb({ h, s, l }: Hsl): Rgb { + const sn = s / 100; + const ln = l / 100; + const c = (1 - Math.abs(2 * ln - 1)) * sn; + const hp = (((h % 360) + 360) % 360) / 60; + const x = c * (1 - Math.abs((hp % 2) - 1)); + const [r1, g1, b1] = + hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]; + const m = ln - c / 2; + return { r: (r1 + m) * 255, g: (g1 + m) * 255, b: (b1 + m) * 255 }; +} + +/** RGB → HSV/HSB (Farbton bei unbunten Farben 0, s. {@link rgbToHsl}). */ +export function rgbToHsv({ r, g, b }: Rgb): Hsv { + const rn = r / 255; + const gn = g / 255; + const bn = b / 255; + const max = Math.max(rn, gn, bn); + const min = Math.min(rn, gn, bn); + const d = max - min; + let h = 0; + if (d !== 0) { + if (max === rn) h = ((gn - bn) / d) % 6; + else if (max === gn) h = (bn - rn) / d + 2; + else h = (rn - gn) / d + 4; + h *= 60; + if (h < 0) h += 360; + } + return { + h: Math.round(h), + s: Math.round((max === 0 ? 0 : d / max) * 100), + v: Math.round(max * 100), + }; +} + +/** HSV/HSB → RGB (Kanäle 0..255, ungerundet). */ +export function hsvToRgb({ h, s, v }: Hsv): Rgb { + const sn = s / 100; + const vn = v / 100; + const c = vn * sn; + const hp = (((h % 360) + 360) % 360) / 60; + const x = c * (1 - Math.abs((hp % 2) - 1)); + const [r1, g1, b1] = + hp < 1 ? [c, x, 0] : hp < 2 ? [x, c, 0] : hp < 3 ? [0, c, x] : hp < 4 ? [0, x, c] : hp < 5 ? [x, 0, c] : [c, 0, x]; + const m = vn - c; + return { r: (r1 + m) * 255, g: (g1 + m) * 255, b: (b1 + m) * 255 }; +} + +export interface NamedColor { + name: string; + hex: string; +} + +/** + * Tango-Palette (freedesktop.org Tango Desktop Project) — die klassische, + * offen lizenzierte (Public Domain) Grafik-/Icon-Palette, die u. a. Inkscape + * lange Zeit als Standardpalette mitgeliefert hat und die auch in GIMP/ + * Scribus als Grundpalette auftaucht. 9 Farbfamilien × 3 Helligkeitsstufen + * (hell/mittel/dunkel) — anders als RAL für flächige Grafik/Illustration + * gedacht, nicht für Bauteil-/Fassadenfarben. Werte sind die kanonischen, + * überall identisch kursierenden Tango-Hex-Codes (keine Näherung wie bei + * RAL — dies IST die digitale Referenz, kein physisches Muster). + */ +export const TANGO_PALETTE: NamedColor[] = [ + { name: "Butter hell", hex: "#FCE94F" }, + { name: "Butter", hex: "#EDD400" }, + { name: "Butter dunkel", hex: "#C4A000" }, + { name: "Orange hell", hex: "#FCAF3E" }, + { name: "Orange", hex: "#F57900" }, + { name: "Orange dunkel", hex: "#CE5C00" }, + { name: "Chocolate hell", hex: "#E9B96E" }, + { name: "Chocolate", hex: "#C17D11" }, + { name: "Chocolate dunkel", hex: "#8F5902" }, + { name: "Chameleon hell", hex: "#8AE234" }, + { name: "Chameleon", hex: "#73D216" }, + { name: "Chameleon dunkel", hex: "#4E9A06" }, + { name: "Sky Blue hell", hex: "#729FCF" }, + { name: "Sky Blue", hex: "#3465A4" }, + { name: "Sky Blue dunkel", hex: "#204A87" }, + { name: "Plum hell", hex: "#AD7FA8" }, + { name: "Plum", hex: "#75507B" }, + { name: "Plum dunkel", hex: "#5C3566" }, + { name: "Scarlet Red hell", hex: "#EF2929" }, + { name: "Scarlet Red", hex: "#CC0000" }, + { name: "Scarlet Red dunkel", hex: "#A40000" }, + { name: "Aluminium 1", hex: "#EEEEEC" }, + { name: "Aluminium 2", hex: "#D3D7CF" }, + { name: "Aluminium 3", hex: "#BABDB6" }, + { name: "Aluminium 4", hex: "#888A85" }, + { name: "Aluminium 5", hex: "#555753" }, + { name: "Aluminium 6", hex: "#2E3436" }, +]; + +/** + * Material-Design-Palette (Google, offen dokumentiert/Apache-Doku-Lizenz) — + * je Farbfamilie die drei Referenz-Stufen 100/500/900 (hell/Basis/dunkel, + * dieselbe Hell/Basis/Dunkel-Logik wie {@link TANGO_PALETTE}) statt der + * vollen 10-Stufen-Skala jeder Familie — deckt die kanonischen, überall + * identisch kursierenden Werte ab, ohne 190 Einzelwerte aus dem Gedächtnis + * zu rekonstruieren. Für flächige UI-/Grafikfarben, kein Bauteilbezug. + */ +export const MATERIAL_PALETTE: NamedColor[] = [ + { name: "Red 100", hex: "#FFCDD2" }, + { name: "Red 500", hex: "#F44336" }, + { name: "Red 900", hex: "#B71C1C" }, + { name: "Pink 100", hex: "#F8BBD0" }, + { name: "Pink 500", hex: "#E91E63" }, + { name: "Pink 900", hex: "#880E4F" }, + { name: "Purple 100", hex: "#E1BEE7" }, + { name: "Purple 500", hex: "#9C27B0" }, + { name: "Purple 900", hex: "#4A148C" }, + { name: "Deep Purple 100", hex: "#D1C4E9" }, + { name: "Deep Purple 500", hex: "#673AB7" }, + { name: "Deep Purple 900", hex: "#311B92" }, + { name: "Indigo 100", hex: "#C5CAE9" }, + { name: "Indigo 500", hex: "#3F51B5" }, + { name: "Indigo 900", hex: "#1A237E" }, + { name: "Blue 100", hex: "#BBDEFB" }, + { name: "Blue 500", hex: "#2196F3" }, + { name: "Blue 900", hex: "#0D47A1" }, + { name: "Light Blue 100", hex: "#B3E5FC" }, + { name: "Light Blue 500", hex: "#03A9F4" }, + { name: "Light Blue 900", hex: "#01579B" }, + { name: "Cyan 100", hex: "#B2EBF2" }, + { name: "Cyan 500", hex: "#00BCD4" }, + { name: "Cyan 900", hex: "#006064" }, + { name: "Teal 100", hex: "#B2DFDB" }, + { name: "Teal 500", hex: "#009688" }, + { name: "Teal 900", hex: "#004D40" }, + { name: "Green 100", hex: "#C8E6C9" }, + { name: "Green 500", hex: "#4CAF50" }, + { name: "Green 900", hex: "#1B5E20" }, + { name: "Light Green 100", hex: "#DCEDC8" }, + { name: "Light Green 500", hex: "#8BC34A" }, + { name: "Light Green 900", hex: "#33691E" }, + { name: "Lime 100", hex: "#F0F4C3" }, + { name: "Lime 500", hex: "#CDDC39" }, + { name: "Lime 900", hex: "#827717" }, + { name: "Yellow 100", hex: "#FFF9C4" }, + { name: "Yellow 500", hex: "#FFEB3B" }, + { name: "Yellow 900", hex: "#F57F17" }, + { name: "Amber 100", hex: "#FFECB3" }, + { name: "Amber 500", hex: "#FFC107" }, + { name: "Amber 900", hex: "#FF6F00" }, + { name: "Orange 100", hex: "#FFE0B2" }, + { name: "Orange 500", hex: "#FF9800" }, + { name: "Orange 900", hex: "#E65100" }, + { name: "Deep Orange 100", hex: "#FFCCBC" }, + { name: "Deep Orange 500", hex: "#FF5722" }, + { name: "Deep Orange 900", hex: "#BF360C" }, + { name: "Brown 100", hex: "#D7CCC8" }, + { name: "Brown 500", hex: "#795548" }, + { name: "Brown 900", hex: "#3E2723" }, + { name: "Grey 100", hex: "#F5F5F5" }, + { name: "Grey 500", hex: "#9E9E9E" }, + { name: "Grey 900", hex: "#212121" }, + { name: "Blue Grey 100", hex: "#CFD8DC" }, + { name: "Blue Grey 500", hex: "#607D8B" }, + { name: "Blue Grey 900", hex: "#263238" }, +]; + +export interface RalColor { + /** Nummernteil ohne "RAL"-Präfix, z. B. "9016". */ + code: string; + /** Offizieller deutscher Name, z. B. "Verkehrsweiss". */ + name: string; + /** NÄHERUNGSWERT (s. Modul-Kommentar) — nicht farbverbindlich. */ + hex: string; +} + +/** + * Kuratierte Auswahl gängiger RAL-Classic-Farben (Fassaden-/Bauteilfarben, + * die in der Praxis am häufigsten vorkommen — Vollton- wie Metallic-Reihe + * ausgenommen). Die Hex-Werte sind NÄHERUNGEN, wie sie in praktisch jeder + * frei verfügbaren RAL-Umrechnungstabelle kursieren: RAL selbst ist ein + * physisches, lizenziertes Farbmuster-System (Fächer/Fächerkarte); eine + * bildschirm-exakte, farbverbindliche Wiedergabe ist ohne kalibriertes + * ICC-Profil UND die offizielle Karte grundsätzlich nicht möglich. Für die + * Bildschirm-Orientierung im Stift-/Farbfeld-Editor ausreichend, für die + * verbindliche Ausschreibung/Bemusterung gilt weiterhin die echte RAL-Karte + * (s. Hinweistext im UI, `pen.ralHint`). + */ +export const RAL_CLASSIC: RalColor[] = [ + { code: "1000", name: "Grünbeige", hex: "#BEBD7F" }, + { code: "1001", name: "Beige", hex: "#C2B078" }, + { code: "1002", name: "Sandgelb", hex: "#C6A664" }, + { code: "1003", name: "Signalgelb", hex: "#E5BE01" }, + { code: "1004", name: "Goldgelb", hex: "#CDA434" }, + { code: "1005", name: "Honiggelb", hex: "#A98307" }, + { code: "1006", name: "Maisgelb", hex: "#E4A010" }, + { code: "1007", name: "Narzissengelb", hex: "#DC9D00" }, + { code: "1011", name: "Braunbeige", hex: "#8A6642" }, + { code: "1013", name: "Perlweiss", hex: "#EAE6CA" }, + { code: "1014", name: "Elfenbein", hex: "#DED6B1" }, + { code: "1015", name: "Hellelfenbein", hex: "#E6D690" }, + { code: "1017", name: "Safrangelb", hex: "#F6A950" }, + { code: "1019", name: "Graubeige", hex: "#A48F7A" }, + { code: "1021", name: "Rapsgelb", hex: "#F7BA0B" }, + { code: "1023", name: "Verkehrsgelb", hex: "#FAD201" }, + { code: "1028", name: "Melonengelb", hex: "#E2A300" }, + { code: "1032", name: "Ginstergelb", hex: "#D6AE01" }, + { code: "2000", name: "Gelborange", hex: "#ED760E" }, + { code: "2001", name: "Rotorange", hex: "#C93C20" }, + { code: "2002", name: "Blutorange", hex: "#CB2821" }, + { code: "2003", name: "Pastellorange", hex: "#FF7514" }, + { code: "2004", name: "Reinorange", hex: "#F44611" }, + { code: "2009", name: "Verkehrsorange", hex: "#E25303" }, + { code: "2010", name: "Signalorange", hex: "#D4652F" }, + { code: "2011", name: "Tieforange", hex: "#E05C1E" }, + { code: "3000", name: "Feuerrot", hex: "#AB2524" }, + { code: "3001", name: "Signalrot", hex: "#A52019" }, + { code: "3002", name: "Karminrot", hex: "#A2231D" }, + { code: "3003", name: "Rubinrot", hex: "#9B111E" }, + { code: "3004", name: "Purpurrot", hex: "#75151E" }, + { code: "3005", name: "Weinrot", hex: "#5E2129" }, + { code: "3007", name: "Schwarzrot", hex: "#412227" }, + { code: "3009", name: "Oxidrot", hex: "#642424" }, + { code: "3011", name: "Braunrot", hex: "#781F19" }, + { code: "3013", name: "Tomatenrot", hex: "#A12312" }, + { code: "3018", name: "Erdbeerrot", hex: "#D53032" }, + { code: "3020", name: "Verkehrsrot", hex: "#CC0605" }, + { code: "3022", name: "Lachsrot", hex: "#D95030" }, + { code: "3027", name: "Himbeerrot", hex: "#B32821" }, + { code: "4001", name: "Rotlila", hex: "#6D3F5B" }, + { code: "4002", name: "Rotviolett", hex: "#922B3E" }, + { code: "4003", name: "Erikaviolett", hex: "#DE4C8A" }, + { code: "4005", name: "Blaulila", hex: "#6C4675" }, + { code: "4006", name: "Verkehrspurpur", hex: "#A03472" }, + { code: "4007", name: "Purpurviolett", hex: "#4A192C" }, + { code: "4008", name: "Signalviolett", hex: "#924E7D" }, + { code: "4009", name: "Pastellviolett", hex: "#8673A1" }, + { code: "5000", name: "Violettblau", hex: "#354D73" }, + { code: "5001", name: "Grünblau", hex: "#1F3438" }, + { code: "5002", name: "Ultramarinblau", hex: "#20214F" }, + { code: "5003", name: "Saphirblau", hex: "#1D1E33" }, + { code: "5005", name: "Signalblau", hex: "#1E2460" }, + { code: "5007", name: "Brillantblau", hex: "#3E5F8A" }, + { code: "5008", name: "Graublau", hex: "#26252D" }, + { code: "5009", name: "Azurblau", hex: "#025669" }, + { code: "5010", name: "Enzianblau", hex: "#0E294B" }, + { code: "5011", name: "Stahlblau", hex: "#231A24" }, + { code: "5012", name: "Lichtblau", hex: "#3B83BD" }, + { code: "5013", name: "Kobaltblau", hex: "#1E213D" }, + { code: "5014", name: "Taubenblau", hex: "#606E8C" }, + { code: "5015", name: "Himmelblau", hex: "#2271B3" }, + { code: "5017", name: "Verkehrsblau", hex: "#063971" }, + { code: "5018", name: "Türkisblau", hex: "#3F888F" }, + { code: "5019", name: "Capriblau", hex: "#1B5583" }, + { code: "5020", name: "Ozeanblau", hex: "#1D334A" }, + { code: "5021", name: "Wasserblau", hex: "#256D7B" }, + { code: "5022", name: "Nachtblau", hex: "#252850" }, + { code: "5024", name: "Pastellblau", hex: "#5D9B9B" }, + { code: "6000", name: "Patinagrün", hex: "#327662" }, + { code: "6001", name: "Smaragdgrün", hex: "#287233" }, + { code: "6002", name: "Laubgrün", hex: "#2D572C" }, + { code: "6003", name: "Olivgrün", hex: "#424632" }, + { code: "6004", name: "Blaugrün", hex: "#1F3A3D" }, + { code: "6005", name: "Moosgrün", hex: "#2F4538" }, + { code: "6006", name: "Grauoliv", hex: "#3E3B32" }, + { code: "6007", name: "Flaschengrün", hex: "#343B29" }, + { code: "6009", name: "Tannengrün", hex: "#31372B" }, + { code: "6010", name: "Grasgrün", hex: "#35682D" }, + { code: "6011", name: "Resedagrün", hex: "#587246" }, + { code: "6012", name: "Schwarzgrün", hex: "#343E40" }, + { code: "6013", name: "Schilfgrün", hex: "#6C7156" }, + { code: "6014", name: "Gelboliv", hex: "#47402E" }, + { code: "6015", name: "Schwarzoliv", hex: "#3B3C36" }, + { code: "6016", name: "Türkisgrün", hex: "#1E5945" }, + { code: "6017", name: "Maigrün", hex: "#4C9141" }, + { code: "6018", name: "Gelbgrün", hex: "#57A639" }, + { code: "6019", name: "Weissgrün", hex: "#BDECB6" }, + { code: "6020", name: "Chromoxidgrün", hex: "#2E3A23" }, + { code: "6021", name: "Blassgrün", hex: "#89AC76" }, + { code: "6024", name: "Verkehrsgrün", hex: "#008351" }, + { code: "6025", name: "Farngrün", hex: "#4D5D53" }, + { code: "6026", name: "Opalgrün", hex: "#005D52" }, + { code: "6027", name: "Lichtgrün", hex: "#81C0BB" }, + { code: "6028", name: "Kieferngrün", hex: "#2D4A34" }, + { code: "6029", name: "Minzgrün", hex: "#007243" }, + { code: "6032", name: "Signalgrün", hex: "#0F8558" }, + { code: "6033", name: "Minttürkis", hex: "#478A84" }, + { code: "6034", name: "Pastelltürkis", hex: "#7FB0B2" }, + { code: "7000", name: "Fehgrau", hex: "#7E8B92" }, + { code: "7001", name: "Silbergrau", hex: "#8F999F" }, + { code: "7002", name: "Olivgrau", hex: "#817F68" }, + { code: "7003", name: "Moosgrau", hex: "#7A7B6D" }, + { code: "7004", name: "Signalgrau", hex: "#9EA0A1" }, + { code: "7005", name: "Mausgrau", hex: "#6B716F" }, + { code: "7006", name: "Beigegrau", hex: "#756F61" }, + { code: "7008", name: "Khakigrau", hex: "#6A5F31" }, + { code: "7009", name: "Grüngrau", hex: "#4D5645" }, + { code: "7010", name: "Zeltgrau", hex: "#4C514A" }, + { code: "7011", name: "Eisengrau", hex: "#434B4D" }, + { code: "7012", name: "Basaltgrau", hex: "#4E5754" }, + { code: "7013", name: "Braungrau", hex: "#4E5541" }, + { code: "7015", name: "Schiefergrau", hex: "#434750" }, + { code: "7016", name: "Anthrazitgrau", hex: "#293133" }, + { code: "7021", name: "Schwarzgrau", hex: "#23282B" }, + { code: "7022", name: "Umbragrau", hex: "#332F2C" }, + { code: "7023", name: "Betongrau", hex: "#686C5E" }, + { code: "7024", name: "Graphitgrau", hex: "#474A51" }, + { code: "7026", name: "Granitgrau", hex: "#2F353B" }, + { code: "7030", name: "Steingrau", hex: "#8B8C7A" }, + { code: "7031", name: "Blaugrau", hex: "#474B4E" }, + { code: "7032", name: "Kieselgrau", hex: "#B8B799" }, + { code: "7033", name: "Zementgrau", hex: "#7D8471" }, + { code: "7034", name: "Gelbgrau", hex: "#92926F" }, + { code: "7035", name: "Lichtgrau", hex: "#D7D7D7" }, + { code: "7036", name: "Platingrau", hex: "#969992" }, + { code: "7037", name: "Staubgrau", hex: "#7D7F7D" }, + { code: "7038", name: "Achatgrau", hex: "#B5B8B1" }, + { code: "7039", name: "Quarzgrau", hex: "#6C6960" }, + { code: "7040", name: "Fenstergrau", hex: "#9DA1AA" }, + { code: "7042", name: "Verkehrsgrau A", hex: "#8D948D" }, + { code: "7043", name: "Verkehrsgrau B", hex: "#4E5452" }, + { code: "7044", name: "Seidengrau", hex: "#CAC4B0" }, + { code: "7045", name: "Telegrau 1", hex: "#909090" }, + { code: "7046", name: "Telegrau 2", hex: "#82898E" }, + { code: "7047", name: "Telegrau 4", hex: "#D0D0D0" }, + { code: "7048", name: "Perlgrau", hex: "#898176" }, + { code: "8000", name: "Grünbraun", hex: "#826C34" }, + { code: "8001", name: "Ockerbraun", hex: "#955F20" }, + { code: "8002", name: "Signalbraun", hex: "#6C3B2A" }, + { code: "8003", name: "Lehmbraun", hex: "#734222" }, + { code: "8004", name: "Kupferbraun", hex: "#8E402A" }, + { code: "8007", name: "Rehbraun", hex: "#59351F" }, + { code: "8008", name: "Olivbraun", hex: "#6F4F28" }, + { code: "8011", name: "Nussbraun", hex: "#5A3A29" }, + { code: "8012", name: "Rotbraun", hex: "#592321" }, + { code: "8014", name: "Sepiabraun", hex: "#382C1E" }, + { code: "8015", name: "Kastanienbraun", hex: "#633A34" }, + { code: "8016", name: "Mahagonibraun", hex: "#4C2F27" }, + { code: "8017", name: "Schokoladenbraun", hex: "#442F29" }, + { code: "8019", name: "Graubraun", hex: "#3D3635" }, + { code: "8022", name: "Schwarzbraun", hex: "#212121" }, + { code: "8023", name: "Orangebraun", hex: "#A65E2E" }, + { code: "8024", name: "Beigebraun", hex: "#79553D" }, + { code: "8025", name: "Blassbraun", hex: "#755C48" }, + { code: "8028", name: "Terrabraun", hex: "#4E3B31" }, + { code: "9001", name: "Cremeweiss", hex: "#FDF4E3" }, + { code: "9002", name: "Grauweiss", hex: "#E7EBDA" }, + { code: "9003", name: "Signalweiss", hex: "#F4F4F4" }, + { code: "9004", name: "Signalschwarz", hex: "#282828" }, + { code: "9005", name: "Tiefschwarz", hex: "#0A0A0A" }, + { code: "9006", name: "Weissaluminium", hex: "#A5A5A5" }, + { code: "9007", name: "Graualuminium", hex: "#8F8F8F" }, + { code: "9010", name: "Reinweiss", hex: "#FFFFFF" }, + { code: "9011", name: "Graphitschwarz", hex: "#1C1C1C" }, + { code: "9016", name: "Verkehrsweiss", hex: "#F6F6F6" }, + { code: "9017", name: "Verkehrsschwarz", hex: "#1E1E1E" }, + { code: "9018", name: "Papyrusweiss", hex: "#D7D7D7" }, +]; diff --git a/src/model/colorIcc.test.ts b/src/model/colorIcc.test.ts new file mode 100644 index 0000000..477c9c6 --- /dev/null +++ b/src/model/colorIcc.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { initIccColorManagement, iccColorManagementAvailable, rgbToCmykIcc, cmykToRgbIcc } from "./colorIcc"; + +// `@tauri-apps/plugin-fs`s `readFile` braucht die echte Tauri-IPC-Bridge +// (`window.__TAURI_INTERNALS__`), die es in vitest/Node NICHT gibt — hier +// kann also nur der GRACEFUL-FALLBACK-Vertrag geprüft werden (kein Wurf, +// sauberes `false`/`undefined`), nicht die echte ICC-Umrechnung selbst. Das +// ist dieselbe Grenze wie bei anderen Tauri-Runtime-Features dieser Codebase +// (s. render3d/Wasm3DViewport) — die echte Umrechnung gegen macOS' Generic +// CMYK Profile wird in der laufenden Tauri-App von Hand geprüft, nicht hier. +describe("colorIcc — Fallback-Vertrag ausserhalb der Tauri-Runtime", () => { + it("initIccColorManagement wirft nie, liefert sauber false ohne Tauri-Bridge", async () => { + const ok = await initIccColorManagement(); + expect(ok).toBe(false); + expect(iccColorManagementAvailable()).toBe(false); + }); + + it("rgbToCmykIcc/cmykToRgbIcc liefern undefined statt zu werfen, wenn nicht initialisiert", () => { + expect(rgbToCmykIcc({ r: 255, g: 0, b: 0 })).toBeUndefined(); + expect(cmykToRgbIcc({ c: 0, m: 100, y: 100, k: 0 })).toBeUndefined(); + }); +}); diff --git a/src/model/colorIcc.ts b/src/model/colorIcc.ts new file mode 100644 index 0000000..31d0e12 --- /dev/null +++ b/src/model/colorIcc.ts @@ -0,0 +1,113 @@ +// Echtes ICC-Farbmanagement für den RGB/CMYK-Mischer (`ui/ColorMixer.tsx`) — +// nutzt `lcms-wasm` (WASM-Portierung der echten Little-CMS-Bibliothek, MIT- +// lizenziert, dieselbe Engine, die auch professionelle Druck-Software +// verwendet) gegen das von macOS mitgelieferte „Generic CMYK Profile" +// (ColorSync, `/System/Library/ColorSync/Profiles/`) als Referenzprofil. +// +// Bewusst KEIN mit der App gebündeltes/verteiltes Farbprofil: die Datei wird +// zur LAUFZEIT vom Betriebssystem gelesen (nur dieser eine, fest verdrahtete +// Pfad ist in `src-tauri/capabilities/default.json` per `fs:allow-read-file` +// freigegeben), nie kopiert oder mit dem App-Bundle verteilt — damit stellt +// sich die Lizenz-/Weitergabefrage für ein Fremd-Farbprofil (z. B. Adobes +// oder ECIs kommerzielle CMYK-Referenzprofile) gar nicht erst. +// +// Nur auf macOS verfügbar (ColorSync-Pfad existiert nur dort). Überall sonst +// — Windows/Linux, oder falls die Datei aus irgendeinem Grund fehlt/das +// WASM nicht lädt — liefern die Funktionen unten `undefined`; der Aufrufer +// (`ui/ColorMixer.tsx`) fällt dann auf die vereinfachte Formel in +// `model/color.ts` zurück (progressive enhancement, kein harter Fehler). +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import { readFile } from "@tauri-apps/plugin-fs"; +import type { LcmsInstance } from "lcms-wasm"; +import type { Cmyk, Rgb } from "./color"; + +const MACOS_GENERIC_CMYK_PROFILE = "/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"; + +interface LcmsHandles { + lcms: LcmsInstance; + toCmyk: number; + toRgb: number; +} + +let handles: LcmsHandles | null = null; +let initPromise: Promise | null = null; + +/** + * Lädt `lcms-wasm` + das System-CMYK-Profil EINMALIG (Ergebnis gecacht, + * mehrfacher Aufruf gibt dasselbe Promise zurück). Nach erfolgreichem + * Abschluss sind {@link rgbToCmykIcc}/{@link cmykToRgbIcc} synchron nutzbar + * (wichtig fürs Mischer-UI: Regler ziehen darf nicht pro Schritt auf ein + * Promise warten). `false` bei jedem Fehler (fehlende Datei, kein macOS, + * WASM-Ladefehler) — kein Reject, der Aufrufer entscheidet selbst über den + * Fallback. + */ +export function initIccColorManagement(): Promise { + if (!initPromise) initPromise = doInit(); + return initPromise; +} + +async function doInit(): Promise { + try { + const [lcmsModule, wasmUrlModule, profileBytes] = await Promise.all([ + import("lcms-wasm"), + import("lcms-wasm/dist/lcms.wasm?url"), + readFile(MACOS_GENERIC_CMYK_PROFILE), + ]); + const wasmUrl = (wasmUrlModule as { default: string }).default; + const lcms = await lcmsModule.instantiate({ locateFile: () => wasmUrl }); + + const cmykProfile = lcms.cmsOpenProfileFromMem(profileBytes, profileBytes.byteLength); + const srgbProfile = lcms.cmsCreate_sRGBProfile(); + if (!cmykProfile || !srgbProfile) return false; + + // Relative Colorimetric — Standard-Intent für RGB<->CMYK-Umwandlung in + // gängiger DTP-/Druckvorstufen-Software (z. B. Adobe-Voreinstellung). + const toCmyk = lcms.cmsCreateTransform( + srgbProfile, + lcmsModule.TYPE_RGB_8, + cmykProfile, + lcmsModule.TYPE_CMYK_8, + lcmsModule.INTENT_RELATIVE_COLORIMETRIC, + 0, + ); + const toRgb = lcms.cmsCreateTransform( + cmykProfile, + lcmsModule.TYPE_CMYK_8, + srgbProfile, + lcmsModule.TYPE_RGB_8, + lcmsModule.INTENT_RELATIVE_COLORIMETRIC, + 0, + ); + if (!toCmyk || !toRgb) return false; + + handles = { lcms, toCmyk, toRgb }; + return true; + } catch { + return false; + } +} + +/** `true`, sobald {@link initIccColorManagement} erfolgreich abgeschlossen hat. */ +export function iccColorManagementAvailable(): boolean { + return handles !== null; +} + +const pctFrom255 = (v: number) => Math.round((v / 255) * 100); +const to255FromPct = (pct: number) => Math.round((pct / 100) * 255); + +/** Echte ICC-Umwandlung RGB→CMYK (0..100 je Kanal). `undefined`, wenn nicht initialisiert. */ +export function rgbToCmykIcc(rgb: Rgb): Cmyk | undefined { + if (!handles) return undefined; + const out = handles.lcms.cmsDoTransform(handles.toCmyk, [rgb.r, rgb.g, rgb.b], 1); + return { c: pctFrom255(out[0]), m: pctFrom255(out[1]), y: pctFrom255(out[2]), k: pctFrom255(out[3]) }; +} + +/** Echte ICC-Umwandlung CMYK→RGB. `undefined`, wenn nicht initialisiert. */ +export function cmykToRgbIcc(cmyk: Cmyk): Rgb | undefined { + if (!handles) return undefined; + const input = [to255FromPct(cmyk.c), to255FromPct(cmyk.m), to255FromPct(cmyk.y), to255FromPct(cmyk.k)]; + const out = handles.lcms.cmsDoTransform(handles.toRgb, input, 1); + return { r: out[0], g: out[1], b: out[2] }; +} diff --git a/src/model/dimension.test.ts b/src/model/dimension.test.ts new file mode 100644 index 0000000..1bf7e55 --- /dev/null +++ b/src/model/dimension.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; +import { + DIM_DEFAULTS_MM, + dimTextFrame, + dimTextOffsetFromPoint, + dimTextPos, + mmToModel, + modelToMm, +} from "./dimension"; + +const A = { x: 0, y: 0 }; +const B = { x: 4, y: 0 }; +/** Schrifthöhe in MODELL-Metern bei 1:50 — die Helfer rechnen in Modellmass. */ +const H = mmToModel(DIM_DEFAULTS_MM.textHeight, 50); + +describe("dimTextFrame", () => { + it("Standardlage: mittig über der Masslinie (Offset eingerechnet)", () => { + const f = dimTextFrame(A, B, 1, H); + expect(f.base.x).toBeCloseTo(2, 9); + expect(f.base.y).toBeCloseTo(1 + H * 0.6, 9); + }); + + it("Leserichtung nie kopfüber — auch bei rückwärts laufender Kette", () => { + const forward = dimTextFrame(A, B, 0, H); + const backward = dimTextFrame(B, A, 0, H); + expect(forward.read.x).toBeCloseTo(1, 9); + // b→a zeigt nach −X; die Zahl dreht sich trotzdem in die Leserichtung. + expect(backward.read.x).toBeCloseTo(1, 9); + }); +}); + +describe("dimTextPos", () => { + it("ohne Versatz identisch zur Standardlage", () => { + const f = dimTextFrame(A, B, 0.5, H); + const p = dimTextPos(A, B, 0.5, H, undefined); + expect(p).toEqual(f.base); + }); + + it("Versatz wirkt entlang der Leserichtung und quer dazu", () => { + const p = dimTextPos(A, B, 0, H, { along: 1, perp: 2 }); + const f = dimTextFrame(A, B, 0, H); + expect(p.x).toBeCloseTo(f.base.x + 1, 9); + expect(p.y).toBeCloseTo(f.base.y + 2, 9); + }); +}); + +describe("dimTextOffsetFromPoint — Verschieben mit Einrasten", () => { + it("nahe der Standardlage rastet BEIDES auf 0 ein", () => { + const f = dimTextFrame(A, B, 0, H); + const near = { x: f.base.x + H * 0.2, y: f.base.y - H * 0.2 }; + expect(dimTextOffsetFromPoint(A, B, 0, H, near)).toEqual({ along: 0, perp: 0 }); + }); + + it("die Achsen rasten UNABHÄNGIG ein (seitlich verschoben, Höhe exakt Standard)", () => { + const f = dimTextFrame(A, B, 0, H); + const pt = { x: f.base.x + 1.5, y: f.base.y + H * 0.1 }; + const o = dimTextOffsetFromPoint(A, B, 0, H, pt); + expect(o.along).toBeCloseTo(1.5, 9); + expect(o.perp).toBe(0); + }); + + it("ausserhalb des Fangbereichs bleibt der gezogene Wert erhalten", () => { + const f = dimTextFrame(A, B, 0, H); + const pt = { x: f.base.x + 0.8, y: f.base.y + 0.6 }; + const o = dimTextOffsetFromPoint(A, B, 0, H, pt); + expect(o.along).toBeCloseTo(0.8, 9); + expect(o.perp).toBeCloseTo(0.6, 9); + }); + + it("Rundreise: gezogene Position → Versatz → Position ergibt wieder den Punkt", () => { + const pt = { x: 3.1, y: 1.4 }; + const o = dimTextOffsetFromPoint(A, B, 0.5, H, pt); + const back = dimTextPos(A, B, 0.5, H, o); + expect(back.x).toBeCloseTo(pt.x, 9); + expect(back.y).toBeCloseTo(pt.y, 9); + }); +}); + +describe("mmToModel/modelToMm — Papier-mm ↔ Modellmass", () => { + it("bei 1:50 entsprechen die Defaults exakt den früheren festen Modellwerten", () => { + expect(mmToModel(DIM_DEFAULTS_MM.gap, 50)).toBeCloseTo(0.05, 12); + expect(mmToModel(DIM_DEFAULTS_MM.overshoot, 50)).toBeCloseTo(0.05, 12); + expect(mmToModel(DIM_DEFAULTS_MM.tickLen, 50)).toBeCloseTo(0.15, 12); + expect(mmToModel(DIM_DEFAULTS_MM.textHeight, 50)).toBeCloseTo(0.2, 12); + }); + + it("derselbe Papierwert ergibt bei anderem Massstab andere Modellmasse", () => { + // 2 mm Papier: bei 1:50 = 10 cm im Modell, bei 1:100 = 20 cm. + expect(mmToModel(2, 50)).toBeCloseTo(0.1, 12); + expect(mmToModel(2, 100)).toBeCloseTo(0.2, 12); + }); + + it("Rundreise mm → Modell → mm ist verlustfrei", () => { + for (const scale of [20, 50, 100, 200]) { + expect(modelToMm(mmToModel(2.5, scale), scale)).toBeCloseTo(2.5, 12); + } + }); +}); diff --git a/src/model/dimension.ts b/src/model/dimension.ts new file mode 100644 index 0000000..a4b38a5 --- /dev/null +++ b/src/model/dimension.ts @@ -0,0 +1,115 @@ +// Gemeinsame Geometrie der Bemassung (SIA 400 B.5.3) — von BEIDEN Seiten +// genutzt: vom Rendering (`plan/generatePlan/drawing2d.ts`) und von den +// Griffen (`state/projectSlice.ts`). Bewusst hier statt doppelt gerechnet: +// sonst driften Masszahl-Position und Masszahl-Griff auseinander, sobald eine +// der beiden Stellen angepasst wird. +// +// EINHEITEN: die Bemassungs-Feinheiten sind PAPIER-MILLIMETER (so denkt die +// Zeichnungsnorm: „Überstand 2 mm", unabhängig vom Massstab). Umgerechnet +// wird mit dem Massstab des jeweiligen Plans (`mmToModel`) — die Funktionen +// hier unten rechnen dann in Modell-Metern, weil die Plan-Geometrie so +// vorliegt. Der Plan wird je Ziel (Bildschirm, Layout-Viewport) EIGENS +// erzeugt (s. `LayoutSheet.tsx`), der Massstab ist zur Erzeugungszeit also +// bekannt und eindeutig. + +import type { Vec2 } from "./types"; + +/** + * Defaults in PAPIER-MILLIMETERN (übliche Zeichnungswerte; entsprechen bei + * 1:50 genau den früheren festen Modellwerten 0.05/0.05/0.15/0.2 m). + */ +export const DIM_DEFAULTS_MM = { + gap: 1, + overshoot: 1, + tickLen: 3, + textHeight: 4, +} as const; + +/** Standard-Massstab, wenn ein Aufrufer keinen mitgibt (1:100, üblichster Planmassstab). */ +export const DEFAULT_SCALE_DENOMINATOR = 100; + +/** Papier-Millimeter → Modell-Meter beim Massstab 1:`scaleDenominator`. */ +export function mmToModel(mm: number, scaleDenominator: number): number { + return (mm / 1000) * scaleDenominator; +} + +/** Modell-Meter → Papier-Millimeter (Umkehrung von {@link mmToModel}). */ +export function modelToMm(m: number, scaleDenominator: number): number { + return (m * 1000) / scaleDenominator; +} + +/** + * Lage der Masszahl EINES Segments in ihrer Standardstellung plus die beiden + * Achsen, in denen ein Nutzer-Versatz (`textOffsets`) gemessen wird: + * `read` = Leserichtung der Zahl, `up` = quer dazu (von der Masslinie weg). + * Die Leserichtung ist nie kopfüber (wie beim Rendern), damit „nach oben" + * für den Nutzer oben bleibt, egal wie die Kette gedreht ist. + */ +export function dimTextFrame( + a: Vec2, + b: Vec2, + offset: number, + textHeight: number, +): { base: Vec2; read: Vec2; up: Vec2; angle: number } { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len = Math.hypot(dx, dy) || 1; + const nx = -dy / len; + const ny = dx / len; + const mid: Vec2 = { + x: (a.x + b.x) / 2 + nx * offset, + y: (a.y + b.y) / 2 + ny * offset, + }; + let angle = Math.atan2(dy, dx); + if (Math.cos(angle) < 0) angle += Math.PI; + const read: Vec2 = { x: Math.cos(angle), y: Math.sin(angle) }; + const up: Vec2 = { x: -Math.sin(angle), y: Math.cos(angle) }; + return { + base: { x: mid.x + up.x * textHeight * 0.6, y: mid.y + up.y * textHeight * 0.6 }, + read, + up, + angle, + }; +} + +/** Endgültige Position der Masszahl inkl. Nutzer-Versatz. */ +export function dimTextPos( + a: Vec2, + b: Vec2, + offset: number, + textHeight: number, + textOffset: { along: number; perp: number } | undefined, +): Vec2 { + const f = dimTextFrame(a, b, offset, textHeight); + const o = textOffset ?? { along: 0, perp: 0 }; + return { + x: f.base.x + f.read.x * o.along + f.up.x * o.perp, + y: f.base.y + f.read.y * o.along + f.up.y * o.perp, + }; +} + +/** + * Zerlegt eine gezogene Masszahl-Position in den Versatz (along/perp) und + * lässt ihn dabei EINRASTEN: nahe der Standardlage wird die jeweilige Achse + * exakt auf 0 gezogen (Nutzer-Wunsch „schiebbar, aber trotzdem einrastend"). + * Beide Achsen rasten unabhängig — man kann die Zahl also seitlich + * verschieben und trotzdem exakt auf Standardhöhe bleiben. + */ +export function dimTextOffsetFromPoint( + a: Vec2, + b: Vec2, + offset: number, + textHeight: number, + pt: Vec2, +): { along: number; perp: number } { + const f = dimTextFrame(a, b, offset, textHeight); + const vx = pt.x - f.base.x; + const vy = pt.y - f.base.y; + const snap = textHeight * 0.5; // Fangbereich ≈ halbe Schrifthöhe + const along = vx * f.read.x + vy * f.read.y; + const perp = vx * f.up.x + vy * f.up.y; + return { + along: Math.abs(along) < snap ? 0 : along, + perp: Math.abs(perp) < snap ? 0 : perp, + }; +} diff --git a/src/model/geoRebase.ts b/src/model/geoRebase.ts index f0e7131..1aed1d3 100644 --- a/src/model/geoRebase.ts +++ b/src/model/geoRebase.ts @@ -98,6 +98,7 @@ export function translateProject(project: Project, dx: number, dy: number): Proj switch (g.shape) { case "line": case "xline": + case "ray": return { ...d, geom: { ...g, a: shift(g.a, dx, dy), b: shift(g.b, dx, dy) } }; case "polyline": return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } }; @@ -117,6 +118,12 @@ export function translateProject(project: Project, dx: number, dy: number): Proj return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } }; case "kote": return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; + case "detailref": + return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; + case "scalebar": + return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; + case "pointmarker": + return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } }; case "text": return { ...d, @@ -124,6 +131,7 @@ export function translateProject(project: Project, dx: number, dy: number): Proj ...g, at: shift(g.at, dx, dy), ...(g.leaderTarget ? { leaderTarget: shift(g.leaderTarget, dx, dy) } : {}), + ...(g.leaderBendPoints ? { leaderBendPoints: shiftAll(g.leaderBendPoints, dx, dy) } : {}), ...(g.pathPts ? { pathPts: shiftAll(g.pathPts, dx, dy) } : {}), }, }; diff --git a/src/model/lcms-wasm.d.ts b/src/model/lcms-wasm.d.ts new file mode 100644 index 0000000..2db42f4 --- /dev/null +++ b/src/model/lcms-wasm.d.ts @@ -0,0 +1,40 @@ +// Ambient-Deklarationen für `lcms-wasm` (liefert selbst keine Typen) + den +// per Vite `?url` aufgelösten Pfad zu seiner `.wasm`-Datei. Nur die +// Teilmenge der API, die `model/colorIcc.ts` tatsächlich nutzt — die +// Bibliothek selbst ist ein sehr dünner Emscripten-Wrapper um Little-CMS +// mit deutlich mehr Funktionen/Konstanten, s. node_modules/lcms-wasm/dist/ +// lcms.js für die vollständige (untypisierte) Oberfläche. + +declare module "lcms-wasm" { + /** Low-Level-WASM-Instanz (Handles sind einfache Zahlen, wie in Little-CMS selbst). */ + export interface LcmsInstance { + cmsOpenProfileFromMem(bytes: Uint8Array, size: number): number; + cmsCreate_sRGBProfile(): number; + cmsCloseProfile(profile: number): void; + cmsCreateTransform( + inputProfile: number, + inputFormat: number, + outputProfile: number, + outputFormat: number, + intent: number, + flags: number, + ): number; + cmsDeleteTransform(transform: number): void; + /** `size` = Anzahl Pixel (nicht Bytes) — Kanalzahl ergibt sich aus dem Transform-Format. */ + cmsDoTransform(transform: number, input: number[], size: number): Uint8Array | Float32Array; + } + + export function instantiate(opts?: { + locateFile?: (filename: string) => string; + }): Promise; + + export const TYPE_RGB_8: number; + export const TYPE_CMYK_8: number; + export const INTENT_RELATIVE_COLORIMETRIC: number; +} + +declare module "lcms-wasm/dist/lcms.wasm?url" { + /** Von Vite aufgelöste URL der WASM-Datei (gehashtes Asset im Build). */ + const url: string; + export default url; +} diff --git a/src/model/types.ts b/src/model/types.ts index 3dc006e..9e19584 100644 --- a/src/model/types.ts +++ b/src/model/types.ts @@ -16,7 +16,7 @@ export type Vec2 = { x: number; y: number }; import type { SiaCategory } from "../geometry/roomArea"; export type { SiaCategory } from "../geometry/roomArea"; // Rich-Text-Dokument für den Raum-Stempel (frei editierbarer Teil). -import type { RichTextDoc, Align, Marks } from "../text/richText"; +import type { RichTextDoc, Align, Marks, TextStylePreset } from "../text/richText"; export type { RichTextDoc } from "../text/richText"; // Ansichts-Enums für Ausschnitte/View-Snapshots (Ansichtstyp, Kamera-Preset, // Detailgrad). Rein type-only importiert — zur Laufzeit erased, kein Zyklus @@ -70,6 +70,45 @@ export interface PenSet { pens: Record; } +/** + * Eine benutzerdefinierte Farbpalette (Farbmischer → „Diese Farbe + * speichern", `ui/FreeColorPicker.tsx`). Anders als Stiftsätze: reine + * Farb-Sammlung ohne Kopplungs-/Baking-Semantik — ein Klick auf einen + * Swatch übernimmt einfach den Hex-Wert wie bei den mitgelieferten + * Paletten (Einfach/Tango/Material/RAL), nur eben frei befüllbar. Mehrere + * Paletten können nebeneinander existieren (z. B. „Fassade Projekt X", + * „Innenausbau"); keine ist „aktiv" — alle sind gleichzeitig über den + * Paletten-Umschalter erreichbar. + */ +export interface CustomPalette { + id: string; + name: string; + /** Hex-Werte, Reihenfolge = Anzeigereihenfolge im Raster. */ + colors: string[]; + /** + * Im Farbwahl-Popover anzeigen? Fehlt das Feld, gilt `true` (sichtbar) — + * so bleiben bestehende Projekte unverändert. Umschaltbar im Ressourcen- + * Manager (Tab „Paletten"), damit die Bank-Leiste im Popover kurz bleibt. + */ + visible?: boolean; +} + +/** + * Sichtbarkeit der MITGELIEFERTEN Farbpaletten-Bänke im Farbwahl-Popover + * (`ui/FreeColorPicker.tsx`). Fehlt ein Schlüssel (oder das ganze Objekt), + * gilt die Bank als sichtbar — nur ein explizites `false` blendet sie aus + * (z. B. RAL, wenn im Projekt nie mit Fassadenfarben gearbeitet wird). + */ +export interface BuiltinPaletteBanks { + simple?: boolean; + tango?: boolean; + material?: boolean; + ral?: boolean; +} + +/** Schlüssel einer mitgelieferten Palette-Bank (s. {@link BuiltinPaletteBanks}). */ +export type BuiltinPaletteBank = keyof BuiltinPaletteBanks; + export interface LineStyle { id: string; name: string; @@ -144,15 +183,23 @@ export interface HatchStyle { name: string; /** * Schraffur-Typ (additiv, Default `undefined` ⇒ "vector"): - * • "vector" — Musterlinien (die bestehenden `pattern`/`scale`/`angle`/ + * • "vector" — Musterlinien (die bestehenden `pattern`/`scale`/`angle`/ * `relativeToWall`/`lineStyleId` sind die Vektor-Parameter). Untermodus * über `lines` (parallel vs. random). - * • "image" — ein Bild wird als Muster (Pattern-Fill) geladen; Parameter in + * • "image" — ein Bild wird als Muster (Pattern-Fill) geladen; Parameter in * `image` (Skalierung/Verzerrung/Rotation). - * Fehlt `kind`, gilt „vector"; heutige Renderer ignorieren `kind` und zeichnen - * weiterhin nach `pattern` (Backward-Compat). + * • "gradient" — ein zweifarbiger Farbverlauf (linear/radial) füllt die + * Fläche; Parameter in `gradient`. Wie „image" unabhängig vom `pattern`- + * Feld. GL-/3D-Szene und DXF-Export kennen keine echten Verläufe (wie + * bei „image" bereits der Fall) und fallen auf eine neutrale Füllung + * zurück — nur die SVG-basierten Renderer (PlanView-Anzeige, Druck-/PDF- + * Export) zeichnen den echten Verlauf, da SVG-``/ + * `` sich genau wie ein `` als `fill="url(#…)"` + * referenzieren lassen — keine neue Fill-Mechanik nötig. + * Fehlt `kind`, gilt „vector"; heutige Renderer ignorieren unbekannte `kind`- + * Werte und zeichnen weiterhin nach `pattern` (Backward-Compat). */ - kind?: "vector" | "image"; + kind?: "vector" | "image" | "gradient"; /** * Untermodus einer Vektor-Schraffur (nur `kind` fehlt/"vector", Default * `undefined` ⇒ "parallel"): @@ -166,6 +213,14 @@ export interface HatchStyle { * = Drehung in Grad. Bei `kind==="vector"` ungenutzt. */ image?: { src: string; scaleX: number; scaleY: number; rotation: number }; + /** + * Farbverlauf (nur `kind==="gradient"`). `type`: "linear" (entlang `angle`, + * SVG-Konvention wie `HatchStyle.angle`) oder "radial" (vom Flächenzentrum + * nach aussen, `angle` dann ungenutzt). `angle` in Grad. Kein Gewicht/keine + * Zwischenfarben (Zweifarben-Verlauf, kein Multi-Stop-Editor) — deckt den + * Hauptfall ab, s. PENDENZEN.md für die bewusste Vereinfachung. + */ + gradient?: { color1: string; color2: string; angle: number; type: "linear" | "radial" }; /** Muster-Typ. */ pattern: HatchPattern; /** Grundmaßstab des Musters (1 = Standardteilung). */ @@ -410,6 +465,10 @@ export interface DoorType { leafStyle: "glatt" | "kassette" | "glas"; /** Glasanteil des Blatts (0..1); nur bei `leafStyle: "glas"` relevant. */ glazingRatio?: number; + /** Anzahl Kassetten-Felder horizontal; nur bei `leafStyle: "kassette"` relevant. Default 2. */ + panelCols?: number; + /** Anzahl Kassetten-Felder vertikal; nur bei `leafStyle: "kassette"` relevant. Default 3. */ + panelRows?: number; /** Zargen-/Rahmenstärke quer zur Wand (Meter). */ frameThickness: number; /** Rahmen-/Zargen-Tiefe in Wandrichtung (Meter); fehlt ⇒ aus Wanddicke. */ @@ -972,6 +1031,10 @@ export interface Wall { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "20" für Wände. */ categoryCode: string; + /** Objekt-Sperre: gesperrte Elemente lassen sich nicht anwählen (daher + * auch nicht verschieben/bearbeiten/löschen) — anders als der Ebenen-/ + * Geschoss-Sperrmodus (`DisplayMode`) ist das hier persistiert. */ + locked?: boolean; /** Achs-Startpunkt im Grundriss (Meter). */ start: Vec2; /** Achs-Endpunkt im Grundriss (Meter). */ @@ -1099,6 +1162,8 @@ export interface Ceiling { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "30" für Decken. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** * Geschlossener Umriss im Grundriss (Meter). Der Schlusspunkt wird NICHT * dupliziert (die letzte Kante läuft von outline[n-1] zu outline[0]). @@ -1206,6 +1271,8 @@ export interface Roof { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "35" für Dächer. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** Geschlossener Grundriss-Umriss (Meter); Geometrie nutzt die Bounding-Box. */ outline: Vec2[]; /** Dachform. */ @@ -1282,6 +1349,8 @@ export interface Opening { hostWallId: string; /** Grafik-Kategorie (Ebene), z. B. "21" für Türen/Fenster. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** Fenster oder Tür. */ kind: "window" | "door"; /** Abstand des ersten Pfostens vom Wand-Startpunkt entlang der Achse (Meter). */ @@ -1422,6 +1491,8 @@ export interface Stair { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "40" für Treppen. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** Grundform (gerade / L / Wendel). */ shape: StairShape; /** Startpunkt der Lauflinie im Grundriss (Meter). */ @@ -1511,6 +1582,8 @@ export interface Room { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "45" für Räume. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** SIA-416-Blatt-Kategorie (HNF/NNF/VF/FF/KGF). */ siaCategory: SiaCategory; /** Raum-Name, z. B. „Wohnen". */ @@ -1612,6 +1685,19 @@ export interface Door { // (keine vorab erzeugten Plan-Primitive). Siehe docs/design/drawing-tools.md §7. /** Geometrie-Form eines 2D-Zeichenelements. */ +/** + * Linienende (Pfeilspitze & Co.) an einer OFFENEN 2D-Form — in jedem CAD eine + * Standard-Objekteigenschaft, vor allem für Beschriftungen. Rein grafisch, + * kein Bezug auf andere Elemente. + * • "none" — offenes Ende (Default) + * • "arrow" — gefüllte Pfeilspitze (wie bisher fest am Leader) + * • "arrowOpen" — offene Pfeilspitze (zwei Striche) + * • "dot" — gefüllter Punkt + * • "tick" — Schrägstrich (45°, wie der Massstrich der Bemassung) + * • "square" — gefülltes Quadrat + */ +export type EndMark = "none" | "arrow" | "arrowOpen" | "dot" | "tick" | "square"; + export type Drawing2DGeom = | { shape: "line"; a: Vec2; b: Vec2 } /** @@ -1623,6 +1709,15 @@ export type Drawing2DGeom = * extend-/join-fähig (reine Ausrichtungshilfe, kein reales Bauteil). */ | { shape: "xline"; a: Vec2; b: Vec2 } + /** + * Strahl (Nutzer-Wunsch: „Ray, halb-unendliche Linie — nur `xline`, + * beidseitig unendlich, existiert"): `a` ist der FESTE Anker (wird NICHT + * verlängert), `b` bestimmt nur die Richtung — beim Rendern/Picken weit + * über `b` hinaus verlängert (dieselbe `XLINE_EXTEND_M`-Konstante), aber + * NICHT über `a` hinaus. Sonst wie `xline`: bewusst NICHT offset-/trim-/ + * extend-/join-fähig. + */ + | { shape: "ray"; a: Vec2; b: Vec2 } | { shape: "polyline"; pts: Vec2[]; @@ -1662,11 +1757,17 @@ export type Drawing2DGeom = */ | { shape: "bezier"; pts: Vec2[] } /** - * Glatte Kurve DURCH `pts` (uniformer Catmull-Rom), analog `polyline`, aber - * mit gerundetem statt geradem Verlauf zwischen den Wegpunkten. `closed` - * schliesst den Ring (letzter Wegpunkt → erster). + * Glatte Kurve über `pts`, analog `polyline`, aber mit gerundetem statt + * geradem Verlauf zwischen den Wegpunkten. `closed` schliesst den Ring + * (letzter Wegpunkt → erster). `mode` (optional, Default `"fit"` bei + * Fehlen — additiv wie üblich): `"fit"` = Kurve verläuft DURCH `pts` + * (uniformer Catmull-Rom, das bisherige/einzige Verhalten); `"control"` = + * `pts` sind Kontrollpunkte eines kubischen B-Splines (CV-Modus), die + * Kurve wird nur von ihnen gezogen, berührt sie i. A. NICHT (Ausnahme: + * Start/Ende bei offener Kurve, geklemmt). S. `tools/curves.ts:: + * sampleUniformBSpline` für die Geometrie. */ - | { shape: "spline"; pts: Vec2[]; closed: boolean } + | { shape: "spline"; pts: Vec2[]; closed: boolean; mode?: "fit" | "control" } /** * Masslinie (lineare Bemassung, SIA 400 B.5.3): misst den Abstand `a`↔`b`. * `offset` ist der VORZEICHENBEHAFTETE Normalabstand (Modell-Meter, links @@ -1684,7 +1785,49 @@ export type Drawing2DGeom = * ganze Kette (nicht mehrere) — spätere Bearbeitung kann Punkte ergänzen * (verlängern ODER dazwischen einfügen, s. `commands/cmds/dimension.ts`). */ - | { shape: "dimension"; pts: Vec2[]; offset: number } + | { + shape: "dimension"; + pts: Vec2[]; + offset: number; + /** + * Darstellungs-Feinheiten der Bemassung, ALLE optional und in + * PAPIER-MILLIMETERN — so, wie die Zeichnungsnorm sie angibt + * („Überstand 2 mm"), also unabhängig vom Massstab. Umgerechnet wird + * beim Erzeugen des jeweiligen Plans (`model/dimension.ts::mmToModel`); + * der Plan wird je Ziel — Bildschirm bzw. Layout-Viewport — eigens + * erzeugt, der Massstab ist dort also bekannt und eindeutig. + * Fehlt ein Wert, gilt `DIM_DEFAULTS_MM`. + */ + /** Abstand Masshilfslinie → bemessener Punkt (Default 1 mm). */ + gapMm?: number; + /** Überstand der Masshilfslinie ÜBER die Masslinie hinaus (Default 1 mm). */ + overshootMm?: number; + /** Länge der Massstriche an den Masslinien-Enden (Default 3 mm). */ + tickLenMm?: number; + /** Schrifthöhe der Masszahl (Default 4 mm). */ + textHeightMm?: number; + /** + * Strichstärken der drei Bestandteile, in PAPIER-MILLIMETERN (wie jede + * andere Strichstärke hier — erst beim Rendern aufgelöst und daher + * massstabsunabhängig; im Gegensatz zu den Abständen oben, die + * zwangsläufig Modellmass sind). Fehlt ein Wert, gilt der bisherige + * Default: Masslinie und Masshilfslinien erben die Strichstärke des + * Elements, die Massstriche werden doppelt so dick gezeichnet + * (Erkennbarkeit, SIA 400 Figur 13). + */ + lineWeightMm?: number; + extWeightMm?: number; + tickWeightMm?: number; + /** + * Verschiebung der Masszahl aus ihrer Standardlage, ebenfalls in + * PAPIER-MILLIMETERN, im Segment-Koordinatensystem: `along` entlang + * der Masslinie (+ = Richtung b), `perp` quer dazu (+ = von der + * Masslinie weg). Fehlt es, sitzt die Zahl mittig knapp über der + * Masslinie. Bei einer Masskette gilt der Versatz je Segment, + * Index = Segmentnummer. + */ + textOffsetsMm?: { along: number; perp: number }[]; + } /** * Höhenkote (SIA 400 B.5.4, Figur 18): Dreieck-Symbol + Höhenwert (Meter, * ±0.00-Referenz frei wählbar, s. Norm) an einem Punkt. `kind` bestimmt @@ -1701,6 +1844,64 @@ export type Drawing2DGeom = /** Drehung (Radiant); Werkzeug erzeugt bewusst nur 0, s. Ellipse-Muster. */ rotation: number; } + /** + * Detail-/Schnitt-Verweis-Symbol (Nutzer-Wunsch: „Nur `leaderTarget` an + * Text — kein zweiteiliges Verweis-Symbol, das eine Sheet/Layout-ID + * trägt"). Klassische zweigeteilte Verweisblase: Kreis mit waagrechter + * Trennlinie, `label` oben (Detail-/Schnitt-Bezeichner, z. B. „A"/„1"), + * Blattbezeichnung unten (`sheetLayoutId` verweist auf ein echtes + * `Project.layouts`-Blatt und LÖST seinen Namen zur Anzeige auf; fehlt der + * Verweis oder ist das Blatt gelöscht, zeigt `sheetLabel` einen manuell + * getippten Platzhalter). Fixe Modell-Meter-Grösse wie beim strukturell + * ähnlichen `kote`-Symbol (keine Papier-mm-Skalierung — dieselbe bewusste + * Vereinfachung). + */ + | { + shape: "detailref"; + /** Zentrum des Kreises. */ + at: Vec2; + /** Obere Zeile: Detail-/Schnitt-Bezeichner. */ + label: string; + /** Verknüpftes Blatt (`Project.layouts[].id`); `undefined` = kein Verweis. */ + sheetLayoutId?: string; + /** + * Untere Zeile OHNE Verweis (oder als Blatt gelöscht wurde): manuell + * getippter Platzhalter. Mit gültigem `sheetLayoutId` wird stattdessen + * der ECHTE Blattname angezeigt (immer aktuell, keine Duplizierung). + */ + sheetLabel?: string; + } + /** + * Massstabsbalken (Nutzer-Wunsch: „kein Massstabsbalken existiert"). Anders + * als Bemassung/Kote/Detail-Verweis ist die BALKENLÄNGE bewusst in ECHTEN + * Modell-Metern angegeben (nicht Papier-mm): der ganze Plan wird ohnehin im + * Papier-Massstab abgebildet, ein 1-Meter-Segment erscheint dadurch + * automatisch in der richtigen Papiergrösse für JEDEN Massstab — keine + * eigene Umrechnung nötig. Nur die Balkenhöhe/Beschriftungsgrösse sind + * (wie bei Bemassung/Kote) Papier-mm, damit sie unabhängig vom Massstab + * lesbar bleiben. Achsparallel (horizontal) — keine Drehung in v1, analog + * zur bewusst einfachen Ellipse-Erzeugung. + */ + | { + shape: "scalebar"; + /** Linke untere Ecke des Balkens. */ + at: Vec2; + /** Länge EINES Segments in ECHTEN Modell-Metern. */ + segmentLength: number; + /** Anzahl Segmente (abwechselnd gefüllt/leer). */ + segments: number; + } + /** + * Punkt-/Knotenmarker (Nutzer-Wunsch: „Punkt-/Knotenmarker" aus der + * Werkzeug-Lücken-Liste). Kleines, fest grosses Kreuz-in-Kreis-Symbol an + * `at` — markiert einen einzelnen Referenz-/Vermessungspunkt im Plan (z. B. + * einen Fixpunkt), OHNE selbst Bemassung/Text zu tragen. Fixe Modell- + * Meter-Grösse wie `kote`/`detailref` (keine Papier-mm-Skalierung) — ein + * physischer Bodenpunkt hat eine reale, vom Papier-Massstab unabhängige + * Grösse ist hier bewusst NICHT das Ziel; wie bei `kote` geht es um + * gleichbleibende Lesbarkeit im Plan. + */ + | { shape: "pointmarker"; at: Vec2 } | { shape: "text"; at: Vec2; @@ -1738,6 +1939,16 @@ export type Drawing2DGeom = * unverändert `undefined`. */ leaderTarget?: Vec2; + /** + * Zwischen-Knickpunkte der Hinweislinie, zwischen `at` (Textanker) und + * `leaderTarget` (Spitze) — Nutzer-Wunsch: „Hinweislinie hat nur EIN + * Segment, kein Knick-Punkt wie bei AutoCADs Multileader". Reihenfolge + * vom TEXTANKER zur SPITZE (wie die Zeichenrichtung im `leader`-Befehl: + * erst Spitze, dann rückwärts über die Knicke zum Text). Fehlt das + * Feld (Alt-Daten/einfache Hinweislinie), bleibt es bei der bisherigen + * geraden Linie `at → leaderTarget` — rein additiv, kein Format-Bruch. + */ + leaderBendPoints?: Vec2[]; /** * Text-entlang-Pfad: mind. 2 Stützpunkte, entlang derer der Text (nur * `text`, KEIN `doc`/Rich-Formatting — v1 bewusst einstilig) über ein @@ -1756,7 +1967,22 @@ export type Drawing2DGeom = * Transformation. Verweist die Instanz auf eine gelöschte/unbekannte * `blockDefId`, rendert sie schlicht nichts (kein Crash, s. `drawing2d.ts`). */ - | { shape: "block"; blockDefId: string; at: Vec2; rotation: number } + | { + shape: "block"; + blockDefId: string; + at: Vec2; + rotation: number; + /** + * Uniformer Skalierungsfaktor der Blockinstanz (Default 1, additiv/ + * optional — alte Projektdateien ohne dieses Feld bleiben gültig). + * Nutzer-Wunsch: „Skalierung beim Einfügen" — zuvor gab es dafür kein + * Modellfeld, ein `scale`-Transform auf eine Blockinstanz war damit ein + * kompletter No-Op (kein Feld zum Multiplizieren). Bewusst NUR ein + * uniformer Skalar (keine unabhängigen x/y-Faktoren) — konsistent mit + * `rotation` (auch nur EIN Winkel, keine Scherung). + */ + scale?: number; + } | { shape: "image"; /** Obere-linke Ecke der Bild-Box (Modell-Meter). */ @@ -1777,6 +2003,16 @@ export interface Drawing2D { levelId: string; /** Grafik-Kategorie (Ebene) — liefert Farbe/Strichstärke als Default. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; + /** + * Sichtbar am Bildschirm, aber von PDF-/SVG-/DXF-Export ausgeschlossen — + * wie eine „Non-Plotting"-Ebene, nur pro Objekt statt pro ganzer Ebene + * (z. B. für eine Konstruktions-/Hilfslinie, s. `xline`). Wirkt nur bei + * `generatePlan(..., forPrint: true)` (den drei Export-Aufrufstellen in + * `state/useExportHandlers.ts`) — die Bildschirmansicht ignoriert das Feld. + */ + noPrint?: boolean; geom: Drawing2DGeom; /** Optionaler Linienstil (Line Manager); sonst Kategorie-Default. */ lineStyleId?: string; @@ -1803,6 +2039,45 @@ export interface Drawing2D { color?: string; /** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */ colorPenId?: string; + /** + * Massstab des Strichmusters DIESES Elements (multipliziert die Strich-/ + * Lückenlängen des Linienstils; Default 1). Entspricht dem LTSCALE je Objekt + * in AutoCAD: dieselbe Strichlinie soll in 1:50 und 1:200 nicht gleich + * „dicht" wirken. Ohne Wert bleibt das Muster exakt wie im Linienstil. + */ + dashScale?: number; + /** + * Platzierung der Schraffur AN DIESEM OBJEKT (alle optional). Die Ressource + * (`HatchStyle`) legt Muster/Massstab/Winkel grundsätzlich fest; hier lässt + * sich das je Objekt nachjustieren — in AutoCAD eine der meistgenutzten + * Objekteigenschaften, etwa damit ein Plattenraster an der Raumecke ansetzt + * statt am Weltnullpunkt. + * • `hatchAngleDeg` — ERSETZT den Winkel der Ressource (Grad) + * • `hatchScale` — MULTIPLIZIERT den Massstab der Ressource + * • `hatchOrigin` — Ankerpunkt des Musterrasters (Modellkoordinaten); + * ohne Angabe bleibt es der Modellursprung, damit + * benachbarte Flächen dieselbe Musterphase teilen. + */ + hatchAngleDeg?: number; + hatchScale?: number; + hatchOrigin?: Vec2; + /** + * Objekt-Transparenz 0..1 (Default 1 = deckend) — wirkt auf Striche UND + * Füllungen dieses Elements. In Vectorworks/AutoCAD eine Standard- + * Objekteigenschaft (Bestand hinterlegen, Abbruch, durchscheinende + * Flächen). Der DXF-Export trägt sie nicht mit (bewusst, s. PENDENZEN.md). + */ + opacity?: number; + /** + * Linienenden an OFFENEN Formen (Linie, offene Polylinie, Bogen, Spline, + * Bezier) sowie an der Hinweislinie eines Textes. `start`/`end` beziehen + * sich auf die Zeichenrichtung der Form; `sizeMm` ist die Grösse in + * PAPIER-MILLIMETERN (massstabsunabhängig, wie die Bemassungs-Feinheiten — + * s. `model/dimension.ts`), Default `END_MARK_DEFAULT_SIZE_MM`. + * Geschlossene Formen (Rechteck, Kreis, Ellipse, geschlossene Polylinie) + * haben keine Enden und ignorieren das Feld. + */ + endMarks?: { start?: EndMark; end?: EndMark; sizeMm?: number }; /** * Optionale Vollton-Füllfarbe für geschlossene Formen (getrennt von der * Strichfarbe `color`). Fehlt sie, ist die Fläche transparent (nur Schraffur @@ -1928,6 +2203,8 @@ export interface Column { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "50" für Tragwerk. */ categoryCode: string; + /** Objekt-Sperre, analog `Wall.locked`. */ + locked?: boolean; /** Einfügepunkt (Profil-Mitte) im Grundriss (Meter). */ position: Vec2; /** Querschnitt (Rechteck oder Kreis). */ @@ -2199,6 +2476,18 @@ export interface ViewSnapshot { * gesetzt. Optional, damit hand-/altangelegte Snapshots ohne Feld gültig sind. */ enabledOverrideRuleIds?: string[]; + /** + * Kameraposition im Grundriss (Nutzer-Wunsch: „Ein gespeicherter Ausschnitt + * ändert, WAS sichtbar ist, nicht WOHIN man schaut" — bisher merkte sich ein + * Ausschnitt nie Bildmitte/Zoom). Beide Felder optional UND nur ein Paar + * (nicht einzeln sinnvoll) — fehlen sie (Alt-Ausschnitte vor dieser + * Ergänzung, oder beim Erfassen war kein Grundriss gemountet, z. B. 3D- + * Ansicht/Schnitt), bleibt die Bildmitte beim Wiederherstellen unverändert + * (nur der Massstab wird gesetzt, wie bisher). + */ + cameraCenter?: Vec2; + /** Zoom (Bildschirm-Pixel je Meter) beim Erfassen — zusammen mit `cameraCenter`. */ + cameraPxPerMeter?: number; } /** @@ -2469,6 +2758,18 @@ export interface Project { name: string; /** Linienstil-Bibliothek (Line Manager). */ lineStyles: LineStyle[]; + /** + * Textstil-Bibliothek (Nutzer-Wunsch: „Textstil-Bibliothek" — bisher gab es + * nur 4 FEST verdrahtete `DEFAULT_PRESETS` in `text/richText.ts`, nirgends + * im Projekt gespeichert, nirgends im ResourceManager editierbar). Optional + * mit Fallback auf `DEFAULT_PRESETS` (wie `layouts` — additiv, alte + * Projektdateien ohne dieses Feld bleiben gültig). Wiederverwendet den + * bereits vorhandenen `TextStylePreset`-Typ (Marks-Vorlage) UND die + * bereits vorhandene `applyPreset()`-Anwendungslogik aus `richText.ts` — + * neu ist NUR, dass die Liste jetzt projektbezogen + editierbar ist statt + * hart codiert. + */ + textStyles?: TextStylePreset[]; /** Schraffur-Bibliothek (Hatch Manager). */ hatches: HatchStyle[]; /** Bauteil-Material-Bibliothek (Component Manager). */ @@ -2524,6 +2825,17 @@ export interface Project { * angelegt/aktiviert), lösen Stift-Verweise auf `PEN_FALLBACK_COLOR` auf. */ activePenSetId?: string; + /** + * Benutzerdefinierte Farbpaletten (s. {@link CustomPalette}) — im + * Farbmischer-Popover per „Diese Farbe speichern" befüllt. Optional + * (siehe `pens`). + */ + customPalettes?: CustomPalette[]; + /** + * Welche MITGELIEFERTEN Paletten-Bänke im Farbwahl-Popover erscheinen + * (s. {@link BuiltinPaletteBanks}). Fehlt das Objekt, sind alle sichtbar. + */ + builtinPaletteBanks?: BuiltinPaletteBanks; /** Oberste Schnitte: Geschosse + Schnitte/Ansichten. */ drawingLevels: DrawingLevel[]; /** Grafik-Kategorie-Baum (geschossübergreifend). */ diff --git a/src/panels/AttributesPanel.tsx b/src/panels/AttributesPanel.tsx index f5a0e9a..341bf14 100644 --- a/src/panels/AttributesPanel.tsx +++ b/src/panels/AttributesPanel.tsx @@ -32,6 +32,12 @@ import { usePanelHost } from "./host"; import { Dropdown } from "../ui/Dropdown"; import { PenColorField } from "../ui/PenColorField"; import { activePenSet, resolvePenWeight } from "../model/penSets"; +import { DIM_DEFAULTS_MM } from "../model/dimension"; +import { END_MARK_DEFAULT_SIZE_MM } from "../plan/generatePlan/endMarks"; +import type { EndMark } from "../model/types"; + +/** Auswahl der Linienenden (Reihenfolge = Anzeige im Dropdown). */ +const END_MARK_OPTIONS: EndMark[] = ["none", "arrow", "arrowOpen", "dot", "tick", "square"]; // Element-spezifische Attribut-Abschnitte (Wand/Decke/Öffnung/Treppe/Raum) — // aus ObjectInfoPanel hierher verschoben (Ribbon Phase 3: ObjectInfo trägt nur // noch Bezugspunkt + Masse). @@ -45,6 +51,7 @@ import { ExtrudedSolidSection, ColumnSection, SectionLineSection, + DetailRefSection, } from "./ObjectInfoPanel"; /** UI-Zustand des 3-Optionen-Quellen-Dropdowns (nicht 1:1 das Modell-Feld: @@ -240,6 +247,16 @@ export function AttributesPanel() { // Effektiver Linienstil rein informativ (kein Setter im Kontrakt → kein Fake). // Wir leiten ihn aus dem Modell-Element ab, wenn explizit gesetzt; sonst „—". + // Offene Formen tragen Linienenden; geschlossene (Rechteck/Kreis/Ellipse/ + // Ring) und die Bemassung (eigene SIA-Massstriche) bewusst nicht. + const openEndsShape = (() => { + const g = isDrawing ? project.drawings2d.find((x) => x.id === sel.id)?.geom : undefined; + if (!g) return false; + if (g.shape === "line" || g.shape === "arc" || g.shape === "bezier") return true; + if (g.shape === "polyline" || g.shape === "spline") return !g.closed; + if (g.shape === "text") return !!g.leaderTarget; + return false; + })(); const drawing = isDrawing ? project.drawings2d.find((d) => d.id === sel.id) : undefined; @@ -273,6 +290,9 @@ export function AttributesPanel() { color={sel.color} penId={sel.colorPenId} pens={project.pens ?? []} + customPalettes={project.customPalettes} + builtinBanks={project.builtinPaletteBanks} + onSaveColor={host.onAddColorToCustomPalette} activeStyles={activePenSet(project)?.pens} showWeight={weightEditable} onColorChange={host.onSetSelectionColor} @@ -340,11 +360,12 @@ export function AttributesPanel() { ) )} - {/* Deckkraft (0..1) — nur Bild-Elemente (Drawing2D `{shape:"image"}` - im Plan, Layout-Annotation `kind:"image"`). Schlichtes Zahlenfeld + {/* Deckkraft (0..1) — bei BILDERN deren eigene Bild-Deckkraft, bei + allen übrigen 2D-Formen die Objekt-Transparenz (wirkt auf Strich + UND Füllung, s. `Drawing2D.opacity`). Schlichtes Zahlenfeld wie die Strichstärke bei Annotationen: kein Bauteil/keine Ebene, also keine Quellen-Vererbung. */} - {sel.isImage && ( + {(sel.isImage || isDrawing) && ( <> {t("attr.opacity")} @@ -427,6 +448,218 @@ export function AttributesPanel() { )} + {/* Strichmuster-Massstab (LTSCALE je Objekt): streckt Striche und + Lücken des Linienstils, ohne den Stil selbst zu ändern. */} + {isDrawing && ( + <> + {t("attr.dashScale")} + + { + const v = Number(e.target.value); + if (Number.isFinite(v) && v > 0) host.onSetDashScale(drawing!.id, v); + }} + /> + + + )} + + {/* Schraffur-Platzierung an DIESEM Objekt: Winkel ersetzt den der + Ressource, Massstab multipliziert sie, der Anker verschiebt das + Musterraster (leer = Modellursprung, damit benachbarte Flächen + dieselbe Phase teilen). Nur sinnvoll, wenn das Element überhaupt + eine Schraffur zeigt. */} + {isDrawing && sel.effectiveHatchId && ( + <> + {t("attr.hatch.angle")} + + { + const v = e.target.value === "" ? null : Number(e.target.value); + if (v === null || Number.isFinite(v)) + host.onSetHatchPlacement(drawing!.id, { angleDeg: v }); + }} + /> + + {t("attr.hatch.scale")} + + { + const v = e.target.value === "" ? null : Number(e.target.value); + if (v === null || (Number.isFinite(v) && v > 0)) + host.onSetHatchPlacement(drawing!.id, { scale: v }); + }} + /> + + {t("attr.hatch.origin")} + + + + + )} + + {/* ── Linienenden (Pfeilspitzen) ──────────────────────────────── + Nur bei OFFENEN 2D-Formen und beim Text mit Hinweislinie — + geschlossene Formen haben keine Enden. Grösse in Papier-mm + (massstabsunabhängig, wie die Bemassungswerte). */} + {openEndsShape && ( + <> +
{t("attr.ends.section")}
+ {( + [ + ["start", "attr.ends.start"], + ["end", "attr.ends.end"], + ] as const + ).map(([key, labelKey]) => ( + + {t(labelKey)} + + + host.onSetEndMarks(drawing!.id, { [key]: v as EndMark }) + } + options={END_MARK_OPTIONS.map((o) => ({ + value: o, + label: t(`attr.ends.${o}`), + }))} + /> + + + ))} + {t("attr.ends.size")} + + { + const mm = Number(e.target.value); + if (Number.isFinite(mm)) host.onSetEndMarks(drawing!.id, { sizeMm: mm }); + }} + /> + + + )} + + {/* ── Bemassung: Darstellungs-Feinheiten (SIA 400 B.5.3) ──────── + Nur bei einer selektierten Masskette. Alle Werte in Zentimetern + (Modellmass, s. `model/dimension.ts`); leer/0 fällt auf den + Standard zurück. Die Masszahl selbst wird direkt im Plan am + eigenen Griff verschoben (rastet nahe der Standardlage ein). */} + {drawing?.geom.shape === "dimension" && ( + <> +
{t("attr.dim.section")}
+ {/* Abstände/Grössen in PAPIER-mm (massstabsunabhängig, wie die + Strichstärken darunter) — beim Erzeugen des Plans wird mit + dessen Massstab in Modellmass umgerechnet. */} + {( + [ + ["gapMm", "attr.dim.gap", DIM_DEFAULTS_MM.gap], + ["overshootMm", "attr.dim.overshoot", DIM_DEFAULTS_MM.overshoot], + ["tickLenMm", "attr.dim.tick", DIM_DEFAULTS_MM.tickLen], + ["textHeightMm", "attr.dim.textHeight", DIM_DEFAULTS_MM.textHeight], + ] as const + ).map(([key, labelKey, fallback]) => { + const geom = drawing.geom as Extract; + return ( + + {t(labelKey)} + + { + const mm = Number(e.target.value); + if (Number.isFinite(mm)) host.onSetDimensionStyle(drawing.id, { [key]: mm }); + }} + /> + + + ); + })} + + )} + + {/* Strichstärken der drei Bestandteile — anders als die Abstände + oben sind das echte PAPIER-mm (wie jede Strichstärke hier), + also massstabsunabhängig. Leer gelassen (0) = Standard: Mass- + und Hilfslinie erben die Elementstärke, der Massstrich wird + doppelt so dick gezeichnet. */} + {drawing?.geom.shape === "dimension" && + ( + [ + ["lineWeightMm", "attr.dim.lineWeight"], + ["extWeightMm", "attr.dim.extWeight"], + ["tickWeightMm", "attr.dim.tickWeight"], + ] as const + ).map(([key, labelKey]) => { + const geom = drawing.geom as Extract; + const fallback = key === "tickWeightMm" ? sel.weightMm * 2 : sel.weightMm; + return ( + + {t(labelKey)} + + { + const mm = Number(e.target.value); + if (Number.isFinite(mm)) + host.onSetDimensionStyle(drawing.id, { [key]: mm }); + }} + /> + + + ); + })} + {/* ── Füllung (Vordergrund/Hintergrund + Schraffur) ─────────── */} {/* Vordergrund = Muster-/Schraffurfarbe, Hintergrund = Füllfarbe/ Poché. Jedes Feld: Nach Ebene (LayerCategory erzwingt den Wert) / @@ -452,6 +685,9 @@ export function AttributesPanel() { color={sel.effectiveForeground ?? "#808080"} penId={sel.foregroundPenId} pens={project.pens ?? []} + customPalettes={project.customPalettes} + builtinBanks={project.builtinPaletteBanks} + onSaveColor={host.onAddColorToCustomPalette} activeStyles={activePenSet(project)?.pens} disabled={!pocheEditable} onColorChange={host.onSetSelectionForeground} @@ -468,6 +704,9 @@ export function AttributesPanel() { color={sel.effectiveBackground ?? "#808080"} penId={sel.backgroundPenId} pens={project.pens ?? []} + customPalettes={project.customPalettes} + builtinBanks={project.builtinPaletteBanks} + onSaveColor={host.onAddColorToCustomPalette} activeStyles={activePenSet(project)?.pens} disabled={!pocheEditable} onColorChange={host.onSetSelectionBackground} @@ -518,6 +757,7 @@ export function AttributesPanel() { {sel.room && } {sel.extrudedSolid && } {sel.column && } + {sel.detailRef && } ); } diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index d0e5674..7d49044 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -35,11 +35,13 @@ import type { } from "../model/types"; import { SIA_CATEGORIES, siaLabelFull } from "../geometry/roomArea"; import { Dropdown } from "../ui/Dropdown"; +import type { DetailLevel } from "../ui/TopBar"; import { ColorHexField } from "../ui/ColorHexField"; import { usePanelHost } from "./host"; import type { CeilingInfo, ColumnInfo, + DetailRefInfo, ExtrudedSolidInfo, OpeningInfo, RoofInfo, @@ -59,6 +61,11 @@ function anchorKey(fx: number, fy: number): string { return `${fx}-${fy}`; } +/** Radiant → Grad, normiert auf [0, 360) (für Winkel-Anzeigefelder). */ +function toDeg360(rad: number): number { + return (((rad * 180) / Math.PI) % 360 + 360) % 360; +} + export function ObjectInfoPanel() { const host = usePanelHost(); const sel = host.selection; @@ -91,9 +98,9 @@ export function ObjectInfoPanel() { // X/Y des gewählten Bezugspunkts (Modell-Meter). Editierbar: Commit // verschiebt die Selektion so, dass der gewählte Bezugspunkt auf die // eingegebene Koordinate wandert (Delta = neu − aktuell → generischer Move - // über den Host). Bei Elementarten, die der Transform-Kern nicht kennt - // (Decke/Öffnung/Treppe/Raum), ist der Host-Aufruf ein No-op — das Feld - // zeigt danach wieder den unveränderten Wert (wie bei Breite/Höhe oben). + // über den Host). Bei Öffnungen (wandgebunden, kein freier 2D-Punkt) ist der + // Host-Aufruf ein No-op — das Feld zeigt danach wieder den unveränderten + // Wert (wie bei Breite/Höhe oben). const px = bbox.minX + anchor.fx * width; const py = bbox.minY + anchor.fy * height; @@ -236,15 +243,29 @@ export function ObjectInfoPanel() { value={height} onCommit={(h) => commitSize(width, h)} /> - {/* Linien-Länge bzw. Kreis-Radius (nur wenn die Selektion genau eine - Linie/ein Kreis ist — das Modell gibt das direkt her, andere Formen - bleiben ohne Zusatzfeld). */} - {drawingShape === "line" && ( - host.onSetDrawingLineLength(v)} - /> + {/* Formspezifische Zusatzfelder (nur wenn das Modell den Wert direkt + hergibt — andere Formen bleiben ohne Zusatzfeld, s. Dateikopf). */} + {drawingShape === "line" && rawDrawing?.geom.shape === "line" && ( + <> + host.onSetDrawingLineLength(v)} + /> + host.onSetDrawingLineAngle(v)} + /> + )} {drawingShape === "circle" && ( host.onSetDrawingCircleRadius(v)} /> )} + {drawingShape === "arc" && rawDrawing?.geom.shape === "arc" && ( + <> + host.onSetDrawingArcRadius(v)} + /> + host.onSetDrawingArcStartAngle(v)} + /> + host.onSetDrawingArcEndAngle(v)} + /> + + )} )} {/* Kontext-Objekt (importiertes Gebäude/Terrain/Konturen): reale LV95- @@ -501,6 +547,66 @@ export function SectionLineSection({ ); } +// ── Detail-/Schnitt-Verweis-Attribut-Abschnitt ────────────────────────────── +// Bezeichner (obere Zeile) + Blattverknüpfung (Dropdown der Project.layouts, +// „kein Verweis" löst sie); ohne Verknüpfung zusätzlich ein manueller +// Blattname-Platzhalter (untere Zeile, s. `DetailRefInfo`-Kommentar). +export function DetailRefSection({ + detailRef, + drawingId, + host, +}: { + detailRef: DetailRefInfo; + drawingId: string; + host: ReturnType; +}) { + return ( + <> +
+
{t("objinfo.detailRef.section")}
+ +
+ {t("objinfo.detailRef.label")} + host.onSetDetailRefLabel(drawingId, e.target.value)} + title={t("objinfo.detailRef.label")} + /> +
+ +
+ {t("objinfo.detailRef.sheet")} + host.onSetDetailRefSheetLayout(drawingId, v === "" ? undefined : v)} + options={[ + { value: "", label: t("objinfo.detailRef.sheet.none") }, + ...detailRef.availableLayouts.map((l) => ({ value: l.id, label: l.name })), + ]} + title={t("objinfo.detailRef.sheet")} + width={130} + /> +
+ + {!detailRef.sheetLayoutId && ( +
+ {t("objinfo.detailRef.sheetLabel")} + host.onSetDetailRefSheetLabel(drawingId, e.target.value)} + title={t("objinfo.detailRef.sheetLabel")} + /> +
+ )} + + ); +} + // ── Extrusions-Attribut-Abschnitt (truck-Integration) ─────────────────────── // Höhe editierbar (löst Re-Extrusion aus); Grundfläche + Geschoss read-only. export function ExtrudedSolidSection({ @@ -1184,6 +1290,28 @@ export function OpeningSection({ )} + {/* Detailstufe-Übersteuerung — fehlt sie ("" = Ansicht), gilt die + ansichtsweite Detailstufe (Grundriss-Kopfzeile). Wirkt auf dasselbe + grob/mittel/fein-Symbol wie die Ansichts-Detailstufe (Türblatt-Bogen, + Rahmen/Glaslinien), nur PRO ELEMENT statt für den ganzen Plan. */} +
+ {t("objinfo.opening.detailLevel")} + + host.onSetOpeningDetailLevel(v === "" ? undefined : (v as DetailLevel)) + } + options={[ + { value: "", label: t("objinfo.detailLevel.view") }, + { value: "grob", label: t("topbar.detail.grob") }, + { value: "mittel", label: t("topbar.detail.mittel") }, + { value: "fein", label: t("topbar.detail.fein") }, + ]} + title={t("objinfo.opening.detailLevel")} + width={130} + /> +
+
{/* UK/OK (read-only, aus der Wand-UK + Brüstung/Höhe abgeleitet). */} diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index 9f439d0..5211a65 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -116,6 +116,15 @@ export function ToolIcon({ id }: { id: ToolId }) { ); + case "ray": + // Diagonale mit festem Startpunkt (Kreis) und nur EINSEITIGER + // Verlängerung im Strich-Punkt-Muster — deutet den Strahl an. + return ( + + + + + ); case "polyline": // Dreisegmentiger Zickzack. return ( @@ -213,6 +222,58 @@ export function ToolIcon({ id }: { id: ToolId }) { ); + case "detailref": + // Zweigeteilte Verweisblase: Kreis + waagrechte Trennlinie + zwei Zeilen. + return ( + + + + + + + ); + case "scalebar": + // Balken mit abwechselnd gefüllten Segmenten (Massstabsbalken). + return ( + + + + + + + + ); + case "revcloud": + // Wolkenförmige Kette kleiner Bögen (Revisionswolke). + return ( + + + + ); + case "pointmarker": + // Kreuz-in-Kreis (Punkt-/Knotenmarker). + return ( + + + + + + ); + case "wipeout": + // Weisse Fläche mit gestricheltem Umriss (Maskenregion — deckt ab). + return ( + + + + ); case "text": // Serifen-„A" als Text-Symbol. return ( @@ -270,6 +331,7 @@ export function ToolIcon({ id }: { id: ToolId }) { const TOOLS_2D: ToolId[] = [ "line", "xline", + "ray", "polyline", "rect", "circle", @@ -281,6 +343,11 @@ const TOOLS_2D: ToolId[] = [ "bezier", "dimension", "kote", + "detailref", + "scalebar", + "revcloud", + "pointmarker", + "wipeout", "text", "leader", "textpath", @@ -289,7 +356,7 @@ const TOOLS_2D: ToolId[] = [ ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; const COMMANDS_3D = ["column", "ceilingopening", "roof", "extrude", "sectionline", "viewline"]; -const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; +const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; const VIEW_STORAGE_KEY = "dossier.toolsPanel.view"; diff --git a/src/panels/host.ts b/src/panels/host.ts index 597d909..2ae47b4 100644 --- a/src/panels/host.ts +++ b/src/panels/host.ts @@ -16,6 +16,7 @@ import { PanelHostContext } from "./types"; import type { DisplayMode, PanelHost } from "./types"; import type { AttributeSource, + EndMark, CeilingType, RoofType, Component, @@ -32,13 +33,16 @@ import type { SiaCategory, SliceTermination, StairShape, + Vec2, VerticalAnchor, WallReferenceLine, WallType, } from "../model/types"; import type { MeasurementReadout, SnapSettings, ToolId } from "../tools/types"; import type { Selection } from "../state/selectionInfo"; +import type { TextStylePreset } from "../text/richText"; import type { ScheduleKind } from "../export/exportSchedule"; +import type { DetailLevel } from "../ui/TopBar"; // ── Darstellungsmodus-Steuerung je Dock-Inhalt ──────────────────────────── @@ -145,6 +149,9 @@ export interface PanelHostValue { onPatchLineStyle: (id: string, patch: Partial) => void; onAddLineStyle: () => void; onDeleteLineStyle: (id: string) => void; + onPatchTextStyle: (id: string, patch: Partial) => void; + onAddTextStyle: () => void; + onDeleteTextStyle: (id: string) => void; /** Wandstile: immutable Änderung eines Wandtyps (Schichtfugen-Stile). */ onPatchWallType: (id: string, patch: Partial) => void; onAddWallType: () => void; @@ -240,6 +247,54 @@ export interface PanelHostValue { onSetSelectionForegroundPen: (penId: string | undefined) => void; /** Koppelt/entkoppelt den Hintergrund-Override, analog {@link onSetSelectionForegroundPen}. */ onSetSelectionBackgroundPen: (penId: string | undefined) => void; + /** + * Legt eine Farbe in einer EIGENEN Farbpalette ab (`Project.customPalettes`, + * „+"-Zelle im Farbwahl-Raster). `paletteId` unbekannt/undefined ⇒ es wird + * automatisch eine neue Palette angelegt (s. `projectSlice.ts`). + */ + onAddColorToCustomPalette: (paletteId: string | undefined, hex: string) => void; + /** + * Ändert die Darstellungs-Feinheiten EINER Masskette (Abstand/Überstand der + * Masshilfslinien, Massstrich-Länge, Schrifthöhe — alles Modell-Meter, + * s. `model/dimension.ts`). Teil-Patch; fehlende Felder bleiben. + */ + /** + * Setzt die Linienenden (Pfeilspitze & Co.) einer offenen 2D-Form bzw. der + * Text-Hinweislinie. Teil-Patch; fehlende Felder bleiben. + */ + /** + * Platzierung der Schraffur AM OBJEKT (Winkel/Massstab/Ankerpunkt, s. + * `Drawing2D.hatchAngleDeg`). Teil-Patch; `null` je Feld setzt zurück. + */ + /** Setzt den Strichmuster-Massstab eines 2D-Elements (LTSCALE je Objekt). */ + onSetDashScale: (drawingId: string, scale: number) => void; + /** Setzt den Bezeichner eines Detail-/Schnitt-Verweis-Symbols (obere Zeile). */ + onSetDetailRefLabel: (drawingId: string, label: string) => void; + /** Verknüpft (oder löst, `undefined`) das Blatt eines Detail-/Schnitt-Verweises. */ + onSetDetailRefSheetLayout: (drawingId: string, sheetLayoutId: string | undefined) => void; + /** Manueller Blattname-Platzhalter, nur relevant OHNE Blattverknüpfung. */ + onSetDetailRefSheetLabel: (drawingId: string, sheetLabel: string) => void; + onSetHatchPlacement: ( + drawingId: string, + patch: { angleDeg?: number | null; scale?: number | null; origin?: Vec2 | null }, + ) => void; + onSetEndMarks: ( + drawingId: string, + patch: { start?: EndMark; end?: EndMark; sizeMm?: number }, + ) => void; + onSetDimensionStyle: ( + drawingId: string, + patch: { + gapMm?: number; + overshootMm?: number; + tickLenMm?: number; + textHeightMm?: number; + /** Strichstärken in Papier-mm (s. `Drawing2DGeom.dimension`). */ + lineWeightMm?: number; + extWeightMm?: number; + tickWeightMm?: number; + }, + ) => void; /** * Setzt die Quelle des Vordergrunds, wenn KEIN „eigener Wert" gilt: "layer" = * Nach Ebene, "object" = Nach Bauteil. Löscht dabei IMMER den expliziten @@ -291,11 +346,29 @@ export interface PanelHostValue { * skaliert, Startpunkt bleibt fix). No-op, wenn die Selektion keine Linie ist. */ onSetDrawingLineLength: (length: number) => void; + /** + * Dreht eine Linien-Drawing2D auf einen absoluten Winkel (Grad, wie + * Bildschirm-X-Achse = 0°); Startpunkt + Länge bleiben fix, nur der + * Endpunkt wandert auf den neuen Winkel. No-op, wenn die Selektion keine + * Linie ist. + */ + onSetDrawingLineAngle: (deg: number) => void; /** * Setzt den Radius einer Kreis-Drawing2D (Mittelpunkt bleibt fix). No-op, * wenn die Selektion kein Kreis ist. */ onSetDrawingCircleRadius: (radius: number) => void; + /** + * Setzt den Radius eines Bogens (Mittelpunkt + Winkel bleiben fix). No-op, + * wenn die Selektion kein Bogen ist. + */ + onSetDrawingArcRadius: (radius: number) => void; + /** + * Setzt den Start- bzw. Endwinkel eines Bogens (Grad, CCW wie `a0`/`a1` im + * Modell). No-op, wenn die Selektion kein Bogen ist. + */ + onSetDrawingArcStartAngle: (deg: number) => void; + onSetDrawingArcEndAngle: (deg: number) => void; // ── Wand-Attribute (Object-Info-Panel; wirken NUR auf die selektierte Wand) ─ /** Setzt die Lage der Wandachse über die Dicke (außen/mitte/innen). */ @@ -360,6 +433,8 @@ export interface PanelHostValue { onSetOpeningDoorType: (doorType: "normal" | "wandoeffnung") => void; /** Setzt die Sturzlinien-Darstellung der Tür. */ onSetOpeningLintelLines: (lintelLines: "keine" | "innen" | "aussen" | "beide") => void; + /** Übersteuert die Detailstufe dieser Öffnung; `undefined` = Ansichts-Detailstufe gilt. */ + onSetOpeningDetailLevel: (detailLevel: DetailLevel | undefined) => void; /** Übersteuert Farbe/Strichstärke der geschnittenen Laibungs-/Stulp-Blöcke. */ onSetOpeningFrameLine: (v: { color?: string; weight?: number } | undefined) => void; /** Übersteuert Farbe/Strichstärke der durchlaufenden Rahmen-Kontur in Aufsicht. */ diff --git a/src/plan/PlanView.tsx b/src/plan/PlanView.tsx index 1cba2d0..0595631 100644 --- a/src/plan/PlanView.tsx +++ b/src/plan/PlanView.tsx @@ -17,8 +17,11 @@ import type { CSSProperties } from "react"; import type { HatchRender, Plan, PlanImage, Primitive } from "./generatePlan"; import type { EdgeGrip, Vec2 } from "../model/types"; import type { ToolHandlers, ToolId, ToolMods } from "../tools/types"; +import type { HudFieldsState } from "../tools/hudFormat"; import type { RichTextDoc } from "../text/richText"; import { docFromText } from "../text/richText"; +import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontMetrics"; +import { textFrameCorners } from "../text/textFrame"; import { RichTextEditor } from "../text/RichTextEditor"; import { useGlPlanRenderer } from "./useGlPlanRenderer"; import { useWasmPlanRenderer } from "./useWasmPlanRenderer"; @@ -32,6 +35,7 @@ import { meetScale, scaleFromView, viewForScale, + viewForCamera, fitBoxFor, pointInPolygon, pointSegDistPx, @@ -51,16 +55,14 @@ import { } from "./planView/primitives"; import { DraftOverlay } from "./planView/overlays"; import { PlanRulers } from "./planView/PlanRulers"; +import { PlanGrid } from "./planView/PlanGrid"; /** - * Feld-Status der Befehlszeile fürs Cursor-HUD (Tab-Feld-Zyklus §2.7): Werte je - * Feld (gelockt oder live), aktives Tab-Ziel und der gerade getippte Text — - * das HUD spiegelt die Eingabe LIVE am Cursor (VW-Verhalten). + * Feld-Status der Befehlszeile fürs Cursor-HUD (Tab-Feld-Zyklus §2.7) — Typ + * lebt in `tools/hudFormat.ts` (dort auch von der 3D-Ansicht genutzt); + * hier nur re-exportiert (bestehende Importe aus `./PlanView` bleiben gültig). */ -export interface HudFieldsState { - fields: { id: string; value: number | null; locked: boolean; active: boolean }[]; - typed: string; -} +export type { HudFieldsState } from "../tools/hudFormat"; // Zoom-Grenzen relativ zur eingepassten Default-Ansicht. Kleinere viewBox- // Breite = stärkerer Zoom. ZOOM_MAX → max. Hineinzoomen, ZOOM_MIN → Herauszoomen. @@ -109,6 +111,13 @@ export interface PlanViewHandle { pxPerMeter: () => number; /** Mitte des aktuellen Ausschnitts in Modell-Metern (z. B. für Import-Platzierung). */ viewCenterModel: () => Vec2; + /** + * Setzt die Bildmitte + den Zoom (Bildschirm-px je Meter) direkt — Gegenstück + * zu `viewCenterModel`/`pxPerMeter` (Auslesen). Für „gespeicherter Ausschnitt + * wiederherstellen": stellt WOHIN man schaut wieder her, nicht nur WAS + * sichtbar ist. No-op ohne Messung (SVG noch nicht gemountet). + */ + setCamera: (center: Vec2, pxPerMeter: number) => void; /** * Auf eine beliebige Punktmenge (Modell-Meter) einpassen, z. B. die Bounding- * Box neu importierter Kontext-Objekte (Auto-Zoom nach Geo-/DXF-Import). @@ -410,6 +419,8 @@ export interface PlanViewProps { toolHandlers?: ToolHandlers; /** Lineale (oben + links, VW-Stil) einblenden. Default an. */ showRulers?: boolean; + /** Sichtbares Hintergrund-Raster (rein visuell, unabhängig vom Fang-Raster). Default aus. */ + showGrid?: boolean; /** * Feld-Status der Befehlszeile fürs Cursor-HUD (Tab-Feld-Zyklus §2.7): * gelockte/live Werte je Feld, aktives Tab-Ziel und der gerade getippte @@ -570,6 +581,7 @@ export const PlanView = forwardRef( toolInputActive, toolHandlers, showRulers = true, + showGrid = false, hudFields, grips, gripHandleLines, @@ -865,6 +877,10 @@ export const PlanView = forwardRef( const v = viewRef.current; return { x: (v.x + v.w / 2) / PX_PER_M, y: -(v.y + v.h / 2) / PX_PER_M }; }, + setCamera: (center, pxPerMeter) => { + const target = viewForCamera(center, pxPerMeter, svgRef.current); + if (target) setView(target); + }, fitBounds: (pts) => { if (pts.length === 0) return; // leerer Import → kein Fit, kein Crash setView(fitBoxFor(pts, toScreenRef.current)); @@ -2177,6 +2193,24 @@ export const PlanView = forwardRef( ); }, [plan, selectedDrawingIds]); + // Hervorhebung ausgewählter TEXT-Objekte (Auswahl-Rahmen, Nutzer-Wunsch): + // `drawingText` hat keine `pts`/`a`/`b` wie Linie/Polygon, daher eigener + // Zweig statt `highlightDrawPrims` — der Rahmen wird geschätzt, s. + // `text/textFrame.ts` `textFrameCorners`. Während des Inline-Editors (`editTextId`) NICHT + // zusätzlich zeichnen — der Editor-Rahmen selbst übernimmt dort die Anzeige. + const highlightTextFrames = useMemo(() => { + const ids = + selectedDrawingIds && selectedDrawingIds.length ? new Set(selectedDrawingIds) : null; + if (!ids) return []; + return plan.primitives.filter( + (p): p is Extract => + p.kind === "drawingText" && + p.drawingId != null && + ids.has(p.drawingId) && + p.drawingId !== editTextId, + ); + }, [plan, selectedDrawingIds, editTextId]); + // Hervorhebung der selektierten Decken: alle Polygone JEDER gewählten Decke // (Fläche + Umriss) mit Akzentkontur überzeichnen — analog zur Wand-Auswahl. const highlightCeilingPolys = useMemo(() => { @@ -2360,7 +2394,21 @@ export const PlanView = forwardRef( const list: HatchedPoly[] = []; plan.primitives.forEach((p, i) => { if (p.kind === "polygon" && polyUsesPattern(p.hatch)) { - const hatch = p.greyed ? { ...p.hatch, color: greyColor(p.hatch.color) ?? p.hatch.color } : p.hatch; + // Verlauf-Schraffuren tragen ihre eigentliche Farbe in `gradient.color1/ + // color2` (nicht in `hatch.color`, das dort ungenutzt ist) — beide + // Stops müssen separat eingegraut werden, sonst bliebe ein gedimmtes + // Bauteil mit einer Verlauf-Schraffur trotzdem knallfarbig. + const hatch = p.greyed + ? { + ...p.hatch, + color: greyColor(p.hatch.color) ?? p.hatch.color, + gradient: p.hatch.gradient && { + ...p.hatch.gradient, + color1: greyColor(p.hatch.gradient.color1) ?? p.hatch.gradient.color1, + color2: greyColor(p.hatch.gradient.color2) ?? p.hatch.gradient.color2, + }, + } + : p.hatch; list.push({ patternId: `hatch-${i}`, hatch }); } }); @@ -2384,6 +2432,15 @@ export const PlanView = forwardRef( // `drawingText` (importierter Einzeltext) rendert IMMER im SVG — der GL- // wie der WASM-Renderer zeichnet ihn nicht. Der Raum-Stempel (`text`) // bleibt: unter WASM rastert ihn render2d selbst (sonst doppelt). + // ZUSÄTZLICH: das gerade im Inline-Editor offene Text-Element NIE + // statisch mitzeichnen — Bug-Meldung ("sonst alles io" nach den + // Positions-Fixes, aber sichtbare Text-Dopplung): das SVG bricht + // Zeilen nach einer GESCHÄTZTEN Zeichenbreite um + // (`CHAR_WIDTH_FACTOR`), der Browser im Editor nach ECHTER + // Font-Metrik — beide Umbrüche weichen leicht voneinander ab, sodass + // der (weisse, aber nicht überall deckende) Editor-Rahmen Reste des + // statischen Texts sichtbar unbedeckt liess. + (p.kind === "drawingText" && p.drawingId === editTextId) || (useGpuRenderer ? wantWasm ? p.kind !== "drawingText" @@ -2401,7 +2458,7 @@ export const PlanView = forwardRef( ), ), // eslint-disable-next-line react-hooks/exhaustive-deps -- toScreen ist modulweit konstant - [plan, hairline, paperScale, useGpuRenderer, wantWasm], + [plan, hairline, paperScale, useGpuRenderer, wantWasm, editTextId], ); const drawingRunEls = useMemo( () => @@ -2510,6 +2567,15 @@ export const PlanView = forwardRef( className={useGpuRenderer ? undefined : "plan-bg"} fill={useGpuRenderer ? "transparent" : undefined} /> + {/* Sichtbares Hintergrund-Raster (rein visuell, unabhängig vom Fang) — + MUSS hinter Luftbildern/Geometrie liegen, sonst überdeckt es die + Zeichnung. */} + {showGrid && ( + + )} {/* Georeferenzierte Luftbilder ZWISCHEN Blatt-Hintergrund und Geometrie: Modell-Meter × PX_PER_M mit negierter y-Achse (s. toScreen) → Bild-Norden (max.y) oben bei y=−max.y·PX; das Bild zeichnet natürlich von oben (kein @@ -2725,6 +2791,21 @@ export const PlanView = forwardRef( /> ), )} + {/* Auswahl-Rahmen für Text-Objekte (geschätzte Box, kein echter Umriss + wie bei Linie/Polygon — s. `text/textFrame.ts` `textFrameCorners`). Gestrichelt + statt durchgezogen wie `.plan-sel-draw`, um sichtbar zu machen: das + ist eine SCHÄTZUNG, keine exakt nachgezeichnete Geometrie. */} + {highlightTextFrames.map((p) => ( + `${s.x},${s.y}`) + .join(" ")} + pointerEvents="none" + /> + ))} )} {/* Gruppen-Auswahl: nur eine Bounding-Box mit vier Eckpunkten (kein @@ -2907,14 +2988,23 @@ export const PlanView = forwardRef( Feedback) — für ein frisch über `text`/`textbox` erzeugtes Element (sofort nach dem Platzieren, s. App.tsx host.focusDrawing) ODER ein per Doppelklick geöffnetes bestehendes. `RichTextEditor` bringt seine - eigene Mini-Toolbar mit (erscheint darüber, wie im Layout-Editor). - `at` ist die Baseline-links der ersten Zeile (s. primitives.tsx - "drawingText") — der Editor-Rahmen sitzt daher ~eine Zeilenhöhe - darüber. OHNE `wrapWidth` (Text-Werkzeug) bleibt die Breite frei - (kein Wortumbruch, nur Enter erzeugt neue Zeilen); MIT `wrapWidth` - (Textspalte) bricht der Editor live um wie ein InDesign-Textrahmen — - `position:"fixed"` mit echten Client-Pixeln (vbToClient), damit die - Positionierung unabhängig vom umgebenden Layout stimmt. */} + eigene Mini-Toolbar mit; die schwebt PER CSS (s. styles.css + `.planview-inline-text .rt-toolbar`, `position:absolute; + bottom:100%`) OBERHALB der Textfläche, ausserhalb von deren + Layout-Fluss — sie darf die Fläche NICHT nach unten schieben + (Bug-Meldung "Editor ist tiefer als der Text": vorher stand die + Toolbar noch im normalen Fluss ÜBER der Fläche und schob sie um + ihre eigene, zoomunabhängige Höhe nach unten, während hier nur mit + EINER Zeilenhöhe Versatz gerechnet wird — bei üblichem Zoom kleiner + als die Toolbar-Höhe). `at` ist die Baseline-links der ersten Zeile + (s. primitives.tsx "drawingText") — der Editor-Rahmen (= die + Textfläche, jetzt ohne die Toolbar davor) sitzt daher ~eine + Zeilenhöhe darüber. OHNE `wrapWidth` (Text-Werkzeug) bleibt die + Breite frei (kein Wortumbruch, nur Enter erzeugt neue Zeilen); MIT + `wrapWidth` (Textspalte) bricht der Editor live um wie ein + InDesign-Textrahmen — `position:"fixed"` mit echten Client-Pixeln + (vbToClient), damit die Positionierung unabhängig vom umgebenden + Layout stimmt. */} {editTextId && (() => { const prim = plan.primitives.find( @@ -2933,7 +3023,11 @@ export const PlanView = forwardRef( // s. styles.css `.planview-inline-text .rt-surface`) — die Toolbar // bleibt dadurch immer normal gross und bedienbar. const pxPerM = currentPxPerMeter(); - const topAnchor = toScreen({ x: prim.at.x, y: prim.at.y + prim.heightM }); + // Baseline → Box-Oberkante: ECHTES Font-Measuring statt der groben + // "ganzes heightM = Ascent"-Näherung (Bug-Meldung "Sprung nach + // rechts oben" — Rest-Y-Versatz nach dem Toolbar-Fluss-/Schrift-Fix). + const baselineFromTop = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); + const topAnchor = toScreen({ x: prim.at.x, y: prim.at.y + prim.heightM * baselineFromTop }); const screen = vbToClient(topAnchor.x, topAnchor.y); const hasWrap = !!prim.wrapWidth; const widthPx = hasWrap ? prim.wrapWidth! * pxPerM : undefined; @@ -2969,7 +3063,12 @@ export const PlanView = forwardRef( } }} > - onCommitTextEdit?.(d)} autoFocus /> + onCommitTextEdit?.(d)} + autoFocus + sizeUnit="em" + />
); diff --git a/src/plan/generatePlan.detailref.test.ts b/src/plan/generatePlan.detailref.test.ts new file mode 100644 index 0000000..f41b8a6 --- /dev/null +++ b/src/plan/generatePlan.detailref.test.ts @@ -0,0 +1,107 @@ +/** + * `generatePlan` — Rendering des Detail-/Schnitt-Verweis-Symbols + * (`shape:"detailref"`): Kreis + waagrechte Trennlinie + Bezeichner oben + + * Blattname unten (aufgelöst über `sheetLayoutId`, sonst manueller + * `sheetLabel`-Platzhalter, s. `drawing2d.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import type { Drawing2D, Layout, Project } from "../model/types"; + +function detailRefDrawing( + id: string, + extra: Partial> = {}, +): Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "detailref", at: { x: 2, y: 1 }, label: "A", ...extra }, + }; +} + +function project(drawings: Drawing2D[], layouts: Layout[] = []): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + layouts, + } as unknown as Project; +} + +const visible = new Set(["20"]); + +describe("generatePlan — Drawing2D detailref", () => { + it("erzeugt einen Kreis + eine Trennlinie + einen Label-Text (ohne Blattbezug)", () => { + const p = project([detailRefDrawing("d1")]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const circles = plan.primitives.filter((pr) => pr.kind === "drawingCircle"); + const lines = plan.primitives.filter((pr) => pr.kind === "line" && pr.drawingId === "d1"); + const texts = plan.primitives.filter((pr) => pr.kind === "drawingText" && pr.drawingId === "d1"); + expect(circles.length).toBe(1); + expect(lines.length).toBe(1); // nur die Trennlinie + expect(texts.length).toBe(1); // nur das Label, kein leerer Blattname + expect(texts[0].kind === "drawingText" && texts[0].text).toBe("A"); + }); + + it("Kreis-Zentrum entspricht 'at'", () => { + const p = project([detailRefDrawing("d1")]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const circle = plan.primitives.find((pr) => pr.kind === "drawingCircle"); + expect(circle && circle.kind === "drawingCircle" && circle.center).toEqual({ x: 2, y: 1 }); + }); + + it("mit manuellem sheetLabel (keine Blattverknüpfung): zweiter Text zeigt den manuellen Platzhalter", () => { + const p = project([detailRefDrawing("d1", { sheetLabel: "A-102" })]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const texts = plan.primitives.filter((pr) => pr.kind === "drawingText" && pr.drawingId === "d1"); + expect(texts.length).toBe(2); + const bodies = texts.map((t) => t.kind === "drawingText" && t.text); + expect(bodies).toContain("A"); + expect(bodies).toContain("A-102"); + }); + + it("mit gültiger sheetLayoutId: zeigt den ECHTEN Blattnamen, nicht den manuellen sheetLabel", () => { + const layout: Layout = { + id: "L1", + name: "02 Grundriss OG", + paper: "a3", + orientation: "landscape", + viewports: [], + }; + const p = project( + [detailRefDrawing("d1", { sheetLayoutId: "L1", sheetLabel: "veralteter Platzhalter" })], + [layout], + ); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const texts = plan.primitives.filter((pr) => pr.kind === "drawingText" && pr.drawingId === "d1"); + const bodies = texts.map((t) => t.kind === "drawingText" && t.text); + expect(bodies).toContain("02 Grundriss OG"); + expect(bodies).not.toContain("veralteter Platzhalter"); + }); + + it("gelöschtes/unbekanntes verknüpftes Blatt fällt auf den manuellen sheetLabel zurück", () => { + const p = project([detailRefDrawing("d1", { sheetLayoutId: "does-not-exist", sheetLabel: "Fallback" })]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const texts = plan.primitives.filter((pr) => pr.kind === "drawingText" && pr.drawingId === "d1"); + const bodies = texts.map((t) => t.kind === "drawingText" && t.text); + expect(bodies).toContain("Fallback"); + }); +}); diff --git a/src/plan/generatePlan.leaderBends.test.ts b/src/plan/generatePlan.leaderBends.test.ts new file mode 100644 index 0000000..edf9215 --- /dev/null +++ b/src/plan/generatePlan.leaderBends.test.ts @@ -0,0 +1,102 @@ +// `Drawing2DGeom["text"].leaderBendPoints` — Rendering mehrsegmentiger +// Hinweislinien (Nutzer-Wunsch: „kein Knick-Punkt wie bei AutoCADs +// Multileader"). Ohne Knickpunkte MUSS das Ergebnis identisch zum bisherigen +// Einzelsegment-Verhalten bleiben (reine Additiv-Erweiterung). + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import type { Drawing2D, Project } from "../model/types"; + +function leaderDrawing(bendPoints?: { x: number; y: number }[]): Drawing2D { + return { + id: "L1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "text", + at: { x: 0, y: 0 }, + text: "", + height: 0.2, + angle: 0, + leaderTarget: { x: 10, y: 0 }, + ...(bendPoints ? { leaderBendPoints: bendPoints } : {}), + }, + }; +} + +function project(drawing: Drawing2D): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [drawing], + context: [], + } as unknown as Project; +} + +const visible = new Set(["20"]); + +function leaderLineSegments(drawing: Drawing2D) { + return generatePlan(project(drawing), "eg", visible) + .primitives.filter( + (p): p is Extract => p.kind === "line" && p.drawingId === "L1", + ); +} + +describe("generatePlan — leaderBendPoints (Multileader)", () => { + it("ohne Knickpunkte: GENAU EIN Segment (unverändertes Verhalten)", () => { + const segs = leaderLineSegments(leaderDrawing()); + expect(segs).toHaveLength(1); + expect(segs[0].a).toEqual({ x: 0, y: 0 }); // Textanker + // b ist die Spitze, zurückgezogen um die Pfeillänge — nicht exakt (10,0). + expect(segs[0].b.x).toBeLessThan(10); + expect(segs[0].b.y).toBeCloseTo(0, 9); + }); + + it("ein Knickpunkt: ZWEI Segmente (Anker→Knick, Knick→Spitze)", () => { + const segs = leaderLineSegments(leaderDrawing([{ x: 5, y: 5 }])); + expect(segs).toHaveLength(2); + // Erstes Segment: Anker → Knick (voller Punkt, kein Pfeil-Rückzug). + expect(segs[0].a).toEqual({ x: 0, y: 0 }); + expect(segs[0].b).toEqual({ x: 5, y: 5 }); + // Zweites Segment: Knick → Spitze (zurückgezogen). + expect(segs[1].a).toEqual({ x: 5, y: 5 }); + expect(segs[1].b.x).toBeLessThan(10); + }); + + it("zwei Knickpunkte: DREI Segmente in Klick-Reihenfolge", () => { + const segs = leaderLineSegments(leaderDrawing([{ x: 3, y: 3 }, { x: 6, y: -2 }])); + expect(segs).toHaveLength(3); + expect(segs[0].a).toEqual({ x: 0, y: 0 }); + expect(segs[0].b).toEqual({ x: 3, y: 3 }); + expect(segs[1].a).toEqual({ x: 3, y: 3 }); + expect(segs[1].b).toEqual({ x: 6, y: -2 }); + expect(segs[2].a).toEqual({ x: 6, y: -2 }); + }); + + it("die Pfeilspitze richtet sich nach dem LETZTEN Segment, nicht der vollen Anker→Spitze-Richtung", () => { + // Knick direkt ÜBER der Spitze (9,5) → letztes Segment zeigt fast senkrecht + // nach unten zur Spitze (10,0), ganz anders als die direkte Gesamtrichtung + // Anker(0,0)→Spitze(10,0) (waagrecht). + const segs = leaderLineSegments(leaderDrawing([{ x: 9, y: 5 }])); + const last = segs[segs.length - 1]; + // b liegt nahe (10,0), zurückgezogen ENTLANG der Knick→Spitze-Richtung + // (steil, fast senkrecht) — NICHT entlang der waagrechten Gesamtrichtung. + expect(Math.abs(last.b.x - 10)).toBeLessThan(0.3); + expect(last.b.y).toBeGreaterThan(0); // noch auf dem Weg von (9,5) nach (10,0), nicht bei y=0 + }); +}); diff --git a/src/plan/generatePlan.noPrint.test.ts b/src/plan/generatePlan.noPrint.test.ts new file mode 100644 index 0000000..cb57d15 --- /dev/null +++ b/src/plan/generatePlan.noPrint.test.ts @@ -0,0 +1,75 @@ +// `Drawing2D.noPrint` (Nutzer-Wunsch: „Kein 'nicht druckend'-Flag im Modell — +// selbst `xline` druckt mit") — ein als `noPrint` markiertes Element bleibt +// am Bildschirm normal sichtbar, fehlt aber im Export (`generatePlan(..., +// forPrint: true)`, s. `state/useExportHandlers.ts`). + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import type { Drawing2D, Project } from "../model/types"; + +function lineDrawing(id: string, noPrint?: boolean): Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + ...(noPrint !== undefined ? { noPrint } : {}), + }; +} + +function project(drawings: Drawing2D[]): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + } as unknown as Project; +} + +const visible = new Set(["20"]); + +// generatePlan-Positionsparameter bis `forPrint` (10.): project, floorId, +// visibleCodes, categoryDisplay, detail, showReferenceLines, mono, +// includeGlobal, scaleDenominator, forPrint. +function linePrimCount(p: Project, forPrint: boolean) { + return generatePlan(p, "eg", visible, undefined, "mittel", false, false, true, undefined, forPrint) + .primitives.filter((pr) => pr.kind === "line" && pr.drawingId).length; +} + +describe("generatePlan — Drawing2D.noPrint", () => { + it("Default (forPrint=false, Bildschirm): ein noPrint-Element bleibt sichtbar", () => { + const p = project([lineDrawing("d1", true)]); + expect(linePrimCount(p, false)).toBe(1); + }); + + it("forPrint=true (Export): ein noPrint-Element fehlt", () => { + const p = project([lineDrawing("d1", true)]); + expect(linePrimCount(p, true)).toBe(0); + }); + + it("forPrint=true lässt normale (nicht-noPrint) Elemente unangetastet", () => { + const p = project([lineDrawing("d1", false), lineDrawing("d2")]); // d2: Feld fehlt ganz (Alt-Daten) + expect(linePrimCount(p, true)).toBe(2); + }); + + it("gemischte Auswahl: forPrint=true lässt nur die noPrint-Elemente weg", () => { + const p = project([lineDrawing("d1", true), lineDrawing("d2", false)]); + expect(linePrimCount(p, true)).toBe(1); + expect(linePrimCount(p, false)).toBe(2); + }); +}); diff --git a/src/plan/generatePlan.openings.test.ts b/src/plan/generatePlan.openings.test.ts index 052edd0..ba56b73 100644 --- a/src/plan/generatePlan.openings.test.ts +++ b/src/plan/generatePlan.openings.test.ts @@ -164,3 +164,42 @@ describe("generatePlan — Fenster Anschlag-Striche (Item 8)", () => { expect(windowRevealCount(projectWithOpening({ ...baseWindow }), "mittel")).toBe(0); }); }); + +describe("generatePlan — Opening.detailLevel (Per-Element-Übersteuerung der Ansichts-Detailstufe)", () => { + /** Zählt Schwenkbögen (arc) für eine Tür bei einer gegebenen ANSICHTS-Detailstufe. */ + const doorArcCount = (opening: Opening, viewDetail: "grob" | "mittel" | "fein") => + generatePlan(projectWithOpening(opening), "eg", visible, undefined, viewDetail).primitives.filter( + (pr) => pr.kind === "arc", + ).length; + + it("ohne detailLevel gilt weiterhin die Ansichts-Detailstufe (rückwärtskompatibel)", () => { + expect(doorArcCount(baseDoor, "grob")).toBe(0); // grob: kein Schwenkbogen + expect(doorArcCount(baseDoor, "mittel")).toBe(1); // mittel+: Schwenkbogen + }); + + it("detailLevel='grob' unterdrückt den Schwenkbogen, AUCH wenn die Ansicht 'fein' zeigt", () => { + expect(doorArcCount({ ...baseDoor, detailLevel: "grob" }, "fein")).toBe(0); + }); + + it("detailLevel='fein' zeigt den Schwenkbogen, AUCH wenn die Ansicht 'grob' zeigt", () => { + expect(doorArcCount({ ...baseDoor, detailLevel: "fein" }, "grob")).toBe(1); + }); + + it("wirkt NUR auf die übersteuerte Öffnung, andere Öffnungen bleiben bei der Ansichts-Detailstufe", () => { + const wall: Wall = { + id: "W1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 6, y: 0 }, + wallTypeId: "aw", + height: 2.6, + }; + const doorFein: Opening = { ...baseDoor, id: "T1", detailLevel: "fein" }; + const doorPlain: Opening = { ...baseDoor, id: "T2", position: 3.0 }; + const p: Project = { ...projectWithOpening(doorFein), walls: [wall], openings: [doorFein, doorPlain] }; + const plan = generatePlan(p, "eg", visible, undefined, "grob"); + expect(plan.primitives.filter((pr) => pr.kind === "arc").length).toBe(1); + }); +}); diff --git a/src/plan/generatePlan.pointmarker.test.ts b/src/plan/generatePlan.pointmarker.test.ts new file mode 100644 index 0000000..49f1553 --- /dev/null +++ b/src/plan/generatePlan.pointmarker.test.ts @@ -0,0 +1,70 @@ +/** + * `generatePlan` — Rendering des Punkt-/Knotenmarkers (`shape:"pointmarker"`): + * Kreuz-in-Kreis, fixe Modell-Meter-Grösse (s. `drawing2d.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import type { Drawing2D, Project } from "../model/types"; + +function pointMarkerDrawing(id: string, at = { x: 2, y: 1 }): Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "pointmarker", at }, + }; +} + +function project(drawings: Drawing2D[]): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + } as unknown as Project; +} + +const visible = new Set(["20"]); + +describe("generatePlan — Drawing2D pointmarker", () => { + it("erzeugt einen Kreis + zwei Kreuz-Linien", () => { + const p = project([pointMarkerDrawing("d1")]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const circles = plan.primitives.filter((pr) => pr.kind === "drawingCircle" && pr.drawingId === "d1"); + const lines = plan.primitives.filter((pr) => pr.kind === "line" && pr.drawingId === "d1"); + expect(circles.length).toBe(1); + expect(lines.length).toBe(2); // waagrecht + senkrecht + }); + + it("Kreis-Zentrum und Kreuz-Mittelpunkt entsprechen 'at'", () => { + const p = project([pointMarkerDrawing("d1", { x: 5, y: 3 })]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const circle = plan.primitives.find((pr) => pr.kind === "drawingCircle" && pr.drawingId === "d1"); + expect(circle && circle.kind === "drawingCircle" && circle.center).toEqual({ x: 5, y: 3 }); + const lines = plan.primitives.filter( + (pr): pr is Extract => pr.kind === "line" && pr.drawingId === "d1", + ); + const horizontal = lines.find((l) => l.a.y === l.b.y); + const vertical = lines.find((l) => l.a.x === l.b.x); + expect(horizontal).toBeDefined(); + expect(vertical).toBeDefined(); + expect((horizontal!.a.x + horizontal!.b.x) / 2).toBeCloseTo(5, 6); + expect((vertical!.a.y + vertical!.b.y) / 2).toBeCloseTo(3, 6); + }); +}); diff --git a/src/plan/generatePlan.scalebar.test.ts b/src/plan/generatePlan.scalebar.test.ts new file mode 100644 index 0000000..c1b4832 --- /dev/null +++ b/src/plan/generatePlan.scalebar.test.ts @@ -0,0 +1,92 @@ +/** + * `generatePlan` — Rendering des Massstabsbalkens (`shape:"scalebar"`): + * abwechselnd gefüllte/leere Segmente + Ticks/Beschriftung an jeder + * Segmentgrenze (s. `drawing2d.ts`). + */ + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import type { Drawing2D, Project } from "../model/types"; + +function scalebarDrawing(id: string, segmentLength: number, segments: number): Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "scalebar", at: { x: 0, y: 0 }, segmentLength, segments }, + }; +} + +function project(drawings: Drawing2D[]): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }, + ], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + doors: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: drawings, + context: [], + } as unknown as Project; +} + +const visible = new Set(["20"]); + +describe("generatePlan — Drawing2D scalebar", () => { + it("erzeugt genau `segments` gefüllte Polygone (abwechselnd) + `segments+1` Ticks/Labels", () => { + const p = project([scalebarDrawing("d1", 1, 4)]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const polys = plan.primitives.filter((pr) => pr.kind === "polygon" && pr.drawingId === "d1"); + const texts = plan.primitives.filter((pr) => pr.kind === "drawingText" && pr.drawingId === "d1"); + expect(polys.length).toBe(4); + expect(texts.length).toBe(5); // 0,1,2,3,4 → 5 Beschriftungen (0..segments) + }); + + it("alterniert Füllung: gerade Segmente gefüllt (fill=color), ungerade leer (fill='none')", () => { + const p = project([scalebarDrawing("d1", 1, 3)]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const polys = plan.primitives.filter( + (pr) => pr.kind === "polygon" && pr.drawingId === "d1", + ) as Extract<(typeof plan.primitives)[number], { kind: "polygon" }>[]; + // Reihenfolge = Erzeugungsreihenfolge (i=0..segments-1). + expect(polys[0].fill).not.toBe("none"); + expect(polys[1].fill).toBe("none"); + expect(polys[2].fill).not.toBe("none"); + }); + + it("Segmentlänge ist eine ECHTE Modell-Distanz — keine Papier-mm-Umrechnung", () => { + const p = project([scalebarDrawing("d1", 2, 2)]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const polys = plan.primitives.filter( + (pr) => pr.kind === "polygon" && pr.drawingId === "d1", + ) as Extract<(typeof plan.primitives)[number], { kind: "polygon" }>[]; + // Erstes Segment: x von 0 bis 2 (Modell-Meter), unabhängig vom Massstab. + const xs = polys[0].pts.map((pt) => pt.x); + expect(Math.min(...xs)).toBeCloseTo(0, 6); + expect(Math.max(...xs)).toBeCloseTo(2, 6); + }); + + it("letzte Beschriftung trägt die 'm'-Einheit, die übrigen nicht", () => { + const p = project([scalebarDrawing("d1", 1, 3)]); + const plan = generatePlan(p, "eg", visible, undefined, "mittel"); + const texts = plan.primitives.filter( + (pr) => pr.kind === "drawingText" && pr.drawingId === "d1", + ) as Extract<(typeof plan.primitives)[number], { kind: "drawingText" }>[]; + const bodies = texts.map((t) => t.text); + expect(bodies).toContain("0"); + expect(bodies).toContain("1"); + expect(bodies).toContain("2"); + expect(bodies).toContain("3m"); // letzte Grenze (3 × 1m) trägt die Einheit + }); +}); diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index 43c381d..8139000 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -71,6 +71,7 @@ import { } from "./generatePlan/shared"; import { addCeilingPoche } from "./generatePlan/ceilings"; import { addContextContours } from "./generatePlan/context"; +import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { addDrawing2D } from "./generatePlan/drawing2d"; import { addDoorSymbol, addOpeningSymbol } from "./generatePlan/openings"; import { addRoof } from "./generatePlan/roofs"; @@ -213,6 +214,24 @@ export function generatePlan( // `generateVisibleLevelsPlan`) dürfen diese NICHT je Geschoss dupliziert // werden — nur der aktive Aufruf liefert sie. includeGlobal = true, + /** + * Papier-Massstab (1:N) DIESES Plans — nur für Bemassungs-Feinheiten, die + * in Papier-mm angegeben sind (s. `model/dimension.ts`). Der Plan wird je + * Ziel eigens erzeugt (Bildschirm bzw. Layout-Viewport), der Massstab ist + * hier also eindeutig. Default 1:100, damit bestehende Aufrufer/Tests + * unverändert bleiben. + */ + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, + /** + * Export-Modus (PDF/SVG/DXF): schliesst Elemente mit `Drawing2D.noPrint` + * aus (analog einer „Non-Plotting"-Ebene, nur pro Objekt statt pro Ebene — + * Nutzer-Wunsch „Kein 'nicht druckend'-Flag im Modell"). Default `false` + * (Bildschirm/Editieren) — ein als `noPrint` markiertes Element bleibt dort + * normal sichtbar, nur der Export lässt es weg. Bewusst als LETZTER + * Parameter angehängt (nicht zwischen bestehende einsortiert), damit keine + * bestehende Aufrufstelle mit positionalen Argumenten verrutscht. + */ + forPrint = false, ): Plan { const primitives: Primitive[] = []; // Aktives Geschoss (für die Grundriss-Schnitthöhe der Treppen). @@ -275,7 +294,8 @@ export function generatePlan( (d) => d.levelId === floorId && visibleCodes.has(d.categoryCode) && - categoryDisplay(d.categoryCode).render, + categoryDisplay(d.categoryCode).render && + (!forPrint || !d.noPrint), ) .map((d) => { // `object_name` matcht bei freier 2D-Geometrie den Formnamen @@ -418,7 +438,10 @@ export function generatePlan( const oLwMm = ov.lineweight ?? lwByCode.get(o.categoryCode) ?? LAYER_LINE_MM; const effO = ov.color !== undefined ? { ...o, color: ov.color } : o; - addOpeningSymbol(primitives, project, wall, effO, d.greyed, detail, oLwMm); + // Per-Element-Detailstufe (`Opening.detailLevel`) übersteuert die + // ansichtsweite `detail`, sonst gilt Letztere unverändert. + const effDetail = o.detailLevel ?? detail; + addOpeningSymbol(primitives, project, wall, effO, d.greyed, effDetail, oLwMm); } } } @@ -466,7 +489,7 @@ export function generatePlan( // 2D-Zeichengeometrie zuletzt (über der Poché). for (const d of drawings) { const greyed = categoryDisplay(d.categoryCode).greyed; - addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode); + addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator); } // Extrudierte Körper (truck-Integration): das Quell-Profil wurde beim @@ -536,6 +559,7 @@ export function generateVisibleLevelsPlan( showReferenceLines = false, mono = false, levelDisplay: CategoryDisplayResolver = SHOW_ALL, + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, ): Plan { const active = project.drawingLevels.find((l) => l.id === activeLevelId); const siblings = @@ -566,8 +590,19 @@ export function generateVisibleLevelsPlan( showReferenceLines, mono, false, // includeGlobal: Schnittlinien/Kontext/Luftbilder nur einmal (aktiv) + scaleDenominator, ); - primitives.push(...(d.greyed ? p.primitives.map((pr) => ({ ...pr, greyed: true })) : p.primitives)); + // KEIN `primitives.push(...p.primitives)`: bei grossen Importen (z. B. ein + // Kataster-DXF einer ganzen Stadt, hunderttausende Drawing2D-Elemente → + // ebenso viele Primitives) sprengt der Spread-Operator die Argumentzahl- + // Grenze von `push` (RangeError "Maximum call stack size exceeded") — s. + // dieselbe, bereits dokumentierte Falle in `swissBuildings3d.ts::concatMeshes`/ + // `dwgParser.ts`. Reine `for`-Schleife ist unbegrenzt sicher. + if (d.greyed) { + for (const pr of p.primitives) primitives.push({ ...pr, greyed: true }); + } else { + for (const pr of p.primitives) primitives.push(pr); + } extend(p.bounds); } @@ -580,8 +615,9 @@ export function generateVisibleLevelsPlan( showReferenceLines, mono, true, + scaleDenominator, ); - primitives.push(...activePlan.primitives); + for (const pr of activePlan.primitives) primitives.push(pr); extend(activePlan.bounds); return { primitives, bounds, backgroundImages: activePlan.backgroundImages }; @@ -843,6 +879,12 @@ function computeBounds( } else if (g.shape === "dimension") { g.pts.forEach(acc); } else if (g.shape === "kote") acc(g.at); + else if (g.shape === "detailref") acc(g.at); + else if (g.shape === "scalebar") { + acc(g.at); + acc({ x: g.at.x + g.segmentLength * g.segments, y: g.at.y }); + } + else if (g.shape === "pointmarker") acc(g.at); else if (g.shape === "text") acc(g.at); else if (g.shape === "image") { acc(g.min); acc(g.max); } } diff --git a/src/plan/generatePlan/drawing2d.test.ts b/src/plan/generatePlan/drawing2d.test.ts index 34d4831..584d691 100644 --- a/src/plan/generatePlan/drawing2d.test.ts +++ b/src/plan/generatePlan/drawing2d.test.ts @@ -120,6 +120,33 @@ describe("addDrawing2D — spline", () => { const last = lines[lines.length - 1]; expect(last.b).toEqual(lines[0].a); }); + + it("mode:'control' rendert einen B-Spline (Kontrollpunkt-Modus) statt Catmull-Rom — berührt den inneren Kontrollpunkt NICHT", () => { + const d: Drawing2D = { + id: "s3", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "spline", + pts: [{ x: 0, y: 0 }, { x: 2, y: 10 }, { x: 6, y: 10 }, { x: 8, y: 0 }], + closed: false, + mode: "control", + }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + const lines = out.filter((p): p is Extract => p.kind === "line"); + expect(lines[0].a).toEqual({ x: 0, y: 0 }); // geklemmt: Start exakt getroffen + const last = lines[lines.length - 1]; + expect(last.b.x).toBeCloseTo(8, 6); + expect(last.b.y).toBeCloseTo(0, 6); + // Der innere Kontrollpunkt (2,10) darf NICHT auf der Kurve liegen (Gegensatz + // zu Catmull-Rom, das interpoliert) — sonst wäre es fälschlich derselbe + // Sampler wie im Default-Modus. + const touchesInner = lines.some((ln) => Math.hypot(ln.a.x - 2, ln.a.y - 10) < 1e-6); + expect(touchesInner).toBe(false); + }); }); describe("addDrawing2D — dimension (SIA 400 B.5.3)", () => { @@ -271,6 +298,46 @@ describe("addDrawing2D — xline (Konstruktionslinie)", () => { }); }); +describe("addDrawing2D — ray (Strahl)", () => { + it("verlängert NUR über b hinaus — a bleibt der feste Anker", () => { + const d: Drawing2D = { + id: "r1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "ray", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + const l = out[0]; + if (l.kind === "line") { + // a bleibt EXAKT der Anker (keine Verlängerung rückwärts). + expect(l.a).toEqual({ x: 0, y: 0 }); + // b wird weit über den Richtungspunkt hinaus verlängert. + expect(l.b.x).toBeGreaterThan(500); + expect(l.b.y).toBeCloseTo(0, 6); + expect(l.dash).not.toBeNull(); + expect(l.drawingId).toBe("r1"); + } else { + throw new Error("expected a line primitive"); + } + }); + + it("entartet (a===b) erzeugt kein Primitiv", () => { + const d: Drawing2D = { + id: "r2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "ray", a: { x: 2, y: 2 }, b: { x: 2, y: 2 } }, + }; + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(0); + }); +}); + describe("addDrawing2D — polyline mit bulge (Bogen-Segmente)", () => { it("ohne bulge: unverändertes Verhalten (gerade Segmente, ein Primitiv je Segment)", () => { const d: Drawing2D = { @@ -286,7 +353,7 @@ describe("addDrawing2D — polyline mit bulge (Bogen-Segmente)", () => { expect(lines.length).toBe(2); }); - it("mit bulge an einem Segment: tessellierter Bogen statt einer Geraden", () => { + it("mit bulge an einem Segment: ECHTER Bogen (drawingArc) statt Geradenstücken", () => { const d: Drawing2D = { id: "pl2", type: "drawing2d", @@ -301,16 +368,37 @@ describe("addDrawing2D — polyline mit bulge (Bogen-Segmente)", () => { }; const out: Primitive[] = []; addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + + // Segment 0 (Halbkreis, bulge=1) → EIN Bogen-Primitiv; Segment 1 (gerade) + // → EINE Linie. Früher war der Bogen in ~15 Geradenstücke tesselliert, + // wodurch er im DXF als Kette von LINEs landete statt als ARC. + const arcs = out.filter((p) => p.kind === "drawingArc"); const lines = out.filter((p) => p.kind === "line"); - // Segment 0 (Halbkreis, bulge=1) tessellierter Bogen → mehrere Teilstücke; - // Segment 1 bleibt eine einzelne Gerade → insgesamt > 2 (statt 2 wie oben). - expect(lines.length).toBeGreaterThan(2); - // Erster und letzter Punkt der gesamten Kette bleiben exakt die echten Endpunkte. - if (lines[0].kind === "line") { - expect(lines[0].a).toEqual({ x: 0, y: 0 }); + expect(arcs.length).toBe(1); + expect(lines.length).toBe(1); + + // Halbkreis über der Sehne (0,0)→(2,0): Mittelpunkt (1,0), Radius 1. + const arc = arcs[0]; + if (arc.kind === "drawingArc") { + expect(arc.center.x).toBeCloseTo(1, 9); + expect(arc.center.y).toBeCloseTo(0, 9); + expect(arc.r).toBeCloseTo(1, 9); + expect(arc.drawingId).toBe("pl2"); + // Die Winkel beschreiben exakt die Endpunkte des Segments (in der + // CCW-Konvention von `drawingArc` ggf. vertauscht). + const p0 = { x: arc.center.x + arc.r * Math.cos(arc.a0), y: arc.center.y + arc.r * Math.sin(arc.a0) }; + const p1 = { x: arc.center.x + arc.r * Math.cos(arc.a1), y: arc.center.y + arc.r * Math.sin(arc.a1) }; + const ends = [p0, p1].sort((u, v) => u.x - v.x); + expect(ends[0].x).toBeCloseTo(0, 9); + expect(ends[0].y).toBeCloseTo(0, 9); + expect(ends[1].x).toBeCloseTo(2, 9); + expect(ends[1].y).toBeCloseTo(0, 9); } - if (lines[lines.length - 1].kind === "line") { - expect(lines[lines.length - 1].b).toEqual({ x: 4, y: 0 }); + + // Das gerade Segment bleibt unverändert eine Linie mit den echten Endpunkten. + if (lines[0].kind === "line") { + expect(lines[0].a).toEqual({ x: 2, y: 0 }); + expect(lines[0].b).toEqual({ x: 4, y: 0 }); } }); @@ -410,6 +498,51 @@ describe("addDrawing2D — block (Symbol-Instanz)", () => { } }); + it("scale zieht sowohl Position ALS AUCH Grössenfelder mit (REGRESSION: circle.r skalierte nicht mit)", () => { + const proj = project(); + proj.blockDefs = [ + { id: "blk1", name: "Kreis-Symbol", geom2d: [{ shape: "circle", center: { x: 1, y: 0 }, r: 1 }] }, + ]; + const d: Drawing2D = { + id: "i1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "block", blockDefId: "blk1", at: { x: 10, y: 10 }, rotation: 0, scale: 2 }, + }; + const out: Primitive[] = []; + addDrawing2D(out, proj, d, false, lwByCode, colorByCode, catByCode); + expect(out.length).toBe(1); + const c = out[0]; + if (c.kind === "drawingCircle") { + // Lokal (1,0) r=1, skaliert ×2 → (2,0), r=2, verschoben um (10,10). + expect(c.center.x).toBeCloseTo(12, 6); + expect(c.center.y).toBeCloseTo(10, 6); + expect(c.r).toBeCloseTo(2, 6); + } else { + throw new Error("expected a drawingCircle primitive"); + } + }); + + it("fehlendes scale-Feld verhält sich wie scale=1 (unverändert)", () => { + const proj = project(); + proj.blockDefs = [ + { id: "blk1", name: "Kreis-Symbol", geom2d: [{ shape: "circle", center: { x: 0, y: 0 }, r: 1 }] }, + ]; + const d: Drawing2D = { + id: "i1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "block", blockDefId: "blk1", at: { x: 0, y: 0 }, rotation: 0 }, + }; + const out: Primitive[] = []; + addDrawing2D(out, proj, d, false, lwByCode, colorByCode, catByCode); + const c = out[0]; + if (c.kind === "drawingCircle") expect(c.r).toBeCloseTo(1, 6); + else throw new Error("expected a drawingCircle primitive"); + }); + it("unbekannte blockDefId rendert nichts (kein Crash)", () => { const d: Drawing2D = { id: "i2", @@ -423,3 +556,278 @@ describe("addDrawing2D — block (Symbol-Instanz)", () => { expect(out.length).toBe(0); }); }); + +describe("addDrawing2D — Bemassung: Strichstärken je Bestandteil", () => { + const dim = (extra: Record = {}): Drawing2D => ({ + id: "dim1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 1, ...extra }, + }); + + /** Alle Linien-Primitive der Bemassung nach Strichstärke gruppiert. */ + const weights = (d: Drawing2D) => { + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode); + return out.filter((p) => p.kind === "line").map((p) => (p.kind === "line" ? p.weightMm : 0)); + }; + + it("Default unverändert: Mass-/Hilfslinien erben die Elementstärke, Massstriche doppelt", () => { + const w = weights(dim()); + const base = Math.min(...w); + // 2 Hilfslinien + 1 Masslinie mit Basisstärke, 2 Massstriche doppelt. + expect(w.filter((x) => x === base).length).toBe(3); + expect(w.filter((x) => Math.abs(x - base * 2) < 1e-9).length).toBe(2); + }); + + it("jede der drei Stärken ist einzeln übersteuerbar", () => { + const w = weights(dim({ lineWeightMm: 0.5, extWeightMm: 0.13, tickWeightMm: 0.7 })); + expect(w.filter((x) => x === 0.13).length).toBe(2); // Hilfslinien + expect(w.filter((x) => x === 0.5).length).toBe(1); // Masslinie + expect(w.filter((x) => x === 0.7).length).toBe(2); // Massstriche + }); + + it("Teil-Übersteuerung lässt die übrigen auf ihrem Default", () => { + const w = weights(dim({ tickWeightMm: 0.9 })); + const base = Math.min(...w); + expect(w.filter((x) => x === base).length).toBe(3); + expect(w.filter((x) => x === 0.9).length).toBe(2); + }); +}); + +describe("addDrawing2D — Bemassung: Papier-mm statt Modellmass", () => { + const dim: Drawing2D = { + id: "dimS", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "dimension", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], + offset: 1, + tickLenMm: 4, + }, + }; + + /** Länge des ersten Massstrichs (Diagonale) im erzeugten Plan. */ + const tickLength = (scale: number) => { + const out: Primitive[] = []; + addDrawing2D(out, project(), dim, false, lwByCode, colorByCode, catByCode, scale); + // Massstriche sind die kürzesten Linien (Diagonalen an den Enden). + const lens = out + .filter((p) => p.kind === "line") + .map((p) => (p.kind === "line" ? Math.hypot(p.b.x - p.a.x, p.b.y - p.a.y) : 0)); + return Math.min(...lens); + }; + + it("derselbe Papierwert ergibt bei grösserem Massstab ein grösseres Modellmass", () => { + // 4 mm Papier: 1:50 → 0.2 m, 1:100 → 0.4 m im Modell. + expect(tickLength(50)).toBeCloseTo(0.2, 9); + expect(tickLength(100)).toBeCloseTo(0.4, 9); + }); + + it("das Verhältnis folgt exakt dem Massstabsverhältnis (gleiche Wirkung auf dem Papier)", () => { + expect(tickLength(200) / tickLength(50)).toBeCloseTo(4, 9); + }); + + it("ohne gesetzten Wert gilt der Default — ebenfalls massstabsabhängig", () => { + const plain: Drawing2D = { ...dim, geom: { ...dim.geom, tickLenMm: undefined } as typeof dim.geom }; + const out: Primitive[] = []; + addDrawing2D(out, project(), plain, false, lwByCode, colorByCode, catByCode, 50); + const lens = out + .filter((p) => p.kind === "line") + .map((p) => (p.kind === "line" ? Math.hypot(p.b.x - p.a.x, p.b.y - p.a.y) : 0)); + // Default 3 mm bei 1:50 = 0.15 m (der frühere feste Modellwert). + expect(Math.min(...lens)).toBeCloseTo(0.15, 9); + }); +}); + +describe("addDrawing2D — Linienenden (Pfeilspitzen & Co.)", () => { + const line = (endMarks?: Drawing2D["endMarks"]): Drawing2D => ({ + id: "em1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }, + endMarks, + }); + const render = (d: Drawing2D, scale = 50) => { + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode, scale); + return out; + }; + + it("ohne Angabe bleibt alles wie bisher: nur die Linie, keine Zusatzgeometrie", () => { + const out = render(line()); + expect(out.length).toBe(1); + expect(out[0].kind).toBe("line"); + }); + + it("gefüllter Pfeil erzeugt ein Dreieck UND verkürzt die Linie dort", () => { + const out = render(line({ end: "arrow", sizeMm: 4 })); + const polys = out.filter((p) => p.kind === "polygon"); + expect(polys.length).toBe(1); + if (polys[0].kind === "polygon") expect(polys[0].pts.length).toBe(3); + // 4 mm bei 1:50 = 0.2 m Rückzug → Linie endet bei x = 3.8. + const ln = out.find((p) => p.kind === "line"); + if (ln?.kind === "line") expect(ln.b.x).toBeCloseTo(3.8, 9); + }); + + it("offene Spitze zeichnet zwei Striche und lässt die Linie durchlaufen", () => { + const out = render(line({ end: "arrowOpen" })); + const lines = out.filter((p) => p.kind === "line"); + expect(lines.length).toBe(3); // Linie + zwei Schenkel + const main = lines[0]; + if (main.kind === "line") expect(main.b.x).toBeCloseTo(4, 9); + }); + + it("Punkt-Ende erzeugt einen Kreis, Quadrat-Ende ein Viereck", () => { + expect(render(line({ start: "dot" })).some((p) => p.kind === "drawingCircle")).toBe(true); + const sq = render(line({ end: "square" })).find((p) => p.kind === "polygon"); + if (sq?.kind === "polygon") expect(sq.pts.length).toBe(4); + }); + + it("beide Enden gleichzeitig, und die Grösse folgt dem Massstab (Papier-mm)", () => { + const at50 = render(line({ start: "arrow", end: "arrow", sizeMm: 4 }), 50); + const at100 = render(line({ start: "arrow", end: "arrow", sizeMm: 4 }), 100); + expect(at50.filter((p) => p.kind === "polygon").length).toBe(2); + const seg50 = at50.find((p) => p.kind === "line"); + const seg100 = at100.find((p) => p.kind === "line"); + // Rückzug 0.2 m bei 1:50, 0.4 m bei 1:100 — an BEIDEN Enden. + if (seg50?.kind === "line" && seg100?.kind === "line") { + expect(seg50.a.x).toBeCloseTo(0.2, 9); + expect(seg100.a.x).toBeCloseTo(0.4, 9); + } + }); + + it("geschlossene Formen ignorieren Linienenden (sie haben keine)", () => { + const ring: Drawing2D = { + id: "em2", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }], + closed: true, + }, + endMarks: { start: "arrow", end: "arrow" }, + }; + expect(render(ring).some((p) => p.kind === "polygon" && p.pts.length === 3 && p.fill !== "none")).toBe( + false, + ); + }); + + it("an einem Bogen-Segment folgt die Spitze der BOGEN-Tangente, nicht der Sehne", () => { + const d: Drawing2D = { + id: "em3", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], + closed: false, + bulge: [1], // Halbkreis + }, + endMarks: { end: "arrow", sizeMm: 4 }, + }; + const poly = render(d).find((p) => p.kind === "polygon"); + expect(poly).toBeDefined(); + if (poly?.kind === "polygon") { + // Halbkreis über (0,0)→(2,0): im Endpunkt (2,0) steht die Tangente + // SENKRECHT zur Sehne. Die Spitze sitzt auf (2,0), ihr Fusspunkt liegt + // daher senkrecht darüber/darunter — nicht seitlich. + const tip = poly.pts[0]; + expect(tip.x).toBeCloseTo(2, 9); + expect(tip.y).toBeCloseTo(0, 9); + const baseMid = { + x: (poly.pts[1].x + poly.pts[2].x) / 2, + y: (poly.pts[1].y + poly.pts[2].y) / 2, + }; + expect(Math.abs(baseMid.x - tip.x)).toBeLessThan(1e-6); + expect(Math.abs(baseMid.y - tip.y)).toBeGreaterThan(0.1); + } + }); +}); + +describe("addDrawing2D — Objekt-Transparenz", () => { + const poly = (opacity?: number): Drawing2D => ({ + id: "op1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { + shape: "polyline", + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }], + closed: true, + }, + // Füllung über die Vollton-Füllfarbe (die Fixture führt keine Schraffuren). + fillColor: "#cccccc", + opacity, + }); + const render = (d: Drawing2D) => { + const out: Primitive[] = []; + addDrawing2D(out, project(), d, false, lwByCode, colorByCode, catByCode, 50); + return out; + }; + + it("ohne Angabe tragen die Primitive keine Deckkraft (unverändertes Verhalten)", () => { + expect(render(poly()).every((p) => p.opacity === undefined)).toBe(true); + }); + + it("wird auf ALLE Primitive des Elements gestempelt — Striche wie Füllung", () => { + const out = render(poly(0.5)); + expect(out.length).toBeGreaterThan(1); + expect(out.every((p) => p.opacity === 0.5)).toBe(true); + // Es sind wirklich beide Sorten dabei (sonst wäre der Test wertlos). + expect(out.some((p) => p.kind === "line")).toBe(true); + expect(out.some((p) => p.kind === "polygon")).toBe(true); + }); + + it("Deckkraft 1 stempelt nichts (kein unnötiges Feld im Plan)", () => { + expect(render(poly(1)).every((p) => p.opacity === undefined)).toBe(true); + }); + + it("negative Werte werden auf 0 geklemmt", () => { + expect(render(poly(-3)).every((p) => p.opacity === 0)).toBe(true); + }); +}); + +describe("addDrawing2D — Strichmuster-Massstab (LTSCALE je Objekt)", () => { + const dashed = (dashScale?: number): Drawing2D => ({ + id: "ds1", + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }, + lineStyleId: "dash", + dashScale, + }); + const dashOf = (d: Drawing2D) => { + const out: Primitive[] = []; + const p = { ...project(), lineStyles: [{ id: "dash", name: "Strich", weight: 0.2, color: "#000", dash: [2, 1] }] }; + addDrawing2D(out, p, d, false, lwByCode, colorByCode, catByCode, 50); + const ln = out.find((x) => x.kind === "line"); + return ln?.kind === "line" ? ln.dash : undefined; + }; + + it("ohne Angabe bleibt das Muster exakt wie im Linienstil", () => { + expect(dashOf(dashed())).toEqual([2, 1]); + }); + + it("streckt Striche UND Lücken um denselben Faktor", () => { + expect(dashOf(dashed(2))).toEqual([4, 2]); + expect(dashOf(dashed(0.5))).toEqual([1, 0.5]); + }); + + it("Faktor 1 lässt das Muster unangetastet (dieselbe Referenz)", () => { + expect(dashOf(dashed(1))).toEqual([2, 1]); + }); + + it("unsinnige Faktoren (0/negativ) werden ignoriert statt das Muster zu verschlucken", () => { + expect(dashOf(dashed(0))).toEqual([2, 1]); + expect(dashOf(dashed(-2))).toEqual([2, 1]); + }); +}); diff --git a/src/plan/generatePlan/drawing2d.ts b/src/plan/generatePlan/drawing2d.ts index 675bb31..95802d4 100644 --- a/src/plan/generatePlan/drawing2d.ts +++ b/src/plan/generatePlan/drawing2d.ts @@ -3,7 +3,7 @@ // circle/arc/text/image) in Plan-Primitive ab. Farbe/Strichstärke kommen aus // dem optionalen LineStyle, sonst aus der Kategorie. -import type { Drawing2D, LayerCategory, Project, Vec2 } from "../../model/types"; +import type { Drawing2D, EndMark, LayerCategory, Project, Vec2 } from "../../model/types"; import { NO_HATCH, WALL_FALLBACK_MM, @@ -13,19 +13,24 @@ import { resolveStrokeWeight, type Primitive, } from "./shared"; -import { ellipsePts, sampleBezierChain, sampleCatmullRom } from "../../tools/curves"; -import { mvGeom } from "../../tools/transform"; -import { bulgeArcPoints } from "../../geometry/bulge"; +import { ellipsePts, sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "../../tools/curves"; +import { scaleGeom } from "../../tools/transform"; +import { bulgeArc, bulgeArcPoints } from "../../geometry/bulge"; +import { END_MARK_DEFAULT_SIZE_MM, addEndMark, pullBack } from "./endMarks"; +import { + DEFAULT_SCALE_DENOMINATOR, + DIM_DEFAULTS_MM, + dimTextFrame, + dimTextPos, + mmToModel, +} from "../../model/dimension"; // ── Bemassung (SIA 400 B.5.3) ──────────────────────────────────────────────── // Modell-Meter-Konstanten für rein grafische (nicht reale) Bemassungs-Details // — analog zu DEFAULT_TEXT_HEIGHT_M (text.ts): fest gewählt, damit sie bei der // üblichen Plan-Massstäben (1:50…1:100) lesbar wirken, nicht dynamisch an den // Massstab gekoppelt (wie auch die übrige Textgrösse im Plan). -const DIM_GAP_M = 0.05; // Abstand Masshilfslinie → bemessener Punkt -const DIM_OVERSHOOT_M = 0.05; // Überstand der Masshilfslinie über die Masslinie hinaus -const DIM_TICK_LEN_M = 0.15; // Länge des Massstrichs (Diagonale an den Masslinien-Enden) -const DIM_TEXT_HEIGHT_M = 0.2; // Schrifthöhe der Masszahl +// Defaults (Papier-mm) liegen in `model/dimension.ts` — geteilt mit den Griffen. /** Formatiert eine Länge (Meter) als Masszahl: 2 Dezimalstellen (SIA 400 B.5.2/B.5.4, „3.25"/„518.60"). */ function formatDimLabel(m: number): string { @@ -38,16 +43,29 @@ function formatDimLabel(m: number): string { * Extrahiert, damit eine Masskette (`shape:"dimension"`, `pts.length` ≥ 2) * je aufeinanderfolgendem Punktpaar dasselbe Rendering wiederverwenden kann. */ +interface DimStyle { + gap: number; + overshoot: number; + tickLen: number; + textHeight: number; + /** Strichstärken (Papier-mm) für Masslinie · Masshilfslinien · Massstriche. */ + lineWeightMm: number; + extWeightMm: number; + tickWeightMm: number; + /** Versatz der Masszahl (entlang/quer zur Masslinie), 0/0 = Standardlage. */ + textOffset: { along: number; perp: number }; +} + function addDimensionSegment( out: Primitive[], a: Vec2, b: Vec2, offset: number, - weightMm: number, dash: number[] | null, color: string, greyed: boolean, drawingId: string, + style: DimStyle, ): void { const dx = b.x - a.x, dy = b.y - a.y; const lineLen = Math.hypot(dx, dy); @@ -57,28 +75,29 @@ function addDimensionSegment( const sign = offset >= 0 ? 1 : -1; const dimA: Vec2 = { x: a.x + nx * offset, y: a.y + ny * offset }; const dimB: Vec2 = { x: b.x + nx * offset, y: b.y + ny * offset }; - const extLine = (from: Vec2, to: Vec2) => - out.push({ kind: "line", a: from, b: to, cls: "draw2d", weightMm, dash, color, greyed, drawingId }); + const lineAt = (from: Vec2, to: Vec2, w: number) => + out.push({ kind: "line", a: from, b: to, cls: "draw2d", weightMm: w, dash, color, greyed, drawingId }); + const extLine = (from: Vec2, to: Vec2) => lineAt(from, to, style.extWeightMm); extLine( - { x: a.x + nx * DIM_GAP_M * sign, y: a.y + ny * DIM_GAP_M * sign }, - { x: dimA.x + nx * DIM_OVERSHOOT_M * sign, y: dimA.y + ny * DIM_OVERSHOOT_M * sign }, + { x: a.x + nx * style.gap * sign, y: a.y + ny * style.gap * sign }, + { x: dimA.x + nx * style.overshoot * sign, y: dimA.y + ny * style.overshoot * sign }, ); extLine( - { x: b.x + nx * DIM_GAP_M * sign, y: b.y + ny * DIM_GAP_M * sign }, - { x: dimB.x + nx * DIM_OVERSHOOT_M * sign, y: dimB.y + ny * DIM_OVERSHOOT_M * sign }, + { x: b.x + nx * style.gap * sign, y: b.y + ny * style.gap * sign }, + { x: dimB.x + nx * style.overshoot * sign, y: dimB.y + ny * style.overshoot * sign }, ); - extLine(dimA, dimB); + lineAt(dimA, dimB, style.lineWeightMm); // die eigentliche Masslinie // Massstriche: 45°-Diagonale (Winkelhalbierende von Richtung/Normale), an // beiden Enden PARALLEL (nicht gespiegelt) — wie in SIA 400 Figur 13. const tx = (ux + nx) / Math.SQRT2, ty = (uy + ny) / Math.SQRT2; - const half = DIM_TICK_LEN_M / 2; + const half = style.tickLen / 2; const tick = (pt: Vec2) => out.push({ kind: "line", a: { x: pt.x - tx * half, y: pt.y - ty * half }, b: { x: pt.x + tx * half, y: pt.y + ty * half }, cls: "draw2d", - weightMm: weightMm * 2, + weightMm: style.tickWeightMm, dash: null, color, greyed, @@ -86,17 +105,17 @@ function addDimensionSegment( }); tick(dimA); tick(dimB); - // Masszahl: Mitte der Masslinie, leicht abgesetzt, nie kopfüber lesbar. - let angle = Math.atan2(dy, dx); - if (Math.cos(angle) < 0) angle += Math.PI; - const upx = -Math.sin(angle), upy = Math.cos(angle); // Links-Normale der ENDGÜLTIGEN Richtung - const mid: Vec2 = { x: (dimA.x + dimB.x) / 2, y: (dimA.y + dimB.y) / 2 }; + // Masszahl: Standardlage mittig knapp über der Masslinie (nie kopfüber), + // plus optionaler Nutzer-Versatz — Lage UND Achsen kommen aus dem geteilten + // Helfer, damit der Masszahl-GRIFF (projectSlice) nicht auseinanderdriftet. + const frame = dimTextFrame(a, b, offset, style.textHeight); + const at = dimTextPos(a, b, offset, style.textHeight, style.textOffset); out.push({ kind: "drawingText", - at: { x: mid.x + upx * DIM_TEXT_HEIGHT_M * 0.6, y: mid.y + upy * DIM_TEXT_HEIGHT_M * 0.6 }, + at, text: formatDimLabel(lineLen), - heightM: DIM_TEXT_HEIGHT_M, - angle, + heightM: style.textHeight, + angle: frame.angle, color, greyed, drawingId, @@ -109,6 +128,19 @@ const KOTE_TRI_HALF_W_M = KOTE_TRI_SIZE_M * 0.6; const KOTE_TEXT_HEIGHT_M = 0.2; const KOTE_TEXT_GAP_M = 0.08; // Abstand Dreieck-Basis → Zahl +// ── Detail-/Schnitt-Verweis-Symbol ─────────────────────────────────────────── +const DETAILREF_RADIUS_M = 0.3; // Kreis-Radius (fixe Modell-Meter, wie „kote") +const DETAILREF_TEXT_HEIGHT_M = 0.2; +const POINTMARKER_RADIUS_M = 0.08; // Kreis-Radius (fixe Modell-Meter, wie „kote"/„detailref") +const POINTMARKER_CROSS_M = 0.12; // Kreuz-Halbarm — etwas grösser als der Kreis (ragt sichtbar heraus) + +// ── Massstabsbalken ────────────────────────────────────────────────────────── +// Papier-mm (wie Bemassung/Kote) — die Balkenlänge selbst ist Modell-Meter, +// s. Kommentar am `scalebar`-Fall. +const SCALEBAR_HEIGHT_MM = 1.5; +const SCALEBAR_TICK_MM = 1; +const SCALEBAR_TEXT_MM = 3; + /** Formatiert einen Höhenwert (SIA 400 B.5.4, Figur 18): „+3.25" · „±0.00" · „-0.10". */ function formatKoteLabel(value: number): string { if (Math.abs(value) < 1e-6) return "±0.00"; @@ -121,42 +153,15 @@ const XLINE_WEIGHT_MM = 0.13; // dünnste übliche Linienstärke (nie dicker als const XLINE_DASH: number[] = [0.3, 0.1, 0.03, 0.1]; // Strich-Punkt (CAD-Mittellinien-Konvention) // ── Leader (Vorführungspfeil) ──────────────────────────────────────────────── -const LEADER_ARROW_LEN_M = 0.12; -const LEADER_ARROW_HALF_W_M = 0.045; -/** Dünne Linie `from`→`to` + gefüllte Pfeilspitze bei `to` (Ziel des Leaders). */ -function addLeaderLine( - out: Primitive[], - from: Vec2, - to: Vec2, - weightMm: number, - color: string, - greyed: boolean, - drawingId: string, -): void { - const dx = to.x - from.x, dy = to.y - from.y; - const len = Math.hypot(dx, dy); - if (len < 1e-6) return; - const ux = dx / len, uy = dy / len; - const nx = -uy, ny = ux; - const base: Vec2 = { x: to.x - ux * LEADER_ARROW_LEN_M, y: to.y - uy * LEADER_ARROW_LEN_M }; - out.push({ kind: "line", a: from, b: base, cls: "draw2d", weightMm, dash: null, color, greyed, drawingId }); - out.push({ - kind: "polygon", - pts: [ - to, - { x: base.x + nx * LEADER_ARROW_HALF_W_M, y: base.y + ny * LEADER_ARROW_HALF_W_M }, - { x: base.x - nx * LEADER_ARROW_HALF_W_M, y: base.y - ny * LEADER_ARROW_HALF_W_M }, - ], - fill: color, - stroke: color, - strokeWidthMm: weightMm, - hatch: NO_HATCH, - greyed, - drawingId, - }); -} +/** + * Erzeugt die Plan-Primitive EINES 2D-Elements. Hülle um + * {@link addDrawing2DInner}: sie stempelt am Ende die Objekt-Transparenz + * (`Drawing2D.opacity`) auf ALLE hier entstandenen Primitive — an einer + * Stelle statt an jeder der dutzenden Push-Stellen, und dadurch auch für + * rekursiv erzeugte Block-Geometrie automatisch korrekt. + */ export function addDrawing2D( out: Primitive[], project: Project, @@ -165,6 +170,37 @@ export function addDrawing2D( lwByCode: Map, colorByCode: Map, catByCode: Map, + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, +): void { + const start = out.length; + addDrawing2DInner(out, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator); + const op = d.opacity; + if (op === undefined || op >= 1) return; + const clamped = Math.max(0, op); + for (let i = start; i < out.length; i++) { + const p = out[i]; + // Bilder tragen bereits eine eigene Deckkraft — beide multiplizieren sich. + out[i] = + p.kind === "drawingImage" + ? { ...p, opacity: p.opacity * clamped } + : { ...p, opacity: (p.opacity ?? 1) * clamped }; + } +} + +function addDrawing2DInner( + out: Primitive[], + project: Project, + d: Drawing2D, + greyed: boolean, + lwByCode: Map, + colorByCode: Map, + catByCode: Map, + /** + * Papier-Massstab (1:N) dieses Plans — nur für Bemassungs-Feinheiten, die + * in Papier-mm angegeben sind. Default 1:100, damit bestehende Aufrufer + * (u. a. Tests) unverändert funktionieren. + */ + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, ): void { const category = catByCode.get(d.categoryCode); const ls = d.lineStyleId @@ -181,7 +217,11 @@ export function addDrawing2D( category, ls?.weight ?? lwByCode.get(d.categoryCode) ?? WALL_FALLBACK_MM, ); - const dash = ls?.dash ?? null; + // Strichmuster des Linienstils, mit dem Objekt-Massstab gestreckt (LTSCALE). + // Nicht-positive Werte werden ignoriert (ein Muster der Länge 0 wäre unsichtbar). + const dashScale = d.dashScale && d.dashScale > 0 ? d.dashScale : 1; + const rawDash = ls?.dash ?? null; + const dash = rawDash && dashScale !== 1 ? rawDash.map((v) => v * dashScale) : rawDash; // Drawing2D trägt kein Bauteil → die By-Layer-Quelle ist hier die einzige // Alternative zum expliziten Wert (kein Component-Fallback); Default // "object"/undefined bleibt exakt das heutige Verhalten. @@ -196,6 +236,33 @@ export function addDrawing2D( const seg = (a: Vec2, b: Vec2) => out.push({ kind: "line", a, b, cls: "draw2d", weightMm, dash, zigzag, motif, color, greyed, drawingId: d.id }); + /** + * Enden einer OFFENEN, bereits tessellierten Punktfolge zeichnen und die + * Folge an den Enden so weit zurückziehen, wie eine gefüllte Spitze sie + * überdeckt. Tangentenrichtung = erstes bzw. letztes Stützpunktpaar. + */ + const withEndMarks = (pts: Vec2[]): Vec2[] => { + if (pts.length < 2 || (!d.endMarks?.start && !d.endMarks?.end)) return pts; + const next = [...pts]; + const dirStart = { x: next[0].x - next[1].x, y: next[0].y - next[1].y }; + const last = next.length - 1; + const dirEnd = { x: next[last].x - next[last - 1].x, y: next[last].y - next[last - 1].y }; + next[0] = pullBack(next[0], dirStart, endMark(next[0], dirStart, d.endMarks?.start)); + next[last] = pullBack(next[last], dirEnd, endMark(next[last], dirEnd, d.endMarks?.end)); + return next; + }; + + // Ein Linienende dieser Form zeichnen (nur offene Formen rufen das auf). + // `outward` zeigt aus der Form heraus; zurück kommt, um wie viel die Linie + // dort verkürzt werden soll (nur bei gefüllter Spitze > 0). + const endMark = (at: Vec2, outward: Vec2, mark: EndMark | undefined): number => + addEndMark(out, at, outward, mark, d.endMarks?.sizeMm ?? END_MARK_DEFAULT_SIZE_MM, scaleDenominator, { + weightMm, + color, + greyed, + drawingId: d.id, + }); + /** * Gefüllte Fläche einer GESCHLOSSENEN Form: trägt die Vollton-Füllfarbe * (`d.fillColor`, sonst transparent) UND die optionale Füllschraffur @@ -218,16 +285,29 @@ export function addDrawing2D( // Drawing2D trägt kein Bauteil → Vordergrund/Schraffur-Override direkt aus // d.foreground/d.hatchId bzw. der Ebene (Attribut „Nach System" ⇒ // undefined ⇒ HatchStyle.color-Fallback bzw. NO_HATCH). - hatch: hatchId ? resolveHatch(project, hatchId, undefined, foreground) : NO_HATCH, + hatch: hatchId + ? resolveHatch(project, hatchId, undefined, foreground, { + angleDeg: d.hatchAngleDeg, + scale: d.hatchScale, + origin: d.hatchOrigin, + }) + : NO_HATCH, greyed, drawingId: d.id, }); const g = d.geom; switch (g.shape) { - case "line": - seg(g.a, g.b); + case "line": { + // Linienenden (Pfeil & Co.) an beiden Seiten; die Linie wird dort + // verkürzt, wo eine gefüllte Spitze sie ohnehin überdeckt. + const dA = { x: g.a.x - g.b.x, y: g.a.y - g.b.y }; + const dB = { x: g.b.x - g.a.x, y: g.b.y - g.a.y }; + const cutA = endMark(g.a, dA, d.endMarks?.start); + const cutB = endMark(g.b, dB, d.endMarks?.end); + seg(pullBack(g.a, dA, cutA), pullBack(g.b, dB, cutB)); break; + } case "xline": { // Konstruktionslinie: weit über a/b hinaus verlängert (wirkt unendlich), // immer im Strich-Punkt-Muster gezeichnet (überstimmt den LineStyle- @@ -249,10 +329,33 @@ export function addDrawing2D( }); break; } + case "ray": { + // Wie „xline", aber NUR über `b` hinaus verlängert — `a` bleibt der + // feste Anker (halb-unendlich statt beidseitig). + const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y; + const len = Math.hypot(dx, dy); + if (len < 1e-6) break; + const ux = dx / len, uy = dy / len; + out.push({ + kind: "line", + a: g.a, + b: { x: g.b.x + ux * XLINE_EXTEND_M, y: g.b.y + uy * XLINE_EXTEND_M }, + cls: "draw2d", + weightMm: Math.min(weightMm, XLINE_WEIGHT_MM), + dash: XLINE_DASH, + color, + greyed, + drawingId: d.id, + }); + break; + } case "polyline": { - // Bogen-Segmente (`bulge`, DXF-Konvention) zu Geradenstücken tessellieren - // — ohne `bulge` liefert `bulgeArcPoints` exakt `[a,b]`, das Ergebnis ist - // dann bitgleich zum alten reinen Geradenzug (kein Sonderpfad nötig). + // FÜLLUNG weiterhin über die tessellierte Kontur: Poché/Schraffur + // brauchen ein Vieleck, ein Bogen-Primitiv trägt keine Fläche. + // KONTUR dagegen als ECHTE Bögen (`drawingArc`) statt Geradenstücken — + // dadurch bleibt der Bogen bei jedem Zoom rund und kommt im DXF als + // ARC statt als Kette von LINEs an (dasselbe Primitiv, das die + // Kreis-/Bogen-Werkzeuge schon nutzen, inkl. Auswahl + GL-Pfad). const ring: Vec2[] = [g.pts[0]]; for (let i = 0; i < g.pts.length - 1; i++) { const sub = bulgeArcPoints(g.pts[i], g.pts[i + 1], g.bulge?.[i]); @@ -265,7 +368,67 @@ export function addDrawing2D( // die Füllfläche nicht nötig, das SVG-`` schliesst implizit. fillPoly(ring.slice(0, -1)); } - for (let i = 0; i < ring.length - 1; i++) seg(ring[i], ring[i + 1]); + /** Ein Segment a→b: gerade als Linie, gekrümmt als echter Bogen. */ + const emitSegment = (a: Vec2, b: Vec2, bulge: number | undefined) => { + const arc = bulge !== undefined ? bulgeArc(a, b, bulge) : null; + if (!arc) { + seg(a, b); + return; + } + // `drawingArc` läuft per Konvention IMMER gegen den Uhrzeigersinn von + // a0 nach a1 (s. planView/primitives.tsx). Ein im Uhrzeigersinn + // laufender Bulge-Bogen wird daher mit vertauschten Winkeln + // beschrieben — dieselbe Kurve, nur andersherum benannt. + const ccw = arc.sweep >= 0; + out.push({ + kind: "drawingArc", + center: arc.center, + r: arc.r, + a0: ccw ? arc.a0 : arc.a1, + a1: ccw ? arc.a1 : arc.a0, + stroke: color, + weightMm, + dash, + greyed, + drawingId: d.id, + }); + }; + // Linienenden nur an der OFFENEN Polylinie. Die Tangentenrichtung am + // Ende folgt dem ersten/letzten Segment — bei einem BOGEN-Segment ist + // das die Bogentangente dort, nicht die Sehne. + const n = g.pts.length; + const open = !(g.closed && n > 2); + let first = g.pts[0]; + let last = g.pts[n - 1]; + if (open && n >= 2 && (d.endMarks?.start || d.endMarks?.end)) { + const tangentAt = (i: number, atStart: boolean): Vec2 => { + const a = g.pts[i]; + const b = g.pts[i + 1]; + const arc = bulgeArc(a, b, g.bulge?.[i] ?? 0); + if (!arc) { + return atStart ? { x: a.x - b.x, y: a.y - b.y } : { x: b.x - a.x, y: b.y - a.y }; + } + // Radius am betreffenden Bogenende, um 90° gedreht = Tangente; + // Vorzeichen so, dass sie aus der Form heraus zeigt. + const p = atStart ? a : b; + const rx = p.x - arc.center.x; + const ry = p.y - arc.center.y; + const sign = (arc.sweep >= 0 ? 1 : -1) * (atStart ? -1 : 1); + return { x: -ry * sign, y: rx * sign }; + }; + const dirStart = tangentAt(0, true); + const dirEnd = tangentAt(n - 2, false); + first = pullBack(first, dirStart, endMark(first, dirStart, d.endMarks?.start)); + last = pullBack(last, dirEnd, endMark(last, dirEnd, d.endMarks?.end)); + } + for (let i = 0; i < n - 1; i++) { + const a = i === 0 ? first : g.pts[i]; + const b = i === n - 2 ? last : g.pts[i + 1]; + emitSegment(a, b, g.bulge?.[i]); + } + if (!open) { + emitSegment(g.pts[n - 1], g.pts[0], g.bulge?.[n - 1]); + } break; } case "rect": { @@ -321,22 +484,40 @@ export function addDrawing2D( break; } case "bezier": { - const pts = sampleBezierChain(g.pts); + const pts = withEndMarks(sampleBezierChain(g.pts)); for (let i = 0; i < pts.length - 1; i++) seg(pts[i], pts[i + 1]); break; } case "spline": { - const pts = sampleCatmullRom(g.pts, g.closed && g.pts.length > 2); - if (g.closed && g.pts.length > 2) fillPoly(pts); + const closed = g.closed && g.pts.length > 2; + const raw = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed); + if (closed) fillPoly(raw); + // Enden nur an der OFFENEN Kurve (ein Ring hat keine). + const pts = closed ? raw : withEndMarks(raw); for (let i = 0; i < pts.length - 1; i++) seg(pts[i], pts[i + 1]); - if (g.closed && g.pts.length > 2) seg(pts[pts.length - 1], pts[0]); + if (closed) seg(pts[pts.length - 1], pts[0]); break; } case "dimension": { // SIA 400 B.5.3, Figur 14 (Reihenbemassung): jedes aufeinanderfolgende // Punktpaar der Kette ist ein eigenes Mass-Segment, alle teilen `offset`. for (let i = 0; i < g.pts.length - 1; i++) { - addDimensionSegment(out, g.pts[i], g.pts[i + 1], g.offset, weightMm, dash, color, greyed, d.id); + // Papier-mm → Modell-Meter mit dem Massstab DIESES Plans. + const mm = (v: number) => mmToModel(v, scaleDenominator); + const offMm = g.textOffsetsMm?.[i]; + addDimensionSegment(out, g.pts[i], g.pts[i + 1], g.offset, dash, color, greyed, d.id, { + gap: mm(g.gapMm ?? DIM_DEFAULTS_MM.gap), + overshoot: mm(g.overshootMm ?? DIM_DEFAULTS_MM.overshoot), + tickLen: mm(g.tickLenMm ?? DIM_DEFAULTS_MM.tickLen), + textHeight: mm(g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight), + lineWeightMm: g.lineWeightMm ?? weightMm, + extWeightMm: g.extWeightMm ?? weightMm, + // Massstriche bisher fest doppelt so dick — bleibt der Default. + tickWeightMm: g.tickWeightMm ?? weightMm * 2, + textOffset: offMm + ? { along: mm(offMm.along), perp: mm(offMm.perp) } + : { along: 0, perp: 0 }, + }); } break; } @@ -372,6 +553,133 @@ export function addDrawing2D( }); break; } + case "detailref": { + // Zweigeteilte Verweisblase: Kreis + waagrechte Trennlinie, Bezeichner + // oben, Blattname (aufgelöst über sheetLayoutId, sonst manueller + // sheetLabel-Platzhalter) unten — fixe Modell-Meter-Grösse wie „kote". + out.push({ + kind: "drawingCircle", + center: g.at, + r: DETAILREF_RADIUS_M, + fill: "none", + stroke: color, + weightMm, + dash: null, + greyed, + drawingId: d.id, + }); + seg( + { x: g.at.x - DETAILREF_RADIUS_M, y: g.at.y }, + { x: g.at.x + DETAILREF_RADIUS_M, y: g.at.y }, + ); + const sheetName = g.sheetLayoutId + ? (project.layouts ?? []).find((l) => l.id === g.sheetLayoutId)?.name + : undefined; + const lowerText = sheetName ?? g.sheetLabel ?? ""; + // `drawingText` ist immer LINKS verankert (kein Zentrier-Anker ohne + // ein volles RichTextDoc, s. `primitives.tsx` "Baseline am Ankerpunkt + // (links)") — wie beim strukturell ähnlichen „kote" daher ein simpler + // Links-Einzug statt echter Zentrierung. + const textX = g.at.x - DETAILREF_RADIUS_M * 0.62; + out.push({ + kind: "drawingText", + at: { x: textX, y: g.at.y + DETAILREF_RADIUS_M * 0.32 }, + text: g.label, + heightM: DETAILREF_TEXT_HEIGHT_M, + angle: 0, + color, + greyed, + drawingId: d.id, + }); + if (lowerText) { + out.push({ + kind: "drawingText", + at: { x: textX, y: g.at.y - DETAILREF_RADIUS_M * 0.68 }, + text: lowerText, + heightM: DETAILREF_TEXT_HEIGHT_M, + angle: 0, + color, + greyed, + drawingId: d.id, + }); + } + break; + } + case "scalebar": { + // Balkenhöhe/Tick-/Textgrösse sind Papier-mm (unabhängig vom Massstab + // lesbar, wie Bemassung/Kote) — die BALKENLÄNGE selbst ist bereits in + // echten Modell-Metern (`g.segmentLength`) und braucht KEINE eigene + // Umrechnung: der ganze Plan wird ohnehin im Papier-Massstab + // abgebildet, ein 1-Meter-Segment landet dadurch automatisch in der + // richtigen Papiergrösse. + const barH = mmToModel(SCALEBAR_HEIGHT_MM, scaleDenominator); + const tickLen = mmToModel(SCALEBAR_TICK_MM, scaleDenominator); + const textH = mmToModel(SCALEBAR_TEXT_MM, scaleDenominator); + for (let i = 0; i < g.segments; i++) { + const x0 = g.at.x + i * g.segmentLength; + const x1 = x0 + g.segmentLength; + const pts: Vec2[] = [ + { x: x0, y: g.at.y }, + { x: x1, y: g.at.y }, + { x: x1, y: g.at.y + barH }, + { x: x0, y: g.at.y + barH }, + ]; + out.push({ + kind: "polygon", + pts, + fill: i % 2 === 0 ? color : "none", + stroke: color, + strokeWidthMm: weightMm, + hatch: NO_HATCH, + greyed, + drawingId: d.id, + }); + } + // Ticks + kumulative Distanz-Beschriftung an jeder Segmentgrenze + // (0..segments) — „m"-Einheit nur an der LETZTEN Zahl (übliche + // Massstabsbalken-Konvention, kein „m" an jeder Zwischenzahl). + for (let i = 0; i <= g.segments; i++) { + const x = g.at.x + i * g.segmentLength; + seg({ x, y: g.at.y }, { x, y: g.at.y - tickLen }); + const dist = i * g.segmentLength; + const distText = Number.isInteger(dist) ? String(dist) : dist.toFixed(2); + out.push({ + kind: "drawingText", + at: { x: x + textH * 0.25, y: g.at.y - tickLen - textH * 1.2 }, + text: i === g.segments ? `${distText}m` : distText, + heightM: textH, + angle: 0, + color, + greyed, + drawingId: d.id, + }); + } + break; + } + case "pointmarker": { + // Kreuz-in-Kreis — fixe Modell-Meter-Grösse wie „kote"/„detailref" + // (keine Papier-mm-Skalierung, s. Typ-Kommentar in model/types.ts). + out.push({ + kind: "drawingCircle", + center: g.at, + r: POINTMARKER_RADIUS_M, + fill: "none", + stroke: color, + weightMm, + dash: null, + greyed, + drawingId: d.id, + }); + seg( + { x: g.at.x - POINTMARKER_CROSS_M, y: g.at.y }, + { x: g.at.x + POINTMARKER_CROSS_M, y: g.at.y }, + ); + seg( + { x: g.at.x, y: g.at.y - POINTMARKER_CROSS_M }, + { x: g.at.x, y: g.at.y + POINTMARKER_CROSS_M }, + ); + break; + } case "text": if (g.pathPts && g.pathPts.length >= 2) { // Text-entlang-Pfad: eigener Primitive-Typ (echtes SVG textPath), @@ -402,25 +710,48 @@ export function addDrawing2D( drawingId: d.id, }); if (g.leaderTarget) { - addLeaderLine(out, g.at, g.leaderTarget, weightMm, color, greyed, d.id); + // Hinweislinie: Spitze ist eine Eigenschaft, optional über + // `leaderBendPoints` mehrsegmentig (Textanker → Knicke → Spitze, + // s. Typ-Kommentar). Ohne Knickpunkte identisch zum bisherigen + // Verhalten (EIN Segment, gefüllter Pfeil an der Spitze). + const path = [g.at, ...(g.leaderBendPoints ?? []), g.leaderTarget]; + const tipIdx = path.length - 1; + const dir = { x: path[tipIdx].x - path[tipIdx - 1].x, y: path[tipIdx].y - path[tipIdx - 1].y }; + const mark = d.endMarks?.end ?? "arrow"; + const cut = endMark(path[tipIdx], dir, mark); + const tipPulled = pullBack(path[tipIdx], dir, cut); + for (let i = 0; i < tipIdx; i++) { + seg(path[i], i === tipIdx - 1 ? tipPulled : path[i + 1]); + } } break; case "block": { // Block-Instanz trägt selbst keine Geometrie: Definition nachschlagen, - // jede Teilgeometrie per `mvGeom` (Rotation um den Ursprung + Verschiebung - // um `at`) transformieren und REKURSIV über denselben Renderpfad ausgeben - // — eine synthetische Drawing2D-Hülle mit derselben Ebene/Kategorie/ + // jede Teilgeometrie per `scaleGeom` (Skalierung um den Ursprung, dann + // Rotation, dann Verschiebung um `at` — Standard-TRS-Reihenfolge) + // transformieren und REKURSIV über denselben Renderpfad ausgeben — eine + // synthetische Drawing2D-Hülle mit derselben Ebene/Kategorie/ // Farb-Overrides wie die Instanz selbst (Sub-Elemente tragen in v1 keinen // eigenen Stil). Unbekannte/gelöschte `blockDefId` ⇒ nichts rendern. const def = project.blockDefs?.find((b) => b.id === g.blockDefId); if (!def) break; + const scl = g.scale ?? 1; const c = Math.cos(g.rotation), s = Math.sin(g.rotation); const xf = (p: Vec2): Vec2 => ({ - x: g.at.x + p.x * c - p.y * s, - y: g.at.y + p.x * s + p.y * c, + x: g.at.x + (p.x * scl) * c - (p.y * scl) * s, + y: g.at.y + (p.x * scl) * s + (p.y * scl) * c, }); for (const sub of def.geom2d) { - addDrawing2D(out, project, { ...d, geom: mvGeom(sub, xf) }, greyed, lwByCode, colorByCode, catByCode); + addDrawing2D( + out, + project, + { ...d, geom: scaleGeom(sub, xf, scl) }, + greyed, + lwByCode, + colorByCode, + catByCode, + scaleDenominator, + ); } break; } diff --git a/src/plan/generatePlan/endMarks.ts b/src/plan/generatePlan/endMarks.ts new file mode 100644 index 0000000..da03dbe --- /dev/null +++ b/src/plan/generatePlan/endMarks.ts @@ -0,0 +1,136 @@ +// Linienenden (Pfeilspitze, Punkt, Schrägstrich, Quadrat) für OFFENE 2D-Formen +// und die Text-Hinweislinie — eine Objekteigenschaft, wie sie jedes CAD kennt. +// +// Zwei Dinge, die der Aufrufer liefern muss: den Endpunkt UND die auswärts +// zeigende Tangentenrichtung dort. Die Richtung ist je Form unterschiedlich +// herzuleiten (Sehne, Bogentangente, erstes/letztes Stützpunktpaar), steht +// deshalb NICHT hier — diese Datei erzeugt nur die Geometrie. +// +// Die Grösse kommt in PAPIER-MILLIMETERN herein und wird mit dem Massstab des +// Plans in Modellmass umgerechnet (gleiche Linie wie die Bemassung, s. +// `model/dimension.ts`): eine 3-mm-Pfeilspitze soll auf dem Papier 3 mm sein, +// egal ob der Plan 1:50 oder 1:200 steht. + +import type { EndMark, Vec2 } from "../../model/types"; +import { mmToModel } from "../../model/dimension"; +import type { Primitive } from "./shared"; +import { NO_HATCH } from "./shared"; + +/** Default-Grösse der Linienenden in Papier-Millimetern. */ +export const END_MARK_DEFAULT_SIZE_MM = 3; + +/** Öffnungsverhältnis der Pfeilspitze (halbe Breite ÷ Länge) — schlanke Spitze. */ +const ARROW_ASPECT = 0.32; + +export interface EndMarkStyle { + weightMm: number; + color: string; + greyed: boolean; + drawingId: string; +} + +/** + * Zeichnet EIN Linienende an `at`. `dir` zeigt AUSWÄRTS (aus der Form heraus) + * und muss nicht normiert sein. `sizeMm` ist Papier-mm, `scaleDenominator` der + * Massstab des Plans. + * + * Liefert zusätzlich, um wie viel die Linie an diesem Ende VERKÜRZT werden + * sollte, damit sie nicht unter der Spitze hervorsteht (0, wo das Ende die + * Linie nicht überdeckt — Punkt/Schrägstrich/Quadrat sitzen mittig auf dem + * Endpunkt). + */ +export function addEndMark( + out: Primitive[], + at: Vec2, + dir: Vec2, + mark: EndMark | undefined, + sizeMm: number, + scaleDenominator: number, + style: EndMarkStyle, +): number { + if (!mark || mark === "none") return 0; + const len = Math.hypot(dir.x, dir.y); + if (len < 1e-9) return 0; + const size = mmToModel(sizeMm, scaleDenominator); + const ux = dir.x / len; + const uy = dir.y / len; + const nx = -uy; + const ny = ux; + const { weightMm, color, greyed, drawingId } = style; + + /** Fusspunkt der Spitze (size zurück entlang der Linie). */ + const base: Vec2 = { x: at.x - ux * size, y: at.y - uy * size }; + const half = size * ARROW_ASPECT; + const wingA: Vec2 = { x: base.x + nx * half, y: base.y + ny * half }; + const wingB: Vec2 = { x: base.x - nx * half, y: base.y - ny * half }; + const line = (a: Vec2, b: Vec2) => + out.push({ kind: "line", a, b, cls: "draw2d", weightMm, dash: null, color, greyed, drawingId }); + + switch (mark) { + case "arrow": + out.push({ + kind: "polygon", + pts: [at, wingA, wingB], + fill: color, + stroke: color, + strokeWidthMm: weightMm, + hatch: NO_HATCH, + greyed, + drawingId, + }); + // Die gefüllte Spitze überdeckt die Linie — dort darf sie enden. + return size; + case "arrowOpen": + line(wingA, at); + line(wingB, at); + // Offene Spitze: die Linie läuft bis zum Punkt durch (sie ist Teil des Bildes). + return 0; + case "dot": + out.push({ + kind: "drawingCircle", + center: at, + r: size * 0.25, + fill: color, + stroke: color, + weightMm, + greyed, + drawingId, + }); + return 0; + case "tick": { + // 45°-Schrägstrich, mittig auf dem Endpunkt (SIA-Massstrich-Anmutung). + const tx = (ux + nx) / Math.SQRT2; + const ty = (uy + ny) / Math.SQRT2; + const h = size / 2; + line({ x: at.x - tx * h, y: at.y - ty * h }, { x: at.x + tx * h, y: at.y + ty * h }); + return 0; + } + case "square": { + const h = size * 0.3; + out.push({ + kind: "polygon", + pts: [ + { x: at.x + (ux + nx) * h, y: at.y + (uy + ny) * h }, + { x: at.x + (ux - nx) * h, y: at.y + (uy - ny) * h }, + { x: at.x + (-ux - nx) * h, y: at.y + (-uy - ny) * h }, + { x: at.x + (-ux + nx) * h, y: at.y + (-uy + ny) * h }, + ], + fill: color, + stroke: color, + strokeWidthMm: weightMm, + hatch: NO_HATCH, + greyed, + drawingId, + }); + return 0; + } + } +} + +/** Punkt `p` um `d` in Richtung `dir` (normiert) zurückgezogen — für die Linienverkürzung. */ +export function pullBack(p: Vec2, dir: Vec2, d: number): Vec2 { + if (d <= 0) return p; + const len = Math.hypot(dir.x, dir.y); + if (len < 1e-9) return p; + return { x: p.x - (dir.x / len) * d, y: p.y - (dir.y / len) * d }; +} diff --git a/src/plan/generatePlan/shared.resolve.test.ts b/src/plan/generatePlan/shared.resolve.test.ts index 26106f8..bd7a592 100644 --- a/src/plan/generatePlan/shared.resolve.test.ts +++ b/src/plan/generatePlan/shared.resolve.test.ts @@ -111,6 +111,38 @@ describe("resolveHatch — reicht `motif` (custom-Muster) unverändert durch", ( }); }); +describe("resolveHatch — reicht `gradient` (Verlauf-Schraffur) unverändert durch", () => { + const gradient: NonNullable = { + color1: "#ffffff", + color2: "#000000", + angle: 45, + type: "radial", + }; + const hatchStyle: HatchStyle = { + id: "h-gradient", + name: "Verlauf", + kind: "gradient", + pattern: "diagonal", // Restwert vom vorherigen Vektor-Modus, wird ignoriert + scale: 1, + angle: 0, + color: "#000", + gradient, + }; + const project = { hatches: [hatchStyle], lineStyles: [] } as unknown as Project; + + it("HatchRender.kind/gradient entsprechen dem HatchStyle", () => { + const render = resolveHatch(project, "h-gradient"); + expect(render.kind).toBe("gradient"); + expect(render.gradient).toEqual(gradient); + }); + + it("ein Hatch OHNE gradient liefert HatchRender.gradient === undefined (kein erfundener Default)", () => { + const diagonal: HatchStyle = { id: "h-diag2", name: "Diagonal", pattern: "diagonal", scale: 1, angle: 0, color: "#000" }; + const p2 = { hatches: [diagonal], lineStyles: [] } as unknown as Project; + expect(resolveHatch(p2, "h-diag2").gradient).toBeUndefined(); + }); +}); + describe("Drawing2D-Panel-Vorschau (selectionInfo.ts) — mappt fehlende Source explizit auf 'layer'", () => { it("simuliert das Aufrufer-Mapping `d.foregroundSource ?? \"layer\"`: liefert die Kategorie-Farbe für ein Drawing2D ohne Bauteil", () => { const noComponent: Component = { id: "", name: "", color: "#000", hatchId: "", joinPriority: 0 }; diff --git a/src/plan/generatePlan/shared.ts b/src/plan/generatePlan/shared.ts index a58e624..ea8573d 100644 --- a/src/plan/generatePlan/shared.ts +++ b/src/plan/generatePlan/shared.ts @@ -102,20 +102,29 @@ export interface HatchRender { * dieses Feld — die Kette ist zur Renderzeit bereits kollabiert. */ color: string; + /** + * Ankerpunkt des Musterrasters (Modellkoordinaten). Fehlt er, ist es der + * Modellursprung — dadurch teilen benachbarte Flächen dieselbe Musterphase + * (s. `hatchLineFamily`). Gesetzt wird er über `Drawing2D.hatchOrigin`. + */ + origin?: Vec2; /** Linienstärke der Musterlinien in mm. */ lineWeight: number; /** Strichmuster der Musterlinien in mm; null = durchgezogen. */ dash: number[] | null; /** * Schraffur-Typ (additiv). `undefined`/"vector" ⇒ Muster nach `pattern` (heutiges - * Verhalten); "image" ⇒ Bild-Muster (`image`). Bestehende Renderer ignorieren - * `kind` und zeichnen nach `pattern` → unbekannte kinds fallen auf heute zurück. + * Verhalten); "image" ⇒ Bild-Muster (`image`); "gradient" ⇒ Farbverlauf + * (`gradient`). Bestehende Renderer ignorieren `kind` und zeichnen nach + * `pattern` → unbekannte kinds fallen auf heute zurück. */ - kind?: "vector" | "image"; + kind?: "vector" | "image" | "gradient"; /** Vektor-Untermodus (additiv). `undefined`/"parallel" ⇒ regelmäßig; "random" ⇒ zufällig. */ lines?: "parallel" | "random"; /** Bild-Muster-Parameter (nur `kind==="image"`); durchgereicht aus dem HatchStyle. */ image?: { src: string; scaleX: number; scaleY: number; rotation: number }; + /** Farbverlauf-Parameter (nur `kind==="gradient"`); durchgereicht aus dem HatchStyle. */ + gradient?: { color1: string; color2: string; angle: number; type: "linear" | "radial" }; /** * Steuer-Parameter der Random-Vektor-Streuung (nur `lines==="random"`), 1:1 aus * dem HatchStyle durchgereicht. Alle optional — die eigentliche Erzeugung/ @@ -161,6 +170,13 @@ export type Primitive = hatch: HatchRender; /** Gedimmt zeichnen (Darstellungsmodus „andere grau"). */ greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; /** * Kanten-Indizes, die NICHT umrissen (gestrichen) werden dürfen — die Füllung * bleibt das volle Polygon. Kante `i` läuft von `pts[i]` nach `pts[(i+1)%n]`. @@ -254,6 +270,13 @@ export type Primitive = /** ID der Treppe (für Links-Klick-Auswahl von Treppen-Symbollinien). */ stairId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { kind: "arc"; @@ -271,6 +294,13 @@ export type Primitive = /** ID der Treppe (für Links-Klick-Auswahl von Wendel-Outline-Bögen). */ stairId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { kind: "text"; @@ -294,6 +324,13 @@ export type Primitive = /** ID des Raums (Room), zu dem dieser Stempel gehört (Auswahl). */ roomId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { // Schlichter, modellverankerter Einzeltext (aus Drawing2D `{shape:"text"}`, @@ -325,6 +362,13 @@ export type Primitive = /** ID des 2D-Zeichenelements (für Links-Klick-Auswahl). */ drawingId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { // Text-entlang-Pfad (aus Drawing2D `{shape:"text", pathPts}` mit ≥2 @@ -339,6 +383,13 @@ export type Primitive = color: string; drawingId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { // Eingebettetes Rasterbild (aus Drawing2D `{shape:"image"}`, Foto/Logo/ @@ -347,6 +398,7 @@ export type Primitive = min: Vec2; max: Vec2; src: string; + /** Deckkraft 0..1 — beim Bild bereits Pflichtfeld (eigene Bild-Deckkraft). */ opacity: number; drawingId?: string; greyed?: boolean; @@ -365,6 +417,13 @@ export type Primitive = dash?: number[] | null; drawingId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; } | { // Glatter Bogen (aus Drawing2D `{shape:"arc"}`, z. B. DXF-ARC) — als @@ -379,6 +438,13 @@ export type Primitive = dash?: number[] | null; drawingId?: string; greyed?: boolean; + /** + * Deckkraft 0..1 dieses Primitivs (Default 1 = deckend). Kommt von der + * Objekt-Transparenz eines 2D-Elements (`Drawing2D.opacity`) und wird in + * `addDrawing2D` EINMAL auf alle erzeugten Primitive gestempelt, statt an + * jeder Push-Stelle mitgeführt zu werden. + */ + opacity?: number; }; /** @@ -400,6 +466,12 @@ export function resolveHatch( hatchId: string, wallAngleDeg?: number, foreground?: string, + /** + * Platzierung am OBJEKT (s. `Drawing2D.hatchAngleDeg`/`hatchScale`/ + * `hatchOrigin`): Winkel ersetzt, Massstab multipliziert, Anker verschiebt + * das Raster. Ohne Angabe bleibt alles bei der Ressource. + */ + placement?: { angleDeg?: number; scale?: number; origin?: Vec2 }, ): HatchRender { const h = getHatch(project, hatchId); const ls = h.lineStyleId ? getLineStyle(project, h.lineStyleId) : null; @@ -410,12 +482,17 @@ export function resolveHatch( // Y nach oben). Wegen der Y-Spiegelung entspricht die Wandrichtung am Bildschirm // dem Winkel −wallAngleDeg; das Muster folgt der Wand also, indem der // Wandwinkel SUBTRAHIERT wird. Ohne Wandkontext (Decke) bleibt `angle` absolut. + // Objekt-Winkel ERSETZT den der Ressource (danach greift die Wandbindung + // weiterhin, damit „relativ zur Wand" auch mit eigenem Winkel funktioniert). + const baseAngle = placement?.angleDeg ?? h.angle; const angle = - h.relativeToWall && wallAngleDeg != null ? h.angle - wallAngleDeg : h.angle; + h.relativeToWall && wallAngleDeg != null ? baseAngle - wallAngleDeg : baseAngle; return { pattern: h.pattern, - scale: h.scale, + // Objekt-Massstab MULTIPLIZIERT (die Ressource bleibt die Grundteilung). + scale: h.scale * (placement?.scale ?? 1), angle, + origin: placement?.origin, // Aufgelöster Vordergrund gewinnt (s. JSDoc oben), sonst neutrale Tinte. color: foreground ?? HATCH_INK, lineWeight: ls?.weight ?? 0.13, @@ -423,6 +500,7 @@ export function resolveHatch( kind: h.kind, lines: h.lines, image: h.image, + gradient: h.gradient, // Random-Streu-Parameter unverändert durchreichen (Erzeugung in glPlanHatch). seed: h.seed, density: h.density, diff --git a/src/plan/generateVisibleLevelsPlan.test.ts b/src/plan/generateVisibleLevelsPlan.test.ts index bdf9a7c..1b4913d 100644 --- a/src/plan/generateVisibleLevelsPlan.test.ts +++ b/src/plan/generateVisibleLevelsPlan.test.ts @@ -138,6 +138,32 @@ describe("generateVisibleLevelsPlan", () => { expect(bands.length).toBe(1); }); + it("Regression: sehr viele Primitive (grossflächiger Import) lösen keinen Stack-Overflow aus", () => { + // Nutzer-Report 2026-10-08: Import eines Kataster-DXF einer ganzen Stadt + // (~400 MB, hunderttausende Elemente) liess die App mit "Maximum call + // stack size exceeded" abstürzen — Ursache war `primitives.push(...grosses + // Array)`, das V8s Argumentzahl-Grenze für Funktionsaufrufe sprengt (anders + // als Array-LITERAL-Spread `[...a,...b]`, der KEIN Funktionsaufruf ist und + // beliebig gross sein darf). Reproduziert hier mit genug Elementen, um die + // Grenze (~65–130k, engine-abhängig) sicher zu überschreiten. + const N = 200_000; + const drawings2d: Project["drawings2d"] = []; + for (let i = 0; i < N; i++) { + drawings2d.push({ + id: `d${i}`, + type: "drawing2d", + levelId: "eg", + categoryCode: "2d-line", + geom: { shape: "line", a: { x: 0, y: i * 0.001 }, b: { x: 1, y: i * 0.001 } }, + } as unknown as Project["drawings2d"][number]); + } + const p = { ...baseProject([floor("eg", "EG")], []), drawings2d }; + const visibleWide = new Set(["20", "90", "2d-line"]); + expect(() => + generateVisibleLevelsPlan(p, "eg", visibleWide, SHOW_ALL, "mittel", false, false, SHOW_ALL), + ).not.toThrow(); + }); + it("Schnitt/Ansicht-Ebenen bleiben Einzel-Pane (kein Stapeln über kind-Grenze)", () => { const p = baseProject( [ diff --git a/src/plan/glPlan/glPlanCompile.ts b/src/plan/glPlan/glPlanCompile.ts index f8d603c..4375fb7 100644 --- a/src/plan/glPlan/glPlanCompile.ts +++ b/src/plan/glPlan/glPlanCompile.ts @@ -137,9 +137,16 @@ function parseColor(hex: string | undefined): Rgba | null { */ const GREY_RGB = 0.549; -/** Färbt auf den festen Grauton um, wenn das Primitiv im Darstellungsmodus „grau" ist. */ -function dim(color: Rgba, greyed: boolean | undefined): Rgba { - return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] : color; +/** + * Färbt auf den festen Grauton um, wenn das Primitiv im Darstellungsmodus + * „grau" ist, und multipliziert die Objekt-Transparenz (`Drawing2D.opacity`) + * in den Alphakanal. Beides ist unabhängig: gedimmt wird UMGEFÄRBT (damit + * dünne Linien erkennbar bleiben), transparent wird über Alpha. + */ +function dim(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba { + const c: Rgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] : color; + if (opacity === undefined || opacity >= 1) return c; + return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)]; } /** @@ -148,8 +155,10 @@ function dim(color: Rgba, greyed: boolean | undefined): Rgba { * gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als graue Fläche * gefüllt, sondern weiss mit nur den Linien sichtbar"). */ -function dimFill(color: Rgba, greyed: boolean | undefined): Rgba { - return greyed ? [1, 1, 1, color[3]] : color; +function dimFill(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba { + const c: Rgba = greyed ? [1, 1, 1, color[3]] : color; + if (opacity === undefined || opacity >= 1) return c; + return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)]; } /** @@ -409,7 +418,7 @@ export function compilePrimitivesToGpu( track(pt.x, pt.y); } for (const t of tris) fillIdx.push(base + t); - addFillBatch(tris.length, dimFill(fill, prim.greyed)); + addFillBatch(tris.length, dimFill(fill, prim.greyed, prim.opacity)); } } // Schraffur (nach der Füllung, vor/passend zum Umriss — wie der SVG stapelt): @@ -427,16 +436,18 @@ export function compilePrimitivesToGpu( // deckungsgleich mit den Schichtfugen in beiden Modi. // `hatch.dash` wird geometrisch (Strich/Lücke) aufgelöst, da die GL- // Linien-Pipeline kein Dash kennt. - // Bild-Schraffur (kind==="image"): WebGL2-Ebene kennt keine Muster-Textur → - // FALLBACK auf die neutrale Poché-Füllung (oben), keine Musterlinien. Der - // Random-Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche). + // Bild-/Verlauf-Schraffur (kind==="image"/"gradient"): WebGL2-Ebene kennt + // weder Muster-Textur noch echten Farbverlauf → FALLBACK auf die neutrale + // Poché-Füllung (oben), keine Musterlinien. Der Random-Untermodus läuft + // transparent über `buildHatchRuns` (Streu-Striche). if ( prim.hatch && prim.hatch.kind !== 'image' && + prim.hatch.kind !== 'gradient' && prim.hatch.pattern !== 'none' && prim.hatch.pattern !== 'solid' ) { - const hatchColor = dim(parseColor(prim.hatch.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed); + const hatchColor = dim(parseColor(prim.hatch.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); const hatchMm = prim.hatch.lineWeight > 0 ? prim.hatch.lineWeight : 0.13; const runs = applyDashRuns(buildHatchRuns(prim.pts, prim.hatch), prim.hatch.dash); for (const run of runs) strokePolyline(run, false, hatchColor, hatchMm, false); @@ -446,10 +457,10 @@ export function compilePrimitivesToGpu( // zoomrichtig in px (wie SVG-printStrokeVb → GL == SVG). const stroke = parseColor(prim.stroke); if (stroke && prim.strokeWidthMm > 0 && prim.pts.length >= 2) { - strokePolygonOutline(prim.pts, dim(stroke, prim.greyed), prim.strokeWidthMm, prim.noStrokeEdges); + strokePolygonOutline(prim.pts, dim(stroke, prim.greyed, prim.opacity), prim.strokeWidthMm, prim.noStrokeEdges); } } else if (prim.kind === 'line') { - const color = dim(parseColor(prim.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed); + const color = dim(parseColor(prim.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); if (prim.zigzag) { // Zickzack-Linie → gehrter Polylinienzug (amplitude/wavelength Papier-mm // → Modell-Meter über dieselbe Kopplung wie Strichmuster). @@ -469,6 +480,7 @@ export function compilePrimitivesToGpu( const color = dim( parseColor((prim as { color?: string }).color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, + prim.opacity, ); const strokeMm = prim.weightMm || 0.18; const c = prim.center; @@ -507,7 +519,7 @@ export function compilePrimitivesToGpu( // kein Kreis-Primitiv → hier bildschirm-adaptiv tessellieren (wie 'arc'). // Kreis = voller Umlauf (geschlossen, optional gefüllt), Bogen = a0..a1 (CCW, // offen). OHNE diesen Zweig blieben gezeichnete Kreise/Bögen im GL unsichtbar. - const stroke = dim(parseColor(prim.stroke) ?? [0.1, 0.1, 0.1, 1], prim.greyed); + const stroke = dim(parseColor(prim.stroke) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); const strokeMm = prim.weightMm || 0.18; const c = prim.center; const TAU = Math.PI * 2; @@ -544,7 +556,7 @@ export function compilePrimitivesToGpu( track(pt.x, pt.y); } for (const t of tris) fillIdx.push(base + t); - addFillBatch(tris.length, dim(fill, prim.greyed)); + addFillBatch(tris.length, dim(fill, prim.greyed, prim.opacity)); } } } diff --git a/src/plan/glPlan/glPlanHatch.origin.test.ts b/src/plan/glPlan/glPlanHatch.origin.test.ts new file mode 100644 index 0000000..eaf2836 --- /dev/null +++ b/src/plan/glPlan/glPlanHatch.origin.test.ts @@ -0,0 +1,59 @@ +/** + * Schraffur-Platzierung am Objekt: Ankerpunkt des Musterrasters. + * Kernzusage — ohne Anker hängt die Musterphase am MODELLURSPRUNG (damit + * benachbarte Flächen zusammenpassen), mit Anker am gewählten Punkt. + */ + +import { describe, expect, it } from "vitest"; +import { hatchLineFamily } from "./glPlanHatch"; +import type { Vec2 } from "../../model/types"; + +/** Quadrat 4×4, dessen linke untere Ecke NICHT im Ursprung liegt. */ +const POLY: Vec2[] = [ + { x: 1.3, y: 0.7 }, + { x: 5.3, y: 0.7 }, + { x: 5.3, y: 4.7 }, + { x: 1.3, y: 4.7 }, +]; + +describe("hatchLineFamily — Ankerpunkt", () => { + it("ohne Anker liegt das Raster auf ganzzahligen Vielfachen ab dem Modellursprung", () => { + for (const y of hatchLineFamily(POLY, 0, 1, 0).map((s) => s.a.y)) { + expect(Math.abs(y - Math.round(y))).toBeLessThan(1e-9); + } + }); + + it("mit Anker beginnt das Raster GENAU dort (Ecke statt Weltnullpunkt)", () => { + const anchor = { x: 1.3, y: 0.7 }; + const ys = hatchLineFamily(POLY, 0, 1, 0, anchor).map((s) => s.a.y); + // Jede Linie liegt auf anchor.y + k·Abstand. + for (const y of ys) { + const k = (y - anchor.y) / 1; + expect(Math.abs(k - Math.round(k))).toBeLessThan(1e-9); + } + // Und der Anker selbst ist eine der Linien (Phase 0). + expect(ys.some((y) => Math.abs(y - anchor.y) < 1e-9)).toBe(true); + }); + + it("ein verschobener Anker verschiebt die Phase entsprechend", () => { + // Aussagekräftig ist die PHASE (Lage modulo Abstand), nicht die erste + // erzeugte Linie: je nach Anker beginnt das Raster einen ganzen Schritt + // früher oder später, ohne dass sich am Muster etwas ändert. + const phase = (anchorY: number) => { + const y = hatchLineFamily(POLY, 0, 1, 0, { x: 0, y: anchorY })[0].a.y; + return ((y % 1) + 1) % 1; + }; + expect(phase(0.25)).toBeCloseTo(0.25, 9); + expect(phase(0.75)).toBeCloseTo(0.75, 9); + // Ein Anker um genau einen Abstand versetzt ergibt dieselbe Phase. + expect(phase(0.25)).toBeCloseTo(phase(1.25), 9); + }); + + it("der Anker ändert NUR die Phase, nicht den Abstand", () => { + const spacing = (anchor?: Vec2) => { + const ys = hatchLineFamily(POLY, 0, 1, 0, anchor).map((s) => s.a.y).sort((x, y) => x - y); + return ys[1] - ys[0]; + }; + expect(spacing()).toBeCloseTo(spacing({ x: 2.2, y: 3.3 }), 9); + }); +}); diff --git a/src/plan/glPlan/glPlanHatch.ts b/src/plan/glPlan/glPlanHatch.ts index 085ae86..e173338 100644 --- a/src/plan/glPlan/glPlanHatch.ts +++ b/src/plan/glPlan/glPlanHatch.ts @@ -231,6 +231,12 @@ export function hatchLineFamily( angleRad: number, spacingM: number, offsetM = 0, + /** + * Ankerpunkt des Rasters. Default ist der MODELL-URSPRUNG (s. Kommentar + * unten); ein Objekt kann ihn über `Drawing2D.hatchOrigin` verschieben, + * um das Muster z. B. an einer Raumecke ansetzen zu lassen. + */ + anchor: Vec2 = { x: 0, y: 0 }, ): HatchSegment[] { if (poly.length < 3 || spacingM <= 1e-9) return []; const bb = bbox(poly); @@ -245,7 +251,7 @@ export function hatchLineFamily( // (Ursprung (0,0) = Modell-Ursprung). Nur mit demselben Anker liegen die // Musterlinien deckungsgleich zum SVG-Referenzpfad — und benachbarte Polygone // teilen dieselbe Muster-Phase statt je eigener (bbox-abhängiger) Versätze. - const center: Vec2 = { x: 0, y: 0 }; + const center: Vec2 = anchor; let dMin = Infinity, dMax = -Infinity; for (const p of poly) { const d = (p.x - center.x) * nrm.x + (p.y - center.y) * nrm.y; @@ -380,10 +386,11 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { const scale = hatch.scale > 1e-6 ? hatch.scale : 1; // Random-Vektor-Untermodus (Kies/Splitt): kurze, deterministisch gestreute - // Striche statt der regelmäßigen Parallel-/Kreuzschar. Bild-Schraffuren - // (kind==="image") werden hier NICHT als Vektorlinien erzeugt — sie fallen im - // Aufrufer auf eine neutrale Füllung zurück (RScene/GL kennen keine Textur). - if (hatch.kind !== 'image' && hatch.lines === 'random') { + // Striche statt der regelmäßigen Parallel-/Kreuzschar. Bild-/Verlauf- + // Schraffuren (kind==="image"/"gradient") werden hier NICHT als Vektorlinien + // erzeugt — sie fallen im Aufrufer auf eine neutrale Füllung zurück + // (RScene/GL kennen weder Textur noch echten Farbverlauf). + if (hatch.kind !== 'image' && hatch.kind !== 'gradient' && hatch.lines === 'random') { return buildRandomHatchRuns(poly, hatch, scale); } @@ -408,7 +415,8 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { // Kopplung wie bei Linien-Motiven, DASH_MM_TO_M, zusätzlich mit `scale` // verknüpft — konsistent zur Zeilenabstand-Formel oben). Ohne Motiv (frisch // angelegter Hatch) fällt „custom" auf gerade Linien zurück (kein Absturz). - const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0).map((s) => + const anchor = hatch.origin ?? { x: 0, y: 0 }; + const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0, anchor).map((s) => pattern === 'custom' && hatch.motif ? motifPoints(s.a, s.b, hatch.motif, scale * DASH_MM_TO_M) : [s.a, s.b], @@ -417,7 +425,7 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { if (pattern === 'crosshatch') { // Zweite Schar: die SVG-Kachel trägt zusätzlich eine horizontale Linie // (x-Achse der Kachel) → 90° zur ersten, gleicher Abstand. - for (const s of hatchLineFamily(poly, a1 + Math.PI / 2, spacingM, 0)) runs.push([s.a, s.b]); + for (const s of hatchLineFamily(poly, a1 + Math.PI / 2, spacingM, 0, anchor)) runs.push([s.a, s.b]); } return runs; } diff --git a/src/plan/hatchLineTypes.test.ts b/src/plan/hatchLineTypes.test.ts index 9a56f2a..c31e9f1 100644 --- a/src/plan/hatchLineTypes.test.ts +++ b/src/plan/hatchLineTypes.test.ts @@ -229,6 +229,47 @@ describe("Bild-Schraffur — Fallback in der (texturlosen) RenderScene", () => { }); }); +describe("Verlauf-Schraffur — Fallback in der (verlauflosen) RenderScene", () => { + it("erzeugt KEINE Musterlinien (nur neutrale Füllung, wie bei Bild-Schraffur)", () => { + const poly: Primitive = { + kind: "polygon", + pts: SQUARE, + fill: "#eeeeee", + stroke: "none", + strokeWidthMm: 0, + hatch: hatch({ + kind: "gradient", + pattern: "crosshatch", // würde OHNE gradient-Fallback ein Kreuzmuster zeichnen + gradient: { color1: "#ffffff", color2: "#000000", angle: 45, type: "linear" }, + }), + }; + const scene = planToRenderScene(planOf([poly])); + expect(scene.polylines.length).toBe(0); // Fallback: keine Vektor-Musterlinien + expect(scene.fills.length).toBe(1); // neutrale Poché-Füllung bleibt + }); + + it("buildHatchRuns ignoriert lines:'random' bei gradient-Schraffuren (wie bei Bild-Schraffuren) — liefert dasselbe wie 'parallel'", () => { + const gradientParams = { color1: "#fff", color2: "#000", angle: 0, type: "linear" as const }; + const asRandom = buildHatchRuns( + SQUARE, + hatch({ kind: "gradient", lines: "random", gradient: gradientParams }), + ); + const asParallel = buildHatchRuns( + SQUARE, + hatch({ kind: "gradient", lines: "parallel", gradient: gradientParams }), + ); + // 'random' wird für gradient NICHT als Streu-Muster interpretiert (sonst + // wären beide Ergebnisse strukturell verschieden — Streu-Striche vs. die + // reguläre Parallelschar). + expect(asRandom).toEqual(asParallel); + // Gegenprobe: für eine normale Vektor-Schraffur macht 'random' sehr wohl + // einen Unterschied (sonst wäre der obige Vergleich nichtssagend). + const vectorRandom = buildHatchRuns(SQUARE, hatch({ kind: "vector", lines: "random" })); + const vectorParallel = buildHatchRuns(SQUARE, hatch({ kind: "vector", lines: "parallel" })); + expect(vectorRandom).not.toEqual(vectorParallel); + }); +}); + // ── Print-SVG (planToPrintSvg): Bild-/ + Zickzack- ── // Node-Umgebung ohne DOM → minimaler document-Stub (nur die von planToPrintSvg // genutzten Methoden). So lässt sich der erzeugte SVG-Knotenbaum inspizieren. diff --git a/src/plan/planView/PlanGrid.tsx b/src/plan/planView/PlanGrid.tsx new file mode 100644 index 0000000..82efeef --- /dev/null +++ b/src/plan/planView/PlanGrid.tsx @@ -0,0 +1,44 @@ +// Sichtbares Hintergrund-Raster (Nutzer-Wunsch: „Kein sichtbares 2D- +// Zeichenraster" — `SnapSettings.gridSize` steuerte bisher NUR den Fang, +// nichts wurde gezeichnet). Zoom-adaptive Linienzahl über `rulerStep` +// (dieselbe Logik wie die Lineal-Hauptstriche, s. `PlanRulers.tsx`) — hält +// die Anzahl der ``-Elemente über den gesamten Zoom-Bereich +// (`ZOOM_MIN`/`ZOOM_MAX` in PlanView.tsx) auf ≤ ~Bildschirmbreite/64px +// begrenzt, unabhängig davon, wie weit heraus- oder hereingezoomt ist. + +import { PX_PER_M } from "./geometry"; +import { rulerStep } from "./PlanRulers"; + +export function PlanGrid({ + vb, + pxPerMeter, +}: { + /** Sichtbarer Ausschnitt in viewBox-Einheiten. */ + vb: { x0: number; y0: number; w: number; h: number }; + pxPerMeter: number; +}) { + const step = rulerStep(pxPerMeter); + + // Sichtbarer Modellbereich (Plan-Y nach oben: vbY = −y·PX_PER_M) — + // identische Umrechnung wie PlanRulers. + const mx0 = vb.x0 / PX_PER_M; + const mx1 = (vb.x0 + vb.w) / PX_PER_M; + const myTop = -vb.y0 / PX_PER_M; + const myBottom = -(vb.y0 + vb.h) / PX_PER_M; + + const xs: number[] = []; + for (let v = Math.ceil(mx0 / step) * step; v <= mx1 + 1e-9; v += step) xs.push(v); + const ys: number[] = []; + for (let v = Math.ceil(myBottom / step) * step; v <= myTop + 1e-9; v += step) ys.push(v); + + return ( + + {xs.map((v, i) => ( + + ))} + {ys.map((v, i) => ( + + ))} + + ); +} diff --git a/src/plan/planView/PlanRulers.tsx b/src/plan/planView/PlanRulers.tsx index 32b38bd..0fc6489 100644 --- a/src/plan/planView/PlanRulers.tsx +++ b/src/plan/planView/PlanRulers.tsx @@ -3,8 +3,13 @@ import type { Vec2 } from "../../model/types"; import { PX_PER_M } from "./geometry"; -/** Schrittweite (Meter) fürs Lineal: 1/2/5·10^n, sodass Major-Ticks ≥ ~64 px auseinander liegen. */ -function rulerStep(pxPerMeter: number): number { +/** + * Schrittweite (Meter) fürs Lineal: 1/2/5·10^n, sodass Major-Ticks ≥ ~64 px + * auseinander liegen. Exportiert — `PlanGrid.tsx` nutzt dieselbe Funktion für + * den Zeilenabstand des sichtbaren Hintergrund-Rasters (identisches + * "welcher Abstand ist bei diesem Zoom sinnvoll"-Problem). + */ +export function rulerStep(pxPerMeter: number): number { const minPx = 64; let step = Math.pow(10, Math.ceil(Math.log10(minPx / pxPerMeter))); for (const f of [0.2, 0.5, 1]) { diff --git a/src/plan/planView/geometry.ts b/src/plan/planView/geometry.ts index 3be21f2..6a15f00 100644 --- a/src/plan/planView/geometry.ts +++ b/src/plan/planView/geometry.ts @@ -133,6 +133,29 @@ export function viewForScale( return { x: cx - w / 2, y: cy - h / 2, w, h }; } +/** + * Ziel-Ausschnitt, der eine bestimmte MODELL-Bildmitte bei einem bestimmten + * Zoom (`targetPxPerMeter`, Bildschirm-px je Meter) zeigt — die Kamera-Hälfte + * von {@link viewForScale} (das hält die BISHERIGE Mitte, hier wird eine + * NEUE gesetzt). Setzt die viewBox auf das Canvas-Seitenverhältnis (kein + * Letterbox). Für „gespeicherter Ausschnitt merkt sich auch WOHIN man + * schaut" (`ViewSnapshot.cameraCenter`/`cameraPxPerMeter`). Ohne Messung + * `null` (kein Sprung blind). + */ +export function viewForCamera( + centerModel: Vec2, + targetPxPerMeter: number, + el: SVGSVGElement | null, +): ViewBox | null { + const rect = el?.getBoundingClientRect(); + if (!rect || rect.width <= 0 || rect.height <= 0 || !(targetPxPerMeter > 0)) return null; + const targetMeetScale = targetPxPerMeter / PX_PER_M; + const w = rect.width / targetMeetScale; + const h = rect.height / targetMeetScale; + const c = toScreen(centerModel); + return { x: c.x - w / 2, y: c.y - h / 2, w, h }; +} + /** * Einpass-Ausschnitt für ein Polygon (in Modell-Metern): dessen Bounding-Box * → viewBox-Einheiten (über toScreen) mit etwas Rand. Für „auf Auswahl einpassen". diff --git a/src/plan/planView/geometry.viewForCamera.test.ts b/src/plan/planView/geometry.viewForCamera.test.ts new file mode 100644 index 0000000..8e35ec3 --- /dev/null +++ b/src/plan/planView/geometry.viewForCamera.test.ts @@ -0,0 +1,55 @@ +/** + * `viewForCamera` — Ziel-Ausschnitt für eine gegebene Modell-Bildmitte + + * einen gegebenen Zoom (px/m). Gegenstück zu `viewForScale` (hält die + * BISHERIGE Mitte, setzt einen neuen Massstab); hier wird eine NEUE Mitte + * bei einem gegebenen Zoom gesetzt — Grundlage für „gespeicherter Ausschnitt + * merkt sich auch WOHIN man schaut" (`ViewSnapshot.cameraCenter`). + */ + +import { describe, it, expect } from "vitest"; +import { viewForCamera, meetScale, toScreen, PX_PER_M } from "./geometry"; + +/** Mock-SVG-Element: nur `getBoundingClientRect` wird von `viewForCamera` gelesen. */ +function fakeSvg(width: number, height: number): SVGSVGElement { + return { + getBoundingClientRect: () => + ({ width, height, x: 0, y: 0, top: 0, left: 0, right: width, bottom: height, toJSON: () => ({}) }) as DOMRect, + } as unknown as SVGSVGElement; +} + +describe("viewForCamera", () => { + it("liefert null ohne Element (SVG noch nicht gemountet)", () => { + expect(viewForCamera({ x: 0, y: 0 }, 50, null)).toBeNull(); + }); + + it("liefert null bei pxPerMeter <= 0", () => { + expect(viewForCamera({ x: 0, y: 0 }, 0, fakeSvg(800, 600))).toBeNull(); + expect(viewForCamera({ x: 0, y: 0 }, -5, fakeSvg(800, 600))).toBeNull(); + }); + + it("liefert null bei einem Element ohne Ausdehnung (width/height = 0)", () => { + expect(viewForCamera({ x: 0, y: 0 }, 50, fakeSvg(0, 0))).toBeNull(); + }); + + it("zentriert die viewBox exakt auf toScreen(centerModel)", () => { + const el = fakeSvg(800, 600); + const center = { x: 5, y: 3 }; + const vb = viewForCamera(center, 50, el)!; + const s = toScreen(center); + expect(vb.x + vb.w / 2).toBeCloseTo(s.x, 6); + expect(vb.y + vb.h / 2).toBeCloseTo(s.y, 6); + }); + + it("reproduziert exakt den angeforderten Zoom (Roundtrip über meetScale)", () => { + const el = fakeSvg(1024, 768); + const vb = viewForCamera({ x: 0, y: 0 }, 120, el)!; + const scale = meetScale(vb, el)!; + expect(scale * PX_PER_M).toBeCloseTo(120, 6); + }); + + it("passt die viewBox-Seitenverhältnisse dem Canvas an (kein Letterbox)", () => { + const el = fakeSvg(1000, 500); // 2:1 + const vb = viewForCamera({ x: 0, y: 0 }, 90, el)!; + expect(vb.w / vb.h).toBeCloseTo(2, 6); + }); +}); diff --git a/src/plan/planView/overlays.tsx b/src/plan/planView/overlays.tsx index 5abfb60..fbc34bf 100644 --- a/src/plan/planView/overlays.tsx +++ b/src/plan/planView/overlays.tsx @@ -4,6 +4,7 @@ import type { Vec2 } from "../../model/types"; import type { SnapResult, ToolDraft } from "../../tools/types"; +import { hudSegments, type HudFieldsState } from "../../tools/hudFormat"; /** * Zeichnet die Werkzeug-Vorschau: Vorschau-Formen (gestrichelte Akzentlinien / @@ -26,10 +27,7 @@ export function DraftOverlay({ toScreen: (v: Vec2) => Vec2; vbPerPx: number; snapColor: string; - hudFields?: { - fields: { id: string; value: number | null; locked: boolean; active: boolean }[]; - typed: string; - } | null; + hudFields?: HudFieldsState | null; }) { const vertSize = 4.5 * vbPerPx; // halbe Kantenlänge eines Stützpunkt-Quadrats (klein + einheitlich) const markSize = 4.75 * vbPerPx; // halbe Kantenlänge des Snap-Markers (klein + fein) @@ -107,55 +105,11 @@ function DraftHud({ hud: NonNullable; toScreen: (v: Vec2) => Vec2; vbPerPx: number; - hudFields?: { - fields: { id: string; value: number | null; locked: boolean; active: boolean }[]; - typed: string; - } | null; + hudFields?: HudFieldsState | null; }) { - // Segmente: mit Befehlszeilen-Feldern (Tab-Zyklus) spiegelt das HUD deren - // Zustand — getippter Text erscheint LIVE im aktiven Feld (VW-Verhalten), - // gelockte Werte fest, ungelockte folgen der Maus (draft.hud-Livewerte als - // Fallback je Feld-Id). Ohne Felder: bisherige L/W- bzw. Text-Anzeige. - interface Seg { - text: string; - active: boolean; - locked: boolean; - } - const liveFor = (id: string): number | null => - id === "length" - ? (hud.length ?? null) - : id === "angle" - ? (hud.angleDeg ?? null) - : id === "width" - ? (hud.dx ?? null) - : id === "height" - ? (hud.dy ?? null) - : null; - // Feld-Beschriftung: Länge/Winkel als L/W, Rechteck-Masse als Δx/Δy (VW). - const labelFor = (id: string): string => - id === "length" ? "L" : id === "angle" ? "W" : id === "width" ? "Δx" : id === "height" ? "Δy" : id; - const segs: Seg[] = []; - if (hudFields && hudFields.fields.length > 0) { - for (const f of hudFields.fields) { - const label = labelFor(f.id); - const unit = f.id === "angle" ? "°" : "m"; - const typedHere = f.active && hudFields.typed.trim() !== ""; - const value = typedHere - ? hudFields.typed - : f.value != null - ? f.value.toFixed(3) - : (liveFor(f.id)?.toFixed(3) ?? "—"); - segs.push({ text: `${label}: ${value}${unit}`, active: f.active, locked: f.locked }); - } - } else if (hud.dx != null && hud.dy != null) { - segs.push({ text: `Δx: ${hud.dx.toFixed(3)}m`, active: false, locked: false }); - segs.push({ text: `Δy: ${hud.dy.toFixed(3)}m`, active: false, locked: false }); - } else if (hud.length != null && hud.angleDeg != null) { - segs.push({ text: `L: ${hud.length.toFixed(3)}m`, active: false, locked: false }); - segs.push({ text: `W: ${hud.angleDeg.toFixed(3)}°`, active: false, locked: false }); - } else if (hud.text) { - segs.push({ text: hud.text, active: false, locked: false }); - } + // Segmente: gemeinsame Formatierung mit dem 3D-Pendant (Wasm3DViewport.tsx), + // s. `tools/hudFormat.ts`. + const segs = hudSegments(hud, hudFields); if (segs.length === 0) return null; const p = toScreen(hud.at); @@ -383,6 +337,40 @@ function SnapMarker({ vectorEffect="non-scaling-stroke" /> )} + {/* Senkrecht: ein rechter Winkel (⌐), wie das klassische CAD-Perpendicular- + Glyph — unterscheidet sich bewusst von „onEdge" (Raute), da die + Konstruktion vom letzten Punkt aus geschieht, nicht vom Cursor. */} + {snap.kind === "perpendicular" && ( + + )} + {/* Tangente: kleiner Kreis (wie „center") plus eine kurze Berührlinie. */} + {snap.kind === "tangent" && ( + <> + + + + )} + {/* Parallel: zwei kurze parallele Striche (∥). */} + {snap.kind === "parallel" && ( + <> + + + + )} {(snap.kind === "endpoint" || snap.kind === "ortho" || snap.kind === "extension") && ( `/``-Eintrag in `` anlegt + * (sonst bliebe die Fläche ohne jede sichtbare Füllung, da `fill="url(#…)"` + * ins Leere zeigen würde). JSX-Rendering selbst wird in diesem Projekt nicht + * per Testing-Library geprüft (keine `.test.tsx`-Dateien) — die eigentliche + * ``/``-Erzeugung bleibt manuelle Prüfung + * (s. PENDENZEN.md „Nutzer prüft in der Tauri-App"). + */ + +import { describe, expect, it } from "vitest"; +import { polyUsesPattern } from "./primitives"; +import type { HatchRender } from "../generatePlan/shared"; + +function hatch(over: Partial = {}): HatchRender { + return { + pattern: "none", + scale: 1, + angle: 0, + color: "#123456", + lineWeight: 0.13, + dash: null, + ...over, + }; +} + +describe("polyUsesPattern — gradient", () => { + it("kind:'gradient' MIT gesetzten Verlauf-Parametern → true (defs-Eintrag nötig)", () => { + expect( + polyUsesPattern( + hatch({ kind: "gradient", gradient: { color1: "#fff", color2: "#000", angle: 0, type: "linear" } }), + ), + ).toBe(true); + }); + + it("kind:'gradient' OHNE gesetzte Verlauf-Parameter (Inkonsistenz) → false, kein leerer defs-Eintrag", () => { + expect(polyUsesPattern(hatch({ kind: "gradient" }))).toBe(false); + }); + + it("kind:'vector' (Default) bleibt unverändert vom `pattern`-Feld gesteuert", () => { + expect(polyUsesPattern(hatch({ pattern: "diagonal" }))).toBe(true); + expect(polyUsesPattern(hatch({ pattern: "none" }))).toBe(false); + }); +}); diff --git a/src/plan/planView/primitives.tsx b/src/plan/planView/primitives.tsx index c273196..0fc9eb3 100644 --- a/src/plan/planView/primitives.tsx +++ b/src/plan/planView/primitives.tsx @@ -26,14 +26,18 @@ export function needsPattern(pattern: HatchRender["pattern"]): boolean { } /** - * Ob ein Polygon ein SVG-`` (in ``) braucht: + * Ob ein Polygon einen SVG-Fill-Server aus `` braucht (`` ODER + * ``/`` — beide lassen sich identisch per + * `fill="url(#id)"` referenzieren): * • Bild-Schraffur (`kind==="image"`) → ja (gekacheltes Bild-Muster). + * • Verlauf-Schraffur (`kind==="gradient"`) → ja (Farbverlauf). * • Random-Vektor (`lines==="random"`) → NEIN: die Streu-Striche werden als * geclippte Polylinien direkt gezeichnet (Determinismus, Parität zu GL/PDF). * • sonst die klassischen Parallel-/Kreuz-/Dämmungs-Muster. */ export function polyUsesPattern(h: HatchRender): boolean { if (h.kind === "image") return !!h.image; + if (h.kind === "gradient") return !!h.gradient; if (h.lines === "random") return false; return needsPattern(h.pattern); } @@ -92,6 +96,32 @@ export function HatchPattern({ ); } + if (hatch.kind === "gradient" && hatch.gradient) { + // Verlauf-Schraffur: / statt — + // SVG referenziert beide identisch über `fill="url(#id)"`, der Aufrufer + // (renderPrimitive) muss NICHT unterscheiden. objectBoundingBox (SVG- + // Default) spannt 0..1 relativ zur Polygon-Bbox auf, unabhängig vom + // aktuellen Zoom/Massstab. + const g = hatch.gradient; + if (g.type === "radial") { + return ( + + + + + ); + } + const rad = (g.angle * Math.PI) / 180; + const dx = Math.cos(rad) / 2; + const dy = Math.sin(rad) / 2; + return ( + + + + + ); + } + if (hatch.pattern === "insulation") { // Weiche Zickzack-/Wellenlinie (SIA-nah). Kachel 14×10 × Maßstab. const w = 14 * hatch.scale; @@ -438,6 +468,17 @@ export function PrimitiveShape({ // Gedimmte Elemente werden auf den festen Grauton umgefärbt (Strich, Füllung // UND Schraffur) — deutlich erkennbar unabhängig von Papierfarbe/Linienstärke. const shape = renderPrimitive(p.greyed ? greyedCopy(p) : p, index, toScreen, hairline, paperScale); + // Objekt-Transparenz (Drawing2D.opacity, in addDrawing2D aufgestempelt) als + // eine Hülle darüber — so muss sie nicht in jeden Primitiv-Zweig eingebaut + // werden und wirkt gleichermassen auf Strich, Füllung und Schraffur. + const op = p.kind === "drawingImage" ? undefined : p.opacity; + if (op !== undefined && op < 1 && shape) { + return ( + + {shape} + + ); + } return shape; } @@ -518,6 +559,17 @@ export function renderPrimitive( ); } + // Verlauf-Schraffur: der Verlauf (/ aus + // , id=hatch-index) deckt die Fläche vollständig ab — keine + // separate Grundfüllung nötig, unabhängig vom `pattern`-Feld. + if (p.hatch.kind === "gradient" && p.hatch.gradient) { + return ( + + + {outline()} + + ); + } // Random-Vektor-Schraffur (Kies/Splitt): Grundfüllung + deterministische // Streu-Striche (im MODELL-Raum erzeugt → toScreen; identischer Seed wie // GL/PDF) + Umriss. KEIN (die Striche werden direkt gezeichnet). diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index ed9ce13..e310332 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -404,13 +404,15 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL // Schraffur: die aufs Polygon geclippten Musterlinien wie im Browser // (glPlanHatch — identische Geometrie), als Polylinien. "none"/"solid" - // brauchen keine Linien (solid deckt die Füllung farbig ab). Bild-Schraffuren - // (kind==="image") kann die render2d-Szene nicht tragen (keine Textur) → - // FALLBACK: nur die neutrale Poché-Füllung (oben), keine Musterlinien. Der - // Random-Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche). + // brauchen keine Linien (solid deckt die Füllung farbig ab). Bild-/ + // Verlauf-Schraffuren (kind==="image"/"gradient") kann die render2d- + // Szene nicht tragen (keine Textur/kein echter Verlauf) → FALLBACK: nur + // die neutrale Poché-Füllung (oben), keine Musterlinien. Der Random- + // Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche). if ( p.hatch && p.hatch.kind !== "image" && + p.hatch.kind !== "gradient" && p.hatch.pattern !== "none" && p.hatch.pattern !== "solid" ) { diff --git a/src/plan/toWalls3d.test.ts b/src/plan/toWalls3d.test.ts index 00fdd0f..7657094 100644 --- a/src/plan/toWalls3d.test.ts +++ b/src/plan/toWalls3d.test.ts @@ -8,7 +8,9 @@ import { describe, it, expect } from "vitest"; import type { Project, Roof, Wall } from "../model/types"; import { sampleProject } from "../model/sampleProject"; -import { selectionHighlightLines, projectToWalls3d, projectToModel3d, pickGeometry } from "./toWalls3d"; +import { selectionHighlightLines, projectToWalls3d, projectToModel3d, pickGeometry, draftWorldLines } from "./toWalls3d"; +import { hexToRgb } from "./toWalls3d/shared"; +import type { ToolDraft } from "../tools/types"; import { resolveHatch, generatePlan } from "./generatePlan"; import { roofGeometry, roofBaseElevation } from "../geometry/roof"; @@ -1250,6 +1252,66 @@ describe("VW-fein-Öffnungsdetails: Fensterbank, DIN-Symbole, verschachtelte Fl expect(projectToModel3d(winProject({ ...baseWin, id: "win-no-leaf" })).meshes.filter(isLeaf).length).toBe(0); }); + it("Kassettentür (leafStyle: kassette): Rahmen-Raster statt Vollblatt, Felder vertieft", () => { + const isLeaf = (m: { color: [number, number, number] }): boolean => + m.color[0] === 0.93 && m.color[1] === 0.9 && m.color[2] === 0.85; + const doorProject = (dt: NonNullable[number]): Project => ({ + ...sampleProject, + doorTypes: [dt], + openings: [ + { + id: "DL", + type: "opening", + hostWallId: "W1", + categoryCode: "31", + kind: "door", + typeId: dt.id, + position: 3.0, + width: 0.9, + height: 2.0, + sillHeight: 0, + }, + ], + doors: [], + context: [], + }); + const baseDoor = { + id: "door-kassette-test", + name: "Kassette-Test", + kind: "dreh" as const, + leafCount: 1 as const, + leafStyle: "kassette" as const, + frameThickness: 0.05, + frameWidth: 0.06, + defaultWidth: 0.9, + defaultHeight: 2.0, + }; + // Default-Raster (fehlt panelCols/panelRows -> 2x3): 4 Rahmen-Riegel + + // (cols-1) Trennstege + (rows-1) Trennstege + cols*rows vertiefte Felder. + const defaultGrid = projectToModel3d(doorProject(baseDoor)).meshes.filter(isLeaf); + expect(defaultGrid.length).toBe(4 + 1 + 2 + 2 * 3); + // Auch bei "grob" vorhanden (Füllung ist kein "fein"-Detail, wie beim Vollblatt). + expect( + projectToModel3d(doorProject(baseDoor), { detail: "grob" }).meshes.filter(isLeaf).length, + ).toBe(defaultGrid.length); + // Explizites 1x1-Raster -> nur Rahmen (4) + EIN vertieftes Feld. + const single = projectToModel3d( + doorProject({ ...baseDoor, id: "door-kassette-1x1", panelCols: 1, panelRows: 1 }), + ).meshes.filter(isLeaf); + expect(single.length).toBe(4 + 1); + // Explizites 3x4-Raster -> 4 + (3-1) + (4-1) + 3*4 Felder. + const grid34 = projectToModel3d( + doorProject({ ...baseDoor, id: "door-kassette-3x4", panelCols: 3, panelRows: 4 }), + ).meshes.filter(isLeaf); + expect(grid34.length).toBe(4 + 2 + 3 + 3 * 4); + // "glatt" bleibt unverändert bei genau 1 Blatt-Mesh (keine Regression durch den neuen Zweig). + expect( + projectToModel3d(doorProject({ ...baseDoor, id: "door-glatt-check", leafStyle: "glatt" })).meshes.filter( + isLeaf, + ).length, + ).toBe(1); + }); + it("Tür-Zarge mit Umgriff: zarge -> 6 Bekleidungs-Riegel mehr als blockrahmen", () => { const doorProject = (frameKind: "zarge" | "blockrahmen"): Project => ({ ...sampleProject, @@ -2089,6 +2151,95 @@ describe("emitStairs — geschlossene Setzstufen (closedRisers) im WASM-Default- }); }); +describe("emitStairRailings (Handlauf/Geländer, StairType.railing)", () => { + // Derselbe Bug-Typ wie nosing/closedRisers oben: `StairType.railing` + // existierte im Modell + im ResourceManager (`StairStylesTab`) + den + // i18n-Labels, wurde aber von KEINEM Renderer je gelesen. + const stairType = ( + railing: "keine" | "links" | "rechts" | "beide", + ): NonNullable[number] => ({ + id: "st-railing-test", + name: "Test Geländer", + structure: "wange", + closedRisers: false, + treadThickness: 0.04, + defaultWidth: 1.0, + railing, + }); + const stairProject = ( + railing: "keine" | "links" | "rechts" | "beide", + shape: "straight" | "L" = "straight", + ): Project => ({ + ...sampleProject, + stairTypes: [stairType(railing)], + stairs: [ + { + id: "STG", + type: "stair", + floorId: "eg", + categoryCode: "40", + shape, + typeId: "st-railing-test", + start: { x: 3.7, y: 0.4 }, + dir: { x: 0, y: 1 }, + runLength: 3.2, + width: 1.0, + totalRise: 2.6, + stepCount: 15, + up: true, + }, + ], + }); + const railMeshes = (p: Project) => { + const rgb = hexToRgb("#74797f"); + return projectToModel3d(p).meshes.filter( + (m) => m.color[0] === rgb[0] && m.color[1] === rgb[1] && m.color[2] === rgb[2], + ); + }; + // Je Seite: 1 Handlauf-Segment + (stepCount Pfosten je Tritt-Vorderkante + 1 Fusspfosten). + + it('"keine" (Default) -> kein Geländer-Mesh', () => { + expect(railMeshes(stairProject("keine")).length).toBe(0); + // Fehlender railing-Wert verhält sich wie "keine" (Default im Code). + const noField: Project = { + ...sampleProject, + stairTypes: [{ ...stairType("keine"), railing: undefined }], + stairs: stairProject("keine").stairs, + }; + expect(railMeshes(noField).length).toBe(0); + }); + + it('"links"/"rechts" -> genau eine Seite (1 Handlauf + 16 Pfosten)', () => { + expect(railMeshes(stairProject("links")).length).toBe(1 + 16); + expect(railMeshes(stairProject("rechts")).length).toBe(1 + 16); + }); + + it('"beide" -> doppelte Menge (beide Seiten)', () => { + expect(railMeshes(stairProject("beide")).length).toBe(2 * (1 + 16)); + }); + + it("L-Treppe: bewusst (noch) kein Geländer (nur gerade Läufe unterstützt)", () => { + expect(railMeshes(stairProject("beide", "L")).length).toBe(0); + }); + + it("Handlauf-Oberkante liegt RAIL_HEIGHT (0.9 m) über Boden- bzw. Austrittshöhe", () => { + const meshes = railMeshes(stairProject("links")); + let minZ = Infinity, maxZ = -Infinity; + for (const m of meshes) { + for (let i = 2; i < m.positions.length; i += 3) { + minZ = Math.min(minZ, m.positions[i]); + maxZ = Math.max(maxZ, m.positions[i]); + } + } + // Treppe startet bei EG-UK (0) und steigt 2.6 m; Handlauf 0.9 m darüber + // am oberen Ende -> Maximalhöhe der Pfosten/des Handlaufs ~ 2.6+0.9=3.5 m + // (Pfostenbreite RAIL_THICK vernachlässigbar für diese grobe Prüfung). + expect(maxZ).toBeGreaterThan(2.6 + 0.9 - 0.1); + expect(maxZ).toBeLessThan(2.6 + 0.9 + 0.1); + expect(minZ).toBeGreaterThan(0 - 0.1); + }); +}); + describe("emitStairMeshes (Betontreppe: glatte Laufplatte als Mesh)", () => { it("gerade Betontreppe -> Mesh mit 8 Ecken je Tritt, glatte schräge Untersicht", () => { // Sample-Treppe ST1: Typ "stair-standard" (Tragart "beton"), gerade, @@ -2380,6 +2531,49 @@ describe("pickGeometry — Dächer (Ray-Dreieck-Pick)", () => { }); }); +describe("pickGeometry — freie 2D-Zeichnungen (Boden-Spuren, Nutzer-Report „2D-Elemente können nicht angewählt werden\")", () => { + const withDrawing: Project = { + ...sampleProject, + drawings2d: [ + { + id: "D1", + type: "drawing2d", + levelId: "eg", + categoryCode: "2d-line", + geom: { shape: "line", a: { x: -1, y: 5 }, b: { x: 1, y: 5 } }, + }, + ], + }; + + it("liefert je Linien-Segment eine Pick-Box mit drawingId, world (x, ≈0, y)", () => { + const { drawings } = pickGeometry(withDrawing); + expect(drawings.length).toBe(1); + expect(drawings[0].drawingId).toBe("D1"); + expect(drawings[0].start).toEqual([-1, 5]); + expect(drawings[0].end).toEqual([1, 5]); + // EG liegt bei baseElevation 0 → die Pick-Box sitzt knapp darüber (+Epsilon + // gegen Z-Fighting), NICHT exakt bei 0 (s. `drawingElevation`). + expect(drawings[0].baseElevation).toBeGreaterThan(-0.1); + expect(drawings[0].baseElevation).toBeLessThan(0.1); + }); + + it("Kreis/Bogen/Text ohne Segment-Zerlegung liefern keine Pick-Box (Parität zu emitDrawingLines)", () => { + const withCircle: Project = { + ...sampleProject, + drawings2d: [ + { + id: "D2", + type: "drawing2d", + levelId: "eg", + categoryCode: "2d-line", + geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 }, + }, + ], + }; + expect(pickGeometry(withCircle).drawings).toEqual([]); + }); +}); + describe("pickGeometry — Kontext-Meshes (importierte Gebäude/Terrain)", () => { const withContext: Project = { ...sampleProject, @@ -2388,7 +2582,7 @@ describe("pickGeometry — Kontext-Meshes (importierte Gebäude/Terrain)", () => id: "CTX1", type: "importedMesh", name: "Testgebäude", - // model (x,y,z=Höhe) -> world (x, z, y): ein Dreieck. + // model (x,y,z=Höhe) -> world (x, z, -y): ein Dreieck. positions: [0, 0, 0, 2, 0, 0, 2, 3, 4], indices: [0, 1, 2], }, @@ -2406,9 +2600,10 @@ describe("pickGeometry — Kontext-Meshes (importierte Gebäude/Terrain)", () => expect(contextMeshes.length).toBe(1); expect(contextMeshes[0].contextObjectId).toBe("CTX1"); expect(contextMeshes[0].tris.length).toBe(1); - // world = (x, z, y) — dasselbe Dreieck (0,0,0),(2,0,0),(2,3,4) - // -> world (0,0,0),(2,0,0),(2,4,3). - expect(contextMeshes[0].tris[0][2]).toEqual([2, 4, 3]); + // world = (x, z, -y) — dasselbe Dreieck (0,0,0),(2,0,0),(2,3,4) + // -> world (0,0,0),(2,0,0),(2,4,-3). Die Nord-Achse (y) wird negiert + // (Spiegelungs-Fix, s. `viewport3d/meshBuilders.ts::buildContext`). + expect(contextMeshes[0].tris[0][2]).toEqual([2, 4, -3]); }); it("kaputte Indizes werden robust übersprungen statt abzustürzen", () => { @@ -2428,3 +2623,116 @@ describe("pickGeometry — Kontext-Meshes (importierte Gebäude/Terrain)", () => expect(contextMeshes.length).toBe(0); }); }); + +describe("draftWorldLines — Zeichnen-Vorschau für den WASM-3D-Viewport", () => { + it("leerer/fehlender Draft -> leeres Array", () => { + expect(draftWorldLines(null, 0).length).toBe(0); + const empty: ToolDraft = { preview: [], vertices: [] }; + expect(draftWorldLines(empty, 0).length).toBe(0); + }); + + it("eine 'line'-Form -> genau EINE Kante (2 Vertices), Modell (x,y) -> world (x, planeY, y) OHNE Vorzeichenwechsel", () => { + const draft: ToolDraft = { + preview: [{ kind: "line", a: { x: 1, y: 2 }, b: { x: 3, y: 4 } }], + vertices: [], + }; + const out = draftWorldLines(draft, 5); + // 2 Vertices x 6 Floats (pos+rgb). + expect(out.length).toBe(12); + expect(Array.from(out.slice(0, 3))).toEqual([1, 5, 2]); + expect(Array.from(out.slice(6, 9))).toEqual([3, 5, 4]); + }); + + it("eine offene 'poly' mit 3 Punkten -> 2 Kanten, kein Schluss-Segment", () => { + const draft: ToolDraft = { + preview: [ + { kind: "poly", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: false }, + ], + vertices: [], + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(2 * 12); // 2 Kanten x 2 Vertices x 6 Floats + }); + + it("eine GESCHLOSSENE 'poly' mit 3 Punkten -> 3 Kanten (inkl. Schluss-Segment zurück zum Start)", () => { + const draft: ToolDraft = { + preview: [ + { kind: "poly", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true }, + ], + vertices: [], + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(3 * 12); + // Letzte Kante schliesst von pts[2] zurück zu pts[0]. + const lastEdgeStart = out.length - 12; + expect(Array.from(out.slice(lastEdgeStart, lastEdgeStart + 3))).toEqual([1, 0, 1]); + expect(Array.from(out.slice(lastEdgeStart + 6, lastEdgeStart + 9))).toEqual([0, 0, 0]); + }); + + it("mehrere preview-Formen werden aneinandergehängt (Reihenfolge erhalten)", () => { + const draft: ToolDraft = { + preview: [ + { kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + { kind: "line", a: { x: 2, y: 0 }, b: { x: 3, y: 0 } }, + ], + vertices: [], + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(2 * 12); + }); + + it("Fang-Marker (Quadrat, 4 Kanten) erscheint am Snap-Punkt, AUCH ohne preview (erster Klick)", () => { + // Leeres preview (noch kein Punkt gesetzt) — der Marker muss trotzdem + // erscheinen, sonst zeigt der allererste Klick keine Fang-Rückmeldung. + const draft: ToolDraft = { + preview: [], + vertices: [], + snap: { point: { x: 2, y: 3 }, kind: "endpoint", distPx: 1 }, + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(4 * 12); // 4 Kanten x 2 Vertices x 6 Floats + // Marker-RGB (gelb) an jedem Vertex (Float32 -> toBeCloseTo statt toEqual). + const rgb = Array.from(out.slice(3, 6)); + expect(rgb[0]).toBeCloseTo(1, 5); + expect(rgb[1]).toBeCloseTo(0.8, 5); + expect(rgb[2]).toBeCloseTo(0, 5); + }); + + it("Ortho-/Verlängerungs-Fang zeichnet zusätzlich die Bezugslinie refA->Punkt (unverlängert)", () => { + const draft: ToolDraft = { + preview: [], + vertices: [], + snap: { point: { x: 5, y: 0 }, kind: "ortho", refA: { x: 0, y: 0 }, distPx: 1 }, + }; + const out = draftWorldLines(draft, 0); + // Marker (4 Kanten) + 1 Bezugslinie = 5 Kanten. + expect(out.length).toBe(5 * 12); + const guideStart = 4 * 12; + expect(Array.from(out.slice(guideStart, guideStart + 3))).toEqual([0, 0, 0]); + expect(Array.from(out.slice(guideStart + 6, guideStart + 9))).toEqual([5, 0, 0]); + }); + + it("weicher Winkel-Fang verlängert die Führungslinie über den Punkt hinaus", () => { + const draft: ToolDraft = { + preview: [], + vertices: [], + snap: { point: { x: 4, y: 0 }, kind: "angle", refA: { x: 0, y: 0 }, angleDeg: 0, distPx: 1 }, + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(5 * 12); + const guideStart = 4 * 12; + expect(Array.from(out.slice(guideStart, guideStart + 3))).toEqual([0, 0, 0]); + // Verlängert um SNAP_ANGLE_GUIDE_EXTEND_M (6m) über den Punkt (4,0) hinaus -> (10,0). + expect(Array.from(out.slice(guideStart + 6, guideStart + 9))).toEqual([10, 0, 0]); + }); + + it("Grid-/Divide-Fang OHNE refA zeigt nur den Marker, keine Bezugslinie", () => { + const draft: ToolDraft = { + preview: [], + vertices: [], + snap: { point: { x: 1, y: 1 }, kind: "grid", distPx: 1 }, + }; + const out = draftWorldLines(draft, 0); + expect(out.length).toBe(4 * 12); + }); +}); diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 8a1a599..cc9177f 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -40,8 +40,9 @@ // truck-Extrusionen, freie 2D-Geometrie) hat ihre eigene Datei unter // `toWalls3d/` — siehe dort für die konkrete Emissions-Logik je Bauteil. -import type { Project, Wall } from "../model/types"; +import type { Project, Vec2, Wall } from "../model/types"; import { getWallType, wallTypeThickness } from "../model/types"; +import type { ToolDraft } from "../tools/types"; import { stairVerticalExtent } from "../model/wall"; import { openingJambs, openingVerticalExtent } from "../geometry/opening"; import type { DetailLevel } from "../ui/TopBar"; @@ -50,7 +51,7 @@ import { roofBaseElevation, roofGeometry } from "../geometry/roof"; import type { Vec3 as RoofVec3 } from "../geometry/roof"; import { computeJoins } from "../model/joins"; import type { WallCuts } from "../model/joins"; -import type { PickOpening, PickRoof, PickStair, PickContextMesh } from "../viewport/raycast3d"; +import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "../viewport/raycast3d"; import { EPS, IMPORTED_RGB, @@ -65,9 +66,9 @@ import { } from "./toWalls3d/shared"; import { emitWall } from "./toWalls3d/bands"; import { emitSlabs } from "./toWalls3d/ceilings"; -import { emitStairMeshes, emitStairs } from "./toWalls3d/stairs"; +import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs"; import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions"; -import { emitDrawingLines } from "./toWalls3d/drawing2d"; +import { emitDrawingLines, pickDrawingSegs } from "./toWalls3d/drawing2d"; import { emitColumns } from "./toWalls3d/columns"; import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs"; import { emitLegacyDoorLeaves, emitOpeningFrames, emitOpeningGlass, emitOpeningShading } from "./toWalls3d/openings"; @@ -114,9 +115,17 @@ function emitMeshes(project: Project): RMesh[] { }); } } - out.push(...emitExtrudedSolids(project)); - out.push(...emitColumns(project)); - out.push(...emitDrawingLines(project)); + // KEIN `out.push(...emitDrawingLines(project))`: bei grossen Importen (z. B. + // ein Kataster-DXF einer ganzen Stadt → hunderttausende Drawing2D-Elemente, + // je eins ein Mesh) sprengt der Spread-Operator die Argumentzahl-Grenze von + // `push` (RangeError "Maximum call stack size exceeded") — dieselbe, bereits + // dokumentierte Falle wie in `swissBuildings3d.ts::concatMeshes`/ + // `dwgParser.ts`. `emitExtrudedSolids`/`emitColumns` sind praktisch nie so + // gross (Nutzer-platzierte BIM-Elemente), aber aus Konsistenz gleich + // behandelt. + for (const m of emitExtrudedSolids(project)) out.push(m); + for (const m of emitColumns(project)) out.push(m); + for (const m of emitDrawingLines(project)) out.push(m); return out; } @@ -208,6 +217,7 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R ...emitOpeningFrames(project, detail), ...emitOpeningShading(project, detail), ...emitStairMeshes(project), + ...emitStairRailings(project), ...emitRoofs(project), ], // Dach-Schicht-Eingabe für den 3D-Live-Schnitt (render3d::roof_cut) — s. @@ -222,8 +232,10 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R * Wand-Teilquader (mit `wallId`) und Decken-Prismen (mit `ceilingId`) desselben * geflachten Modells wie {@link projectToModel3d}, aber ohne die Kontext-Meshes * (die sind für die Bauteil-Auswahl irrelevant), PLUS die Öffnungs- (Fenster/ - * Türen) und Treppen-Boxen fürs Raycast-Picking. Reine TS-Nutzung — geht NICHT - * an render3d; die Records tragen dieselben Geometriefelder wie die Serde- + * Türen) und Treppen-Boxen sowie die (tolerant aufgeweiteten) Boden-Spuren + * freier 2D-Zeichnungen (`drawings`, s. `toWalls3d/drawing2d.ts:: + * pickDrawingSegs`) fürs Raycast-Picking. Reine TS-Nutzung — geht NICHT an + * render3d; die Records tragen dieselben Geometriefelder wie die Serde- * Payload, plus die Ids fürs Picking. */ export function pickGeometry( @@ -235,6 +247,7 @@ export function pickGeometry( stairs: PickStair[]; roofs: PickRoof[]; contextMeshes: PickContextMesh[]; + drawings: PickDrawingSeg[]; } { // Dächer: Dachflächen + Giebel als WORLD-Dreiecke (fan-trianguliert wie // emitRoofs; model [x,y,z=Höhe] → world [x, z, y]) — präzise geneigte @@ -289,9 +302,15 @@ export function pickGeometry( }); } // Kontext-Meshes (importierte Gebäude/Terrain, s. ContextObject): rohe - // WORLD-Dreiecke wie beim Dach, direkt aus dem Indexpuffer (kein Fan nötig — - // ImportedMesh/TerrainMesh liefern bereits ein echtes Dreiecksnetz). Kaputte - // Indizes robust überspringen statt abzustürzen (importierte Daten). + // WORLD-Dreiecke, direkt aus dem Indexpuffer (kein Fan nötig — ImportedMesh/ + // TerrainMesh liefern bereits ein echtes Dreiecksnetz). Kaputte Indizes + // robust überspringen statt abzustürzen (importierte Daten). + // Modell (x,y,z) → world (x, z, −y) — Nord-Achse NEGIERT, damit der Pick + // dieselbe (gespiegelte→korrigierte) Lage trifft wie die sichtbare Geometrie + // in `viewport3d/meshBuilders.ts::buildContextMesh` (dort ausführlich + // begründet: reines Achsen-Vertauschen ohne Vorzeichenwechsel ist für einen + // allgemeinen xyz-Punktsatz eine Spiegelung, anders als bei Wand/Dach, die + // über eine orientierungserhaltende Rotation/Fächer-Triangulation entstehen). const contextMeshes: PickContextMesh[] = []; for (const obj of project.context ?? []) { if (obj.type === "contourSet" || obj.type === "image") continue; @@ -303,12 +322,21 @@ export function pickGeometry( const ib = obj.indices[i + 1]; const ic = obj.indices[i + 2]; if (ia >= vcount || ib >= vcount || ic >= vcount) continue; - const at = (idx: number): RoofPickVec3 => [pos[idx * 3], pos[idx * 3 + 2], pos[idx * 3 + 1]]; + const at = (idx: number): RoofPickVec3 => [pos[idx * 3], pos[idx * 3 + 2], -pos[idx * 3 + 1]]; tris.push([at(ia), at(ib), at(ic)]); } if (tris.length > 0) contextMeshes.push({ tris, contextObjectId: obj.id }); } - return { walls: projectToWalls3d(project), slabs: emitSlabs(project), openings, stairs, roofs, contextMeshes }; + const drawings = pickDrawingSegs(project); + return { + walls: projectToWalls3d(project), + slabs: emitSlabs(project), + openings, + stairs, + roofs, + contextMeshes, + drawings, + }; } /** @@ -478,3 +506,86 @@ export function selectionHighlightLines( } return new Float32Array(out); } + +/** Blau-Akzent der Zeichnen-Vorschau — identisch zu `Viewport3D.tsx`s `draftLineMat` (0x2f8fff). */ +const DRAFT_LINE_RGB: RRgb = [0x2f / 255, 0x8f / 255, 0xff / 255]; +/** Warmes Gelb für Fang-Marker/-Führungslinien (Objekt-Snap, Ortho/Extension, + * weicher Winkel-Snap) — analog dem 2D-Snap-Akzent (`PlanView`s `snapColor`- + * Prop), hier als fester Wert (der 3D-Viewport hat noch keine eigene + * einstellbare Snap-Farbe, s. PENDENZEN „ArchiCAD-Wunschliste"). */ +const SNAP_GUIDE_RGB: RRgb = [1, 0.8, 0]; +/** Halbe Kantenlänge des Fang-Markers (Welt-Meter) — deutlich grösser als die + * 0.008m Zeichnungs-Linienbreite, aber klein genug, den Punkt nicht zu + * verdecken. */ +const SNAP_MARKER_HALF = 0.06; +/** Länge der weichen-Winkel-Führungslinie über den Fangpunkt hinaus (Welt- + * Meter) — bewusst ENDLICH (anders als die 2D-SVG-Version, die bis zum + * Viewport-Rand läuft; im 3D gibt es keine sinnvolle "Rand"-Grenze, eine + * unendliche Linie liefe unkontrolliert durchs ganze Modell). */ +const SNAP_ANGLE_GUIDE_EXTEND_M = 6; + +/** + * Wandelt den aktiven Werkzeug-Draft (`ToolDraft.preview`, Modell-Meter, + * Grundriss-Ebene) in dasselbe flache Weltraum-LineList-Format wie + * {@link selectionHighlightLines} (`[px,py,pz,r,g,b, ...]`, world-Meter, je 2 + * Vertices = 1 Kante) — reicht denselben `set_highlight_lines`-Kanal der + * WASM-Engine, um im 3D-Viewport eine Live-Vorschau beim Zeichnen zu zeigen + * (Parität zum three.js-Pfad, dessen `drawDraft` dieselben `DraftShape`s auf + * derselben Ebene rendert). Modell (x,y) → world (x, planeY, y) — KEIN + * Vorzeichenwechsel (dieselbe unveränderte, orientierungserhaltende + * Konvention wie Wand-/Zeichnungslinien; s. `addDrawingLines`/`toWalls3d/ + * drawing2d.ts` — anders als die Kontext-Mesh-Konvention, s. PENDENZEN.md). + * + * ZUSÄTZLICH (Nutzer-Wunsch „generell im 3D auch Snapping einbauen"): bei + * gesetztem `draft.snap` ein kleines Quadrat am Fangpunkt (JEDE Fang-Art, + * analog der 2D-`SnapMarker`) sowie — bei Ortho-/Verlängerungs-Fang bzw. + * weichem Winkel-Fang — die zugehörige Bezugslinie/-Führungslinie (analog + * `snap-helper-line`/`AngleGuide` im 2D-Plan). Läuft VOR jedem gesetzten + * Punkt (auch beim allerersten Klick, ohne `preview`), zeigt der Marker also + * schon, wohin der erste Punkt fängt — deshalb NICHT mehr früh bei leerem + * `preview` abgebrochen. + */ +export function draftWorldLines(draft: ToolDraft | null, planeY: number): Float32Array { + if (!draft) return new Float32Array(0); + const out: number[] = []; + const pushSeg = (a: Vec2, bPt: Vec2, rgb: RRgb = DRAFT_LINE_RGB) => { + const [cr, cg, cb] = rgb; + out.push(a.x, planeY, a.y, cr, cg, cb); + out.push(bPt.x, planeY, bPt.y, cr, cg, cb); + }; + for (const shape of draft.preview) { + if (shape.kind === "line") { + pushSeg(shape.a, shape.b); + } else { + const n = shape.pts.length; + for (let i = 0; i + 1 < n; i++) pushSeg(shape.pts[i], shape.pts[i + 1]); + if (shape.closed && n > 2) pushSeg(shape.pts[n - 1], shape.pts[0]); + } + } + const snap = draft.snap; + if (snap) { + const p = snap.point; + const h = SNAP_MARKER_HALF; + const c1 = { x: p.x - h, y: p.y - h }; + const c2 = { x: p.x + h, y: p.y - h }; + const c3 = { x: p.x + h, y: p.y + h }; + const c4 = { x: p.x - h, y: p.y + h }; + pushSeg(c1, c2, SNAP_GUIDE_RGB); + pushSeg(c2, c3, SNAP_GUIDE_RGB); + pushSeg(c3, c4, SNAP_GUIDE_RGB); + pushSeg(c4, c1, SNAP_GUIDE_RGB); + if (snap.refA && (snap.kind === "ortho" || snap.kind === "extension")) { + pushSeg(snap.refA, p, SNAP_GUIDE_RGB); + } else if (snap.refA && snap.kind === "angle") { + const dx = p.x - snap.refA.x; + const dy = p.y - snap.refA.y; + const len = Math.hypot(dx, dy); + const ext = + len > 1e-6 + ? { x: p.x + (dx / len) * SNAP_ANGLE_GUIDE_EXTEND_M, y: p.y + (dy / len) * SNAP_ANGLE_GUIDE_EXTEND_M } + : p; + pushSeg(snap.refA, ext, SNAP_GUIDE_RGB); + } + } + return new Float32Array(out); +} diff --git a/src/plan/toWalls3d/drawing2d.test.ts b/src/plan/toWalls3d/drawing2d.test.ts new file mode 100644 index 0000000..6881a11 --- /dev/null +++ b/src/plan/toWalls3d/drawing2d.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import type { Project } from "../../model/types"; +import { sampleProject } from "../../model/sampleProject"; +import { emitDrawingLines } from "./drawing2d"; + +// Regression fürs Nord-Achsen-Vorzeichen der 2D-Boden-Spuren im 3D (Nutzer- +// Report 2026-09-25: "eine in 3D gezeichnete Linie erscheint danach +// gespiegelt — nur bei 2D-Elementen"; 2026-09-27 auf weitere Bauteile +// ausgeweitet). `emitDrawingLines` geht über `RMesh.kind:"extrusion"` an +// render3d — `append_context_mesh` (Rust) negiert die Nord-Achse NUR für +// `"imported"`/`"terrain"` (echte, unabhängige Import-Rohdaten), NICHT für +// `"extrusion"` (orientierungserhaltende, plan-abgeleitete Geometrie wie +// Wand/Dach/Treppe/Öffnung). Die JS-Seite gibt die Positionen daher +// UNVERÄNDERT (kein manuelles Vorzeichen-Spiel mehr nötig) — dieselbe +// Konvention wie das drei.js-Pendant `addDrawing2DLines`. +describe("emitDrawingLines — Nord-Achsen-Vorzeichen (kind:\"extrusion\" statt \"imported\")", () => { + it("lässt Modell-x/-y unverändert (keine Negation), kind ist \"extrusion\"", () => { + const withLine: Project = { + ...sampleProject, + drawings2d: [ + { + id: "D1", + type: "drawing2d", + levelId: "eg", + categoryCode: "2d-line", + // Reine "Nord"-Linie (kein x-Versatz) — am einfachsten zu prüfen: + // model (0,0) -> (0,5), Ribbon-Breite vernachlässigbar (0.008m). + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 0, y: 5 } }, + }, + ], + }; + const meshes = emitDrawingLines(withLine); + expect(meshes).toHaveLength(1); + expect(meshes[0].kind).toBe("extrusion"); + const pos = meshes[0].positions; + // 4 Vertices (Ribbon-Quad) x 3 Floats, Reihenfolge a+nx, a-nx, b-nx, b+nx + // (s. `emitDrawingLines`) — Vertex 0/1 liegen also bei a (Modell-y=0), + // Vertex 2/3 bei b (Modell-y=5). Der Quer-Versatz (nx, senkrecht zur + // Nord-Süd-Richtung) ist die halbe Ribbon-Breite (0.008m) auf der + // x-Achse; der Längs-Versatz (ny) ist bei dieser Linienrichtung null. + const yOf = (vertexIdx: number) => pos[vertexIdx * 3 + 1]; + const xOf = (vertexIdx: number) => pos[vertexIdx * 3]; + expect(yOf(0)).toBeCloseTo(0, 6); + expect(yOf(1)).toBeCloseTo(0, 6); + // b-Ende (Modell-y=5): bleibt +5 (KEINE Negation mehr). + expect(yOf(2)).toBeCloseTo(5, 6); + expect(yOf(3)).toBeCloseTo(5, 6); + // x um die halbe Ribbon-Breite versetzt (±0.008m). + for (const i of [0, 1, 2, 3]) expect(Math.abs(xOf(i))).toBeCloseTo(0.008, 6); + }); + + it("Höhe (dritte Komponente) bleibt unverändert positiv (Geschoss-UK + Epsilon)", () => { + const withLine: Project = { + ...sampleProject, + drawings2d: [ + { + id: "D1", + type: "drawing2d", + levelId: "eg", + categoryCode: "2d-line", + geom: { shape: "line", a: { x: 1, y: 1 }, b: { x: 2, y: 1 } }, + }, + ], + }; + const pos = emitDrawingLines(withLine)[0].positions; + for (let i = 0; i < 4; i++) expect(pos[i * 3 + 2]).toBeGreaterThan(0); + }); +}); diff --git a/src/plan/toWalls3d/drawing2d.ts b/src/plan/toWalls3d/drawing2d.ts index ecfa026..154320d 100644 --- a/src/plan/toWalls3d/drawing2d.ts +++ b/src/plan/toWalls3d/drawing2d.ts @@ -6,6 +6,7 @@ import type { Drawing2D, Project, Vec2 } from "../../model/types"; import { flattenCategories, getFloor } from "../../model/types"; import { DRAWING_LINE_FALLBACK_RGB, hexToRgb, type RMesh, type RRgb } from "./shared"; +import { DRAWING_PICK_TOLERANCE, type PickDrawingSeg } from "../../viewport/raycast3d"; /** Halbe Linienbreite der 2D-Boden-Spuren im 3D (Meter) — liest sich als dünne Linie. */ const DRAWING_LINE_HALF_WIDTH = 0.008; @@ -18,7 +19,7 @@ const DRAWING_LINE_ELEVATION_EPS = 0.01; * line/polyline/rect. Kreis/Bogen/Text bleiben aussen vor (keine neue * Fähigkeit gegenüber dem Fallback, nur Parität). */ -function drawingSegments3d(d: Drawing2D): [Vec2, Vec2][] { +export function drawingSegments3d(d: Drawing2D): [Vec2, Vec2][] { const g = d.geom; const out: [Vec2, Vec2][] = []; if (g.shape === "line") out.push([g.a, g.b]); @@ -42,27 +43,49 @@ function drawingColor3d(project: Project, d: Drawing2D): RRgb { return cat?.color ? hexToRgb(cat.color, DRAWING_LINE_FALLBACK_RGB) : DRAWING_LINE_FALLBACK_RGB; } +/** Boden-Spur-Höhe (world-Y) einer 2D-Zeichnung: Geschoss-UK + Epsilon gegen + * Z-Fighting, oder 0 als Fallback (Geschoss nicht mehr auflösbar). Gemeinsam + * für `emitDrawingLines` (Sichtbarkeit) UND `pickDrawingSegs` (Klickbarkeit) — + * beide MÜSSEN dieselbe Höhe verwenden, sonst klickt man daneben. */ +function drawingElevation(project: Project, d: Drawing2D): number { + let baseZ = 0; + try { + baseZ = getFloor(project, d.levelId).baseElevation ?? 0; + } catch { + // Geschoss nicht (mehr) auflösbar: bei UK 0 zeichnen (Fallback). + } + return baseZ + DRAWING_LINE_ELEVATION_EPS; +} + /** * Emittiert je 2D-Zeichnung ein dünnes Ribbon-Mesh knapp über ihrer * Geschossebene — die "2D-Referenz im 3D" (z. B. ein Boden-Raster), die der * drei.js-Fallback (`addDrawing2DLines`) zeigt, bisher aber im nativen * render3d/wgpu-Pfad fehlte (`RModel3d` kannte nur walls/slabs/meshes). - * `positions` in MODELL-Metern (x, y, z=Höhe) wie `emitOpeningGlass`; render3d - * rendert Kontext-Meshes ohnehin doppelseitig (`append_context_mesh`), daher - * genügt ein flaches Ribbon (kein Quader) pro Strecke. + * `positions` in MODELL-Metern (x, y, z=Höhe); render3d rendert Kontext- + * Meshes ohnehin doppelseitig (`append_context_mesh`), daher genügt ein + * flaches Ribbon (kein Quader) pro Strecke. + * + * NORD-ACHSE / `kind` (Nutzer-Report 2026-09-25: „wenn ich eine Linie in 3D + * zeichne, wird sie nach dem Zeichnen gespiegelt — nur bei 2D-Elementen"; + * 2026-09-27 auf weitere Bauteile ausgeweitet): `kind:"extrusion"` (NICHT + * "imported"!) — `append_context_mesh` (Rust, `mesh.rs`) negiert die Nord- + * Achse NUR für `"imported"`/`"terrain"` (echte, unabhängige Import- + * Rohdaten wie swisstopo-Terrain/-Gebäude); diese Boden-Spuren sind aber + * eine FLACHE, orientierungserhaltende Ableitung der 2D-Plan-Geometrie (wie + * eine Wand) — dieselbe Konvention wie das drei.js-Pendant + * `addDrawing2DLines` (bildet `a.y`/`b.y` UNVERÄNDERT auf die Nord-Achse ab, + * keine Negation). `positions` bleiben daher unverändert (KEINE manuelle + * Vorzeichen-Kompensation mehr nötig, seit `append_context_mesh` selbst + * zwischen den beiden Fällen unterscheidet — s. PENDENZEN.md für die volle + * Herleitung über alle betroffenen Bauteile). */ export function emitDrawingLines(project: Project): RMesh[] { const out: RMesh[] = []; for (const d of project.drawings2d) { const segs = drawingSegments3d(d); if (segs.length === 0) continue; - let baseZ = 0; - try { - baseZ = getFloor(project, d.levelId).baseElevation ?? 0; - } catch { - // Geschoss nicht (mehr) auflösbar: bei UK 0 zeichnen (Fallback). - } - const elev = baseZ + DRAWING_LINE_ELEVATION_EPS; + const elev = drawingElevation(project, d); const positions: number[] = []; const indices: number[] = []; for (const [a, b] of segs) { @@ -82,7 +105,30 @@ export function emitDrawingLines(project: Project): RMesh[] { indices.push(base, base + 1, base + 2, base, base + 2, base + 3); } if (positions.length === 0) continue; - out.push({ positions, indices, kind: "imported", color: drawingColor3d(project, d) }); + out.push({ positions, indices, kind: "extrusion", color: drawingColor3d(project, d) }); + } + return out; +} + +/** + * Pick-Kandidaten (Raycast-Boxen, s. `viewport/raycast3d.ts::PickDrawingSeg`) + * für alle 2D-Zeichnungen — dieselben Segmente/Höhen wie `emitDrawingLines` + * (Klick trifft, was sichtbar ist), nur mit grosszügiger Toleranz statt der + * sichtbaren 0.008m Linienbreite. Bislang gab es GAR KEINE Pick-Unterstützung + * für freie 2D-Geometrie im WASM-Viewport (Nutzer-Report: „2D-Elemente können + * nicht angewählt werden" — Wände/Decken/Öffnungen/Treppen/Dächer waren schon + * pickbar, 2D-Zeichnungen nie). + */ +export function pickDrawingSegs(project: Project): PickDrawingSeg[] { + const out: PickDrawingSeg[] = []; + for (const d of project.drawings2d) { + const segs = drawingSegments3d(d); + if (segs.length === 0) continue; + const elev = drawingElevation(project, d); + const baseElevation = elev - DRAWING_PICK_TOLERANCE / 2; + for (const [a, b] of segs) { + out.push({ start: [a.x, a.y], end: [b.x, b.y], baseElevation, drawingId: d.id }); + } } return out; } diff --git a/src/plan/toWalls3d/openings.ts b/src/plan/toWalls3d/openings.ts index 2b050b2..cb5bb80 100644 --- a/src/plan/toWalls3d/openings.ts +++ b/src/plan/toWalls3d/openings.ts @@ -124,7 +124,9 @@ function openingAxisBox( const t = i & 4 ? nMax : nMin; positions.push(wall.start.x + ux * s + nx * t, wall.start.y + uy * s + ny * t, z); } - return { positions, indices: [...OPENING_BOX_TRIS], kind: "imported", color }; + // "extrusion", NICHT "imported" — s. Moduldoc an emitOpeningGlass (Nord- + // Achsen-Negation in append_context_mesh gilt nur für echte Import-Kinds). + return { positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color }; } /** @@ -180,7 +182,8 @@ function openingPlaneBox( const h = hi + s * halfWidth * ph; positions.push(wall.start.x + ux * u + nx * t, wall.start.y + uy * u + ny * t, h); } - return { positions, indices: [...OPENING_BOX_TRIS], kind: "imported", color }; + // "extrusion", NICHT "imported" — s. Moduldoc an emitOpeningGlass. + return { positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color }; } /** Klemmt `v` auf `[lo,hi]`. */ @@ -304,6 +307,15 @@ interface OpeningFrameParams { * kein Bodenanschlag). */ drawThresholdProfile: boolean; + /** + * Kassettentür-Blatt (Rahmen aus Stegen/Pfosten + vertiefte Felder statt + * einer glatten Platte) zeichnen: nur Türen mit `leafStyle === "kassette"`. + * Fenster: nie. + */ + panelled: boolean; + /** Kassetten-Raster horizontal/vertikal (nur bei {@link panelled} relevant). */ + panelCols: number; + panelRows: number; } function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): OpeningFrameParams | null { @@ -341,6 +353,9 @@ function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): Opening // Zarge umgreift die Wand (Bekleidung auf beiden Flächen); Blockrahmen bleibt bündig. zargeCladding: (dt.frameKind ?? "zarge") === "zarge", drawThresholdProfile: dt.threshold === true, + panelled: dt.leafStyle === "kassette", + panelCols: Math.max(1, Math.round(dt.panelCols ?? 2)), + panelRows: Math.max(1, Math.round(dt.panelRows ?? 3)), }; } const wt = getWindowType(project, op); @@ -389,6 +404,9 @@ function resolveOpeningFrame(project: Project, wall: Wall, op: Opening): Opening drawInteriorSill: wt.sillBoard === "innen" || wt.sillBoard === "beide", zargeCladding: false, drawThresholdProfile: false, + panelled: false, + panelCols: 1, + panelRows: 1, }; } @@ -734,13 +752,16 @@ function glassPanesForOpening( } /** - * Türblatt EINER typisierten Tür als solide Blatt-Tafel im Hauptfeld (zwischen - * den Rahmen-Pfosten, über Schwelle bis Sturz bzw. Kämpfer): Vollblatt - * (`leafStyle` ≠ "glas") füllt das ganze Feld, Teilverglasung - * (`glazingRatio` < 1) nur den blinden UNTEREN Rest unter dem Glasanteil - * (Anteil von OBEN gemessen, s. {@link glassPanesForOpening}). Das Blatt liegt - * mittig um die Glasebene (nMax − 0.03), ~4 cm dick ({@link DOOR_LEAF_THICK}), - * in {@link DOOR_LEAF_RGB} — damit Türen im 3D als Türen lesbar sind statt als + * Türblatt EINER typisierten Tür als Füllung im Hauptfeld (zwischen den + * Rahmen-Pfosten, über Schwelle bis Sturz bzw. Kämpfer): Vollblatt + * (`leafStyle` ∈ {"glatt","kassette"}) füllt das ganze Feld, Teilverglasung + * (`glazingRatio` < 1 bei `leafStyle: "glas"`) nur den blinden UNTEREN Rest + * unter dem Glasanteil (Anteil von OBEN gemessen, s. {@link + * glassPanesForOpening}). Bei `leafStyle === "kassette"` ist das Feld selbst + * kein glatter Quader, sondern ein Rahmen-Raster mit vertieften Feldern (s. + * {@link kassettePanels}). Das Blatt liegt mittig um die Glasebene + * (nMax − 0.03), ~4 cm dick ({@link DOOR_LEAF_THICK}), in + * {@link DOOR_LEAF_RGB} — damit Türen im 3D als Türen lesbar sind statt als * offene Löcher mit Rahmen. Fenster: nie (glazedFraction = 1 ⇒ kein Blatt). */ function doorLeafPanels( @@ -765,11 +786,97 @@ function doorLeafPanels( if (leafTop - leafBottom <= EPS || leafTo - leafFrom <= EPS) return out; const n1 = params.nMax - 0.02 + DOOR_LEAF_THICK / 2; const n0 = Math.max(params.nMin, n1 - DOOR_LEAF_THICK); + if (params.panelled) { + return kassettePanels(wall, leafFrom, leafTo, leafBottom, leafTop, n0, n1, params); + } const mesh = openingAxisBox(wall, leafFrom, leafTo, leafBottom, leafTop, n0, n1, DOOR_LEAF_RGB); if (mesh) out.push(mesh); return out; } +/** Stegbreite der Kassetten-Füllstäbe (Rahmen ums Feld + Trennstege), Meter. */ +const PANEL_STILE_WIDTH = 0.06; +/** + * Vertiefung der Kassetten-Füllung gegenüber den Stegen (je Seite, Meter) — + * dieselbe „Tiefenstufe"-Technik wie die Flügelrahmen-Verschachtelung bei + * Fenstern ({@link frameMeshesForOpening}s `sashFrontN`/`sashBackN`): ein + * zweiter, dünnerer Quader mittig im Blatt sitzt um {@link PANEL_RECESS} + * zurückversetzt ⇒ wirkt von beiden Seiten vertieft. + */ +const PANEL_RECESS = 0.012; + +/** + * Kassettentür-Blatt (`DoorType.leafStyle === "kassette"`): statt einer + * glatten Blatt-Tafel ({@link doorLeafPanels}) ein Raster aus + * `panelRows × panelCols` Feldern — äusserer Rahmen + Trennstege in voller + * Blattdicke ({@link DOOR_LEAF_THICK}, dieselbe Technik wie die Sprossen- + * Raster-Riegel bei Fenstern, `mullionRows`/`mullionCols` in + * {@link frameMeshesForOpening}), die Felder selbst dünner und um + * {@link PANEL_RECESS} zurückversetzt (vertiefter Kassetten-Look). Steg- und + * Feld-Quader überlappen an den Rändern geringfügig (das vertiefte Feld + * verschwindet dort einfach hinter dem dickeren Steg) — bewusst in Kauf + * genommen statt pixelgenauer Spaltberechnung, rein dekorative Geometrie + * ohne Boolean-Anspruch. + */ +function kassettePanels( + wall: Wall, + leafFrom: number, + leafTo: number, + leafBottom: number, + leafTop: number, + n0: number, + n1: number, + params: OpeningFrameParams, +): RMesh[] { + const out: RMesh[] = []; + const push = (from: number, to: number, zB: number, zT: number, a: number, b: number) => { + const m = openingAxisBox(wall, from, to, zB, zT, a, b, DOOR_LEAF_RGB); + if (m) out.push(m); + }; + const cols = params.panelCols; + const rows = params.panelRows; + const sw = Math.min( + PANEL_STILE_WIDTH, + (leafTo - leafFrom) / (2 * cols), + (leafTop - leafBottom) / (2 * rows), + ); + if (sw <= EPS) { + // Blatt zu schmal fürs Raster (Mini-Tür/Degenerat) — Fallback Vollblatt. + push(leafFrom, leafTo, leafBottom, leafTop, n0, n1); + return out; + } + // Äusserer Rahmen (Stile/Riegel) — volle Blattdicke. + push(leafFrom, leafTo, leafBottom, leafBottom + sw, n0, n1); // unterer Riegel + push(leafFrom, leafTo, leafTop - sw, leafTop, n0, n1); // oberer Riegel + push(leafFrom, leafFrom + sw, leafBottom, leafTop, n0, n1); // linker Pfosten + push(leafTo - sw, leafTo, leafBottom, leafTop, n0, n1); // rechter Pfosten + const cellW = (leafTo - leafFrom) / cols; + const cellH = (leafTop - leafBottom) / rows; + // Trennstege zwischen den Feldern — volle Blattdicke. + for (let c = 1; c < cols; c++) { + const x = leafFrom + c * cellW; + push(x - sw / 2, x + sw / 2, leafBottom, leafTop, n0, n1); + } + for (let r = 1; r < rows; r++) { + const y = leafBottom + r * cellH; + push(leafFrom, leafTo, y - sw / 2, y + sw / 2, n0, n1); + } + // Vertiefte Kassetten-Felder — dünner, mittig zurückversetzt. + const n0p = n0 + PANEL_RECESS; + const n1p = Math.max(n0p + 0.004, n1 - PANEL_RECESS); + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const fx0 = leafFrom + c * cellW + sw / 2; + const fx1 = leafFrom + (c + 1) * cellW - sw / 2; + const fy0 = leafBottom + r * cellH + sw / 2; + const fy1 = leafBottom + (r + 1) * cellH - sw / 2; + if (fx1 - fx0 <= EPS || fy1 - fy0 <= EPS) continue; + push(fx0, fx1, fy0, fy1, n0p, n1p); + } + } + return out; +} + /** * Emittiert je Fensteröffnung eine Glasscheibe und je Türöffnung die Füllung * (Blatt-Tafel, s. {@link doorLeafPanels}, plus Scheibe bei Glasanteil/ @@ -793,8 +900,15 @@ function doorLeafPanels( * `positions` liegen — wie bei den übrigen Meshes — in MODELL-Metern als * flaches (x, y, z=Höhe)-Array; render3d bildet sie selbst nach world * (x, Höhe, y) ab und rendert die Meshes doppelseitig (append_context_mesh), - * daher ist die Winding-Reihenfolge der Dreiecke unerheblich. `kind: "imported"` - * mit gesetzter `color` ⇒ render3d zeichnet die Scheibe in GLASS_RGB. + * daher ist die Winding-Reihenfolge der Dreiecke unerheblich. `kind: + * "extrusion"` (NICHT "imported"!) mit gesetzter `color` ⇒ render3d zeichnet + * die Scheibe in GLASS_RGB — "extrusion" ist zugleich die Weiche gegen die + * Nord-Achsen-Negation, die `append_context_mesh` NUR für `"imported"`/ + * `"terrain"` anwendet (echte, unabhängige Import-Rohdaten); Öffnungs-Boxen + * entstehen dagegen orientierungserhaltend aus der Wandachse wie eine Wand + * selbst (Fund 2026-09-27: mit `kind:"imported"` wäre die Scheibe/der Rahmen + * für jede Wand ausserhalb y=0 an der falschen Stelle gerendert worden — + * s. PENDENZEN.md). */ export function emitOpeningGlass(project: Project): RMesh[] { const out: RMesh[] = []; diff --git a/src/plan/toWalls3d/stairs.ts b/src/plan/toWalls3d/stairs.ts index 7621771..088630c 100644 --- a/src/plan/toWalls3d/stairs.ts +++ b/src/plan/toWalls3d/stairs.ts @@ -131,9 +131,9 @@ function closedRiserOutline( * ergänzt (sonst bleibt die Treppe dort offen) — wortgetreu wie im Three.js- * Pfad, hier ans WASM/wgpu-Default-3D nachgezogen (beide Felder waren dort * unwirksam: existierten im Modell + der ResourceManager-UI, aber der - * Standard-Renderer las sie nie, s. PENDENZEN.md). Geländer sind weiterhin - * eine Verfeinerung (Three.js-Pfad, dort selbst noch als TODO markiert) — - * hier zählt zuerst die SICHTBARKEIT. + * Standard-Renderer las sie nie, s. PENDENZEN.md). Handlauf/Geländer + * (`StairType.railing`) sind separat in {@link emitStairRailings} (nur + * gerade Läufe, s. dort). * `ceilingId` trägt hier die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert * das Feld, und der Pick läuft separat über `pickGeometry`). */ @@ -274,3 +274,122 @@ export function emitStairMeshes(project: Project): RMesh[] { } return out; } + +/** Neutrales Metallgrau für Handlauf + Pfosten. */ +const RAIL_RGB: RRgb = hexToRgb("#74797f", SLAB_RGB); +/** Handlaufhöhe über der Trittvorderkante (SIA-üblich), Meter. */ +const RAIL_HEIGHT = 0.9; +/** Handlauf-/Pfosten-Querschnitt (Kantenlänge), Meter. */ +const RAIL_THICK = 0.04; + +type Vec3 = { x: number; y: number; z: number }; + +/** + * Schlanker Quader zwischen zwei beliebigen 3D-Punkten (Modell-Meter, NICHT + * an eine Wandachse gebunden — anders als die übrigen Quader-Helfer in + * `openings.ts`, die alle wand-lokale Achsen voraussetzen). Querschnitt-Achsen + * werden aus einem festen Welt-„oben" (0,0,1) abgeleitet (fällt bei fast + * senkrechten Segmenten — Pfosten — auf die X-Achse zurück, damit das + * Kreuzprodukt nicht entartet). `null` bei entartetem (zu kurzem) Segment. + */ +function strutBox(a: Vec3, b: Vec3, half: number, color: RRgb): RMesh | null { + const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z; + const len = Math.hypot(dx, dy, dz); + if (len < EPS) return null; + const d = { x: dx / len, y: dy / len, z: dz / len }; + const upRef: Vec3 = Math.abs(d.z) > 0.98 ? { x: 1, y: 0, z: 0 } : { x: 0, y: 0, z: 1 }; + let rx = d.y * upRef.z - d.z * upRef.y; + let ry = d.z * upRef.x - d.x * upRef.z; + let rz = d.x * upRef.y - d.y * upRef.x; + const rl = Math.hypot(rx, ry, rz) || 1; + rx /= rl; ry /= rl; rz /= rl; + const ux = ry * d.z - rz * d.y; + const uy = rz * d.x - rx * d.z; + const uz = rx * d.y - ry * d.x; + const corners: Vec3[] = []; + for (const p of [a, b]) { + for (const [sr, su] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) { + corners.push({ + x: p.x + rx * sr * half + ux * su * half, + y: p.y + ry * sr * half + uy * su * half, + z: p.z + rz * sr * half + uz * su * half, + }); + } + } + const positions: number[] = []; + for (const c of corners) positions.push(c.x, c.y, c.z); + const indices: number[] = []; + const quad = (a0: number, b0: number, c0: number, d0: number) => + indices.push(a0, b0, c0, a0, c0, d0); + quad(0, 1, 2, 3); // Stirnfläche bei a + quad(7, 6, 5, 4); // Stirnfläche bei b + quad(0, 4, 5, 1); + quad(1, 5, 6, 2); + quad(2, 6, 7, 3); + quad(3, 7, 4, 0); + return { positions, indices, kind: "extrusion", color }; +} + +/** + * Handlauf + Pfosten (`StairType.railing`: "keine"|"links"|"rechts"|"beide") + * — bislang ein „totes" Feld: im Modell, im ResourceManager (`StairStylesTab`) + * und in den i18n-Labels längst vorhanden, aber von KEINEM Renderer je + * gelesen (weder dem alten Three.js-Pfad — dort selbst als TODO markiert — + * noch diesem WASM/wgpu-Default-3D). Nur für GERADE Läufe umgesetzt: bei + * einer geraden Treppe liegt die Vorderkante jedes Tritts (das Eckpunktpaar + * mit dem GRÖSSEREN Lauf-Parameter, s. `treadRect`/`stairGeometry`) exakt auf + * der linearen Rampen-Geraden (Steigung totalRise/runLength ist über den + * ganzen Lauf konstant) — Handlauf und Pfosten lassen sich daher als EIN + * gerades, schräges Segment je Seite + ein Pfosten je Trittvorderkante bauen, + * ohne die Stufen einzeln nachzubilden. L-Läufe/Wendeltreppen (Richtungs- + * wechsel bzw. keine lineare Rampe) bleiben bewusst aussen vor — eigener, + * grösserer Folgeschritt (Rampen-Polyline müsste knickweise bzw. als Spirale + * gebaut werden), kein Blocker für die Sichtbarkeit bei geraden Treppen, dem + * mit Abstand häufigsten Fall. + */ +export function emitStairRailings(project: Project): RMesh[] { + const out: RMesh[] = []; + for (const stair of project.stairs ?? []) { + if (stair.shape !== "straight") continue; + const st = getStairType(project, stair); + const railing = st?.railing ?? "keine"; + if (railing === "keine") continue; + const { zBottom, zTop } = stairVerticalExtent(project, stair); + const totalRise = zTop - zBottom; + if (totalRise <= EPS) continue; + const geo = stairGeometry(stair, totalRise); + if (geo.treads.length === 0) continue; + const sides: ("left" | "right")[] = + railing === "beide" ? ["left", "right"] : railing === "links" ? ["left"] : ["right"]; + for (const side of sides) { + // Tritt-Eckpunkte (s. treadRect): 0/1 = linke Kante (Start/Ende), + // 3/2 = rechte Kante (Start/Ende). Die „Ende"-Ecke jedes Tritts ist + // dessen Vorderkante (liegt auf der Rampen-Geraden, s. Funktionsdoc). + const iStart = side === "left" ? 0 : 3; + const iEnd = side === "left" ? 1 : 2; + const first = geo.treads[0]; + const startPt = first.pts[iStart]; + const last = geo.treads[geo.treads.length - 1]; + const endPt = last.pts[iEnd]; + const rail = strutBox( + { x: startPt.x, y: startPt.y, z: zBottom + RAIL_HEIGHT }, + { x: endPt.x, y: endPt.y, z: zTop + RAIL_HEIGHT }, + RAIL_THICK / 2, + RAIL_RGB, + ); + if (rail) out.push(rail); + const postAt = (p: Vec2, topZ: number) => { + const post = strutBox( + { x: p.x, y: p.y, z: topZ }, + { x: p.x, y: p.y, z: topZ + RAIL_HEIGHT }, + RAIL_THICK / 2, + RAIL_RGB, + ); + if (post) out.push(post); + }; + postAt(startPt, zBottom); // Fusspfosten am Bodenanschluss. + for (const tr of geo.treads) postAt(tr.pts[iEnd], zBottom + tr.topRise); + } + } + return out; +} diff --git a/src/state/commandAliasOverrides.test.ts b/src/state/commandAliasOverrides.test.ts new file mode 100644 index 0000000..46c6253 --- /dev/null +++ b/src/state/commandAliasOverrides.test.ts @@ -0,0 +1,42 @@ +/** + * `isValidAliasKey` — reine Validierung für die Kürzel-Remap-Sektion + * (Einstellungen). `loadAliasOverrides`/`saveAliasOverrides` sind + * localStorage-gekoppelt und bleiben — wie jeder localStorage-Code in diesem + * Projekt (Theme/Renderer-Modus) — ohne dediziertes Unit-Test, s. Kopfkommentar + * in `commandAliasOverrides.ts` (beide Funktionen sind bewusst defensiv: + * try/catch, No-op statt Absturz ohne funktionierendes localStorage). + */ +import { describe, it, expect } from "vitest"; +import { isValidAliasKey } from "./commandAliasOverrides"; + +describe("isValidAliasKey", () => { + it("akzeptiert ein einfaches Kürzel", () => { + expect(isValidAliasKey("zz")).toBe(true); + expect(isValidAliasKey("dr")).toBe(true); + }); + + it("trimmt und ist case-insensitiv (Grossbuchstaben sind gültig, werden aber wie klein behandelt)", () => { + expect(isValidAliasKey(" ZZ ")).toBe(true); + }); + + it("lehnt leere/nur-Leerzeichen-Strings ab", () => { + expect(isValidAliasKey("")).toBe(false); + expect(isValidAliasKey(" ")).toBe(false); + }); + + it("lehnt Leerzeichen/Kommas innerhalb des Kürzels ab", () => { + expect(isValidAliasKey("z z")).toBe(false); + expect(isValidAliasKey("z,z")).toBe(false); + }); + + it("lehnt 'r' und 'r...' ab (Kollision mit relativ-Koordinaten)", () => { + expect(isValidAliasKey("r")).toBe(false); + expect(isValidAliasKey("r5")).toBe(false); + expect(isValidAliasKey("r5,3")).toBe(false); + }); + + it("erlaubt andere mit 'r' beginnende Kürzel, die NICHT von einer Ziffer gefolgt werden", () => { + expect(isValidAliasKey("rf")).toBe(true); // z. B. bereits als eingebautes Kürzel für "roof" genutzt + expect(isValidAliasKey("raum")).toBe(true); + }); +}); diff --git a/src/state/commandAliasOverrides.ts b/src/state/commandAliasOverrides.ts new file mode 100644 index 0000000..01bdefc --- /dev/null +++ b/src/state/commandAliasOverrides.ts @@ -0,0 +1,55 @@ +// Nutzer-Kürzel-Übersteuerungen für die Befehlszeile (Nutzer-Wunsch: „Befehls- +// Kürzel sind hart codiert (`commands/registry.ts` ALIASES), keine Remap-UI"). +// Persistiert in localStorage (GERÄT-/Profil-weite Einstellung, wie Theme/ +// Renderer-Modus — kein Projekt-Feld, da es um die TIPP-Gewohnheit des +// Nutzers geht, nicht um Projektinhalt). Ein Eintrag `{taste: befehlsname}` +// überschreibt (nur für DIESEN Nutzer) das eingebaute Kürzel mit demselben +// Schlüssel, falls eins existiert — s. `commands/registry.ts::resolveCommand`. +// +// Reine Lese-/Schreib-/Validierungsfunktionen; die React-/Engine-Anbindung +// (laden beim Start, `engine.setAliasOverrides(...)` bei jeder Änderung) +// bleibt in App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +const STORAGE_KEY = "cad.commandAliasOverrides"; + +/** Liest die gespeicherten Kürzel-Übersteuerungen; `{}` ohne gespeicherten Wert oder bei kaputten Daten. */ +export function loadAliasOverrides(): Record { + try { + const raw = window.localStorage.getItem(STORAGE_KEY); + if (!raw) return {}; + const parsed: unknown = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; + const out: Record = {}; + for (const [k, v] of Object.entries(parsed as Record)) { + if (typeof v === "string") out[k] = v; + } + return out; + } catch { + return {}; + } +} + +/** Speichert die Kürzel-Übersteuerungen (bestes Bemühen — schlägt z. B. im privaten Fenster still fehl). */ +export function saveAliasOverrides(overrides: Record): void { + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(overrides)); + } catch { + // Ignorieren (Quota/privates Fenster) — dieselbe Bestes-Bemühen-Haltung wie + // die übrigen localStorage-Einstellungen in diesem Projekt. + } +} + +/** + * Ist `key` als NEUER (oder geänderter) Kürzel-Eintrag gültig? Getrimmt, + * nicht leer, keine Leerzeichen/Kommas (würde mit der Koordinaten-/Options- + * Eingabe der Befehlszeile kollidieren) und NICHT `r…` (kollidiert mit dem + * relativ-Koordinaten-Präfix, dieselbe Ausnahme wie bei den eingebauten + * Kürzeln, s. Kopfkommentar von `ALIASES` in `registry.ts`). + */ +export function isValidAliasKey(key: string): boolean { + const k = key.trim().toLowerCase(); + if (k.length === 0) return false; + if (/[\s,]/.test(k)) return false; + if (k === "r" || /^r\d/.test(k)) return false; + return true; +} diff --git a/src/state/exportScope.test.ts b/src/state/exportScope.test.ts new file mode 100644 index 0000000..a5912fc --- /dev/null +++ b/src/state/exportScope.test.ts @@ -0,0 +1,89 @@ +// Export-Scope „nur Auswahl" (`filterProjectToSelection`/`selectionMemberCount`), +// s. exportScope.ts. + +import { describe, it, expect } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { filterProjectToSelection, selectionMemberCount } from "./exportScope"; +import type { Project, Wall, Drawing2D } from "../model/types"; + +const wall1: Wall = { + id: "w1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 4, y: 0 }, + wallTypeId: sampleProject.wallTypes[0]?.id ?? "wt1", + height: 2.6, +}; +const wall2: Wall = { ...wall1, id: "w2" }; + +const drawing1: Drawing2D = { + id: "d1", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, +}; +const drawing2: Drawing2D = { ...drawing1, id: "d2" }; + +function project(overrides: Partial): Project { + return { + ...sampleProject, + walls: [wall1, wall2], + drawings2d: [drawing1, drawing2], + ...overrides, + }; +} + +describe("filterProjectToSelection", () => { + it("behält nur ausgewählte Wände/Zeichnungen, andere Elemente unangetastet", () => { + const p = project({}); + const next = filterProjectToSelection(p, { wallIds: ["w1"], drawingIds: ["d2"] }); + expect(next.walls.map((w) => w.id)).toEqual(["w1"]); + expect(next.drawings2d.map((d) => d.id)).toEqual(["d2"]); + // Bibliotheken/Ebenen unverändert (dieselbe Referenz, nicht kopiert). + expect(next.wallTypes).toBe(p.wallTypes); + expect(next.drawingLevels).toBe(p.drawingLevels); + }); + + it("leert eine Art komplett, wenn dafür keine IDs angegeben sind", () => { + const p = project({}); + const next = filterProjectToSelection(p, { wallIds: ["w1"] }); + expect(next.walls.map((w) => w.id)).toEqual(["w1"]); + expect(next.drawings2d).toEqual([]); + }); + + it("leert ALLES bei komplett leerer Auswahl (kein Element selektiert)", () => { + const p = project({}); + const next = filterProjectToSelection(p, {}); + expect(next.walls).toEqual([]); + expect(next.drawings2d).toEqual([]); + expect(next.ceilings).toEqual([]); + expect(next.rooms).toEqual([]); + }); + + it("lässt das Ursprungsprojekt unverändert (Immutabilität)", () => { + const p = project({}); + filterProjectToSelection(p, { wallIds: ["w1"] }); + expect(p.walls).toHaveLength(2); + }); + + it("ignoriert unbekannte IDs (kein Crash, einfach nicht enthalten)", () => { + const p = project({}); + const next = filterProjectToSelection(p, { wallIds: ["does-not-exist"] }); + expect(next.walls).toEqual([]); + }); +}); + +describe("selectionMemberCount", () => { + it("zählt über alle Arten", () => { + expect( + selectionMemberCount({ wallIds: ["w1", "w2"], drawingIds: ["d1"] }), + ).toBe(3); + }); + + it("liefert 0 bei leerem Objekt", () => { + expect(selectionMemberCount({})).toBe(0); + }); +}); diff --git a/src/state/exportScope.ts b/src/state/exportScope.ts new file mode 100644 index 0000000..298756f --- /dev/null +++ b/src/state/exportScope.ts @@ -0,0 +1,57 @@ +// Export-Scope „nur Auswahl" (Nutzer-Wunsch aus der 2D-Lücken-Recherche: +// „Export exportiert immer den GANZEN Plan" — weder DXF- noch PDF-Dialog +// bieten einen Scope). Reine Projekt-Transform-Funktion: baut ein Project, +// das NUR die ausgewählten Elemente der acht `MemberKind`-Arten enthält +// (dieselbe Abdeckung wie `objectLock.ts`/`groupActions.ts`), sonst +// unverändert (Bibliotheken/Ebenen/Geschosse bleiben stehen, damit ID- +// Referenzen — Wandtyp, Linienstil, Layer — weiter auflösen). Wird VOR +// `generatePlan()` angewendet, analog `projectToWorldCoords()` beim +// DXF-Export — `generatePlan.ts` selbst bleibt unangetastet. +// +// `project.doors` (Legacy-Feld, s. PENDENZEN.md — echte Türen sind +// `Opening kind=door`) braucht KEINEN eigenen Filter: `generatePlan.ts` +// filtert Türen ohnehin über `hostWallId` gegen die (hier bereits +// gefilterten) Wände, nicht ausgewählte Wände nehmen also automatisch +// keine Türen mehr mit. +// +// Reines Modul: keine React-/Store-Abhängigkeit, wie `objectLock.ts`. +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { Project } from "../model/types"; +import type { GroupMembership } from "./groupActions"; + +/** + * Baut ein Project, das nur die in `members` aufgeführten Elemente der acht + * Arten enthält — jede Art OHNE Eintrag (oder mit leerer Liste) wird + * komplett geleert (das ist der Zweck: „nur Auswahl", nicht „alles ausser + * explizit ausgeschlossen"). + */ +export function filterProjectToSelection( + project: Project, + members: Partial, +): Project { + const wallIds = new Set(members.wallIds ?? []); + const drawingIds = new Set(members.drawingIds ?? []); + const ceilingIds = new Set(members.ceilingIds ?? []); + const roomIds = new Set(members.roomIds ?? []); + const stairIds = new Set(members.stairIds ?? []); + const columnIds = new Set(members.columnIds ?? []); + const roofIds = new Set(members.roofIds ?? []); + const openingIds = new Set(members.openingIds ?? []); + return { + ...project, + walls: project.walls.filter((w) => wallIds.has(w.id)), + drawings2d: project.drawings2d.filter((d) => drawingIds.has(d.id)), + ceilings: (project.ceilings ?? []).filter((c) => ceilingIds.has(c.id)), + rooms: (project.rooms ?? []).filter((r) => roomIds.has(r.id)), + stairs: (project.stairs ?? []).filter((s) => stairIds.has(s.id)), + columns: (project.columns ?? []).filter((c) => columnIds.has(c.id)), + roofs: (project.roofs ?? []).filter((r) => roofIds.has(r.id)), + openings: (project.openings ?? []).filter((o) => openingIds.has(o.id)), + }; +} + +/** Gesamtzahl ausgewählter Elemente über alle acht Arten (0 = keine Auswahl). */ +export function selectionMemberCount(members: Partial): number { + return Object.values(members).reduce((sum, ids) => sum + (ids?.length ?? 0), 0); +} diff --git a/src/state/keyboardShortcuts.test.ts b/src/state/keyboardShortcuts.test.ts new file mode 100644 index 0000000..9ce265e --- /dev/null +++ b/src/state/keyboardShortcuts.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from "vitest"; +import { + comboFromEvent, + comboMatches, + findConflict, + formatCombo, + isReservedCombo, + matchesShortcut, + resolveCombo, + SHORTCUT_DEFS, + type ShortcutOverrides, +} from "./keyboardShortcuts"; + +// Reines Objekt statt `new KeyboardEvent(...)` — Letzteres braucht ein DOM +// (im "node"-Vitest-Environment nicht vorhanden); `comboMatches`/`comboFromEvent` +// lesen ohnehin nur die vier Felder unten. +function key( + k: string, + mods: Partial<{ ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean }> = {}, +): KeyboardEvent { + return { + key: k, + ctrlKey: mods.ctrlKey ?? false, + metaKey: mods.metaKey ?? false, + shiftKey: mods.shiftKey ?? false, + altKey: mods.altKey ?? false, + } as KeyboardEvent; +} + +describe("SHORTCUT_DEFS", () => { + it("hat für jede Id eine eindeutige Default-Kombination (keine eingebaute Kollision)", () => { + const seen = new Map(); + for (const def of SHORTCUT_DEFS) { + const prev = seen.get(def.defaultCombo); + expect(prev, `${def.defaultCombo} kollidiert: ${prev} vs ${def.id}`).toBeUndefined(); + seen.set(def.defaultCombo, def.id); + } + }); +}); + +describe("comboMatches", () => { + it("erkennt Ctrl/Cmd+Z (mod+z)", () => { + expect(comboMatches(key("z", { ctrlKey: true }), "mod+z")).toBe(true); + expect(comboMatches(key("z", { metaKey: true }), "mod+z")).toBe(true); + expect(comboMatches(key("Z", { metaKey: true }), "mod+z")).toBe(true); // Grossbuchstabe (Caps/Shift-Ambiguität) egal + }); + + it("verlangt exakte Modifikator-Übereinstimmung (kein zusätzliches Shift)", () => { + expect(comboMatches(key("z", { ctrlKey: true, shiftKey: true }), "mod+z")).toBe(false); + expect(comboMatches(key("z", { ctrlKey: true, shiftKey: true }), "mod+shift+z")).toBe(true); + }); + + it("bare-Key ohne Modifikator matcht nur ohne jeden Modifikator", () => { + expect(comboMatches(key("m"), "m")).toBe(true); + expect(comboMatches(key("m", { ctrlKey: true }), "m")).toBe(false); + expect(comboMatches(key("m", { shiftKey: true }), "m")).toBe(false); + }); + + it("Sondertasten (Delete) werden namentlich, nicht kleingeschrieben verglichen", () => { + expect(comboMatches(key("Delete"), "Delete")).toBe(true); + expect(comboMatches(key("Backspace"), "Delete")).toBe(false); + }); +}); + +describe("comboFromEvent", () => { + it("liefert null bei reinem Modifikator-Tastendruck", () => { + expect(comboFromEvent(key("Control"))).toBeNull(); + expect(comboFromEvent(key("Shift"))).toBeNull(); + }); + + it("baut die Kombination in fester Reihenfolge mod+shift+alt+key", () => { + expect(comboFromEvent(key("g", { metaKey: true, shiftKey: true }))).toBe("mod+shift+g"); + expect(comboFromEvent(key("G", { ctrlKey: true }))).toBe("mod+g"); + expect(comboFromEvent(key("q"))).toBe("q"); + }); +}); + +describe("resolveCombo / matchesShortcut", () => { + it("nutzt den Default ohne Übersteuerung", () => { + expect(resolveCombo("undo", {})).toBe("mod+z"); + expect(matchesShortcut(key("z", { ctrlKey: true }), "undo", {})).toBe(true); + }); + + it("nutzt die Übersteuerung, sobald vorhanden", () => { + const overrides: ShortcutOverrides = { undo: "mod+shift+u" }; + expect(resolveCombo("undo", overrides)).toBe("mod+shift+u"); + expect(matchesShortcut(key("z", { ctrlKey: true }), "undo", overrides)).toBe(false); + expect(matchesShortcut(key("u", { ctrlKey: true, shiftKey: true }), "undo", overrides)).toBe( + true, + ); + }); +}); + +describe("findConflict", () => { + it("findet eine Kollision mit einer anderen Default-Kombination", () => { + expect(findConflict("mod+a", "undo", {})).toBe("selectAll"); + }); + + it("ignoriert die eigene Id", () => { + expect(findConflict("mod+z", "undo", {})).toBeNull(); + }); + + it("berücksichtigt bereits gesetzte Übersteuerungen anderer Ids", () => { + const overrides: ShortcutOverrides = { redo: "mod+r" }; + expect(findConflict("mod+r", "undo", overrides)).toBe("redo"); + }); +}); + +describe("isReservedCombo", () => { + it("verweigert die fest reservierten Steuer-Tasten", () => { + expect(isReservedCombo("Tab")).toBe(true); + expect(isReservedCombo("Enter")).toBe(true); + expect(isReservedCombo("Escape")).toBe(true); + expect(isReservedCombo("Backspace")).toBe(true); + }); + + it("erlaubt normale Kombinationen", () => { + expect(isReservedCombo("mod+z")).toBe(false); + expect(isReservedCombo("m")).toBe(false); + }); +}); + +describe("formatCombo", () => { + it("macOS-Darstellung: Symbole ohne Trenner", () => { + expect(formatCombo("mod+shift+z", true)).toBe("⌘⇧Z"); + }); + + it("Nicht-macOS-Darstellung: Wörter mit +", () => { + expect(formatCombo("mod+shift+z", false)).toBe("Strg+Umschalt+Z"); + }); + + it("Sondertasten bekommen ein lesbares Label", () => { + expect(formatCombo("Delete", false)).toBe("Entf"); + }); + + it("bare-Key bleibt Grossbuchstabe ohne Modifikator-Präfix", () => { + expect(formatCombo("m", false)).toBe("M"); + }); +}); + +// `loadShortcutOverrides`/`saveShortcutOverrides` sind localStorage-gekoppelt +// und bleiben — wie `loadAliasOverrides`/`saveAliasOverrides` (s. +// commandAliasOverrides.test.ts) — ohne dediziertes Unit-Test (window/ +// localStorage im "node"-Vitest-Environment nicht vorhanden); beide sind +// bewusst defensiv (try/catch, No-op statt Absturz). diff --git a/src/state/keyboardShortcuts.ts b/src/state/keyboardShortcuts.ts new file mode 100644 index 0000000..0f8fd00 --- /dev/null +++ b/src/state/keyboardShortcuts.ts @@ -0,0 +1,351 @@ +// Registry + Nutzer-Übersteuerungen für die GLOBALEN Tastatur-Shortcuts +// (Undo/Redo, Alles-wählen, Löschen, Split/Join, Kopieren/Einfügen, Boolean- +// Ops, Bewegen/Spiegeln/Drehen/Messen, Gruppieren, Werkzeug-Zifferntasten). +// Nutzer-Wunsch: „Einstellungen vollständiger machen, damit man eigene +// Shortcuts setzen kann" — bisher waren alle Kombinationen hart in +// `useKeyboardShortcuts.ts` verdrahtet (literale `e.key`/`e.ctrlKey`-Checks, +// keine Indirektion). ACHTUNG Abgrenzung zu `commandAliasOverrides.ts`: DAS +// dort sind Tipp-Kürzel für die Befehlszeile („w" → wall); DIESES Modul sind +// echte `keydown`-Tastenkombinationen (Ctrl/Cmd+Z usw.). +// +// Bewusst NICHT rebindbar (bleiben hart codiert, kollidieren sonst mit +// Kontext-Verhalten, das gar nicht über dieses Registry läuft): Tab/Enter/ +// Escape/Backspace als Werkzeug-Steuerung (Feld-Zyklus, Gesten-Abschluss, +// Punkt zurücknehmen, Entwurf verwerfen) sowie die Ctrl/Cmd+Y-Redo- und +// Backspace-Löschen-ZUSATZ-Bindungen (bleiben als fixe Zweit-Belegung neben +// der hier konfigurierbaren Haupt-Kombination bestehen, s. `useUndoRedoShortcut`/ +// `useSelectAllAndDeleteShortcut`). +// +// Reine Logik (Parsen/Matchen/Formatieren/Persistenz); die React-Anbindung +// (Laden beim Start, Weiterreichen an die Hooks, Cross-Fenster-`storage`- +// Sync) bleibt in App.tsx — exaktes Muster wie `commandAliasOverrides.ts`. +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +export type ShortcutId = + | "undo" + | "redo" + | "selectAll" + | "deleteSelection" + | "split" + | "join" + | "copyElements" + | "pasteElements" + | "booleanUnion" + | "booleanDifference" + | "booleanIntersection" + | "transformMove" + | "transformMirror" + | "transformRotate" + | "measure" + | "group" + | "ungroup" + | "toolText" + | "toolLine" + | "toolCircle" + | "toolRect" + | "toolPolyline" + | "toolWall" + | "toolCeiling" + | "toolWindow" + | "toolDoor" + | "toolRoom"; + +export type ShortcutCategory = + | "general" + | "selection" + | "edit" + | "boolean" + | "transform" + | "group" + | "tools"; + +export interface ShortcutDef { + id: ShortcutId; + category: ShortcutCategory; + /** i18n-Key für die Aktions-Beschriftung, s. `shortcut.` in de.ts/en.ts. */ + labelKey: string; + defaultCombo: string; + /** Bare-Key-Shortcuts (Werkzeug-/Transform-Kürzel): die Remap-UI verweigert + * hier eine Kombination MIT Modifikator (Ctrl/Shift/Alt bleiben frei fürs + * Tippen/OS-Kürzel — dieselbe Einschränkung, die die Hooks vorher schon + * hart hatten). */ + bareKeyOnly?: boolean; +} + +export const SHORTCUT_DEFS: ShortcutDef[] = [ + { id: "undo", category: "general", labelKey: "shortcut.undo", defaultCombo: "mod+z" }, + { id: "redo", category: "general", labelKey: "shortcut.redo", defaultCombo: "mod+shift+z" }, + { id: "selectAll", category: "selection", labelKey: "shortcut.selectAll", defaultCombo: "mod+a" }, + { + id: "deleteSelection", + category: "selection", + labelKey: "shortcut.deleteSelection", + defaultCombo: "Delete", + }, + { id: "split", category: "edit", labelKey: "shortcut.split", defaultCombo: "mod+s" }, + { id: "join", category: "edit", labelKey: "shortcut.join", defaultCombo: "mod+j" }, + { id: "copyElements", category: "edit", labelKey: "shortcut.copyElements", defaultCombo: "mod+c" }, + { id: "pasteElements", category: "edit", labelKey: "shortcut.pasteElements", defaultCombo: "mod+v" }, + { + id: "booleanUnion", + category: "boolean", + labelKey: "shortcut.booleanUnion", + defaultCombo: "mod+shift+u", + }, + { + id: "booleanDifference", + category: "boolean", + labelKey: "shortcut.booleanDifference", + defaultCombo: "mod+shift+d", + }, + { + id: "booleanIntersection", + category: "boolean", + labelKey: "shortcut.booleanIntersection", + defaultCombo: "mod+shift+i", + }, + { + id: "transformMove", + category: "transform", + labelKey: "shortcut.transformMove", + defaultCombo: "m", + bareKeyOnly: true, + }, + { + id: "transformMirror", + category: "transform", + labelKey: "shortcut.transformMirror", + defaultCombo: "s", + bareKeyOnly: true, + }, + { + id: "transformRotate", + category: "transform", + labelKey: "shortcut.transformRotate", + defaultCombo: "d", + bareKeyOnly: true, + }, + { + id: "measure", + category: "transform", + labelKey: "shortcut.measure", + defaultCombo: "q", + bareKeyOnly: true, + }, + { id: "group", category: "group", labelKey: "shortcut.group", defaultCombo: "mod+g" }, + { id: "ungroup", category: "group", labelKey: "shortcut.ungroup", defaultCombo: "mod+shift+g" }, + { + id: "toolText", + category: "tools", + labelKey: "shortcut.toolText", + defaultCombo: "1", + bareKeyOnly: true, + }, + { + id: "toolLine", + category: "tools", + labelKey: "shortcut.toolLine", + defaultCombo: "2", + bareKeyOnly: true, + }, + { + id: "toolCircle", + category: "tools", + labelKey: "shortcut.toolCircle", + defaultCombo: "3", + bareKeyOnly: true, + }, + { + id: "toolRect", + category: "tools", + labelKey: "shortcut.toolRect", + defaultCombo: "4", + bareKeyOnly: true, + }, + { + id: "toolPolyline", + category: "tools", + labelKey: "shortcut.toolPolyline", + defaultCombo: "5", + bareKeyOnly: true, + }, + { + id: "toolWall", + category: "tools", + labelKey: "shortcut.toolWall", + defaultCombo: "6", + bareKeyOnly: true, + }, + { + id: "toolCeiling", + category: "tools", + labelKey: "shortcut.toolCeiling", + defaultCombo: "7", + bareKeyOnly: true, + }, + { + id: "toolWindow", + category: "tools", + labelKey: "shortcut.toolWindow", + defaultCombo: "8", + bareKeyOnly: true, + }, + { + id: "toolDoor", + category: "tools", + labelKey: "shortcut.toolDoor", + defaultCombo: "9", + bareKeyOnly: true, + }, + { + id: "toolRoom", + category: "tools", + labelKey: "shortcut.toolRoom", + defaultCombo: "0", + bareKeyOnly: true, + }, +]; + +const DEFS_BY_ID = new Map(SHORTCUT_DEFS.map((d) => [d.id, d])); + +export function shortcutDef(id: ShortcutId): ShortcutDef { + const def = DEFS_BY_ID.get(id); + if (!def) throw new Error(`Unbekannte ShortcutId: ${id}`); + return def; +} + +export type ShortcutOverrides = Partial>; + +const STORAGE_KEY = "dossier.keyboardShortcutOverrides"; + +const KNOWN_IDS = new Set(SHORTCUT_DEFS.map((d) => d.id)); + +/** Liest die gespeicherten Tastenkombinations-Übersteuerungen; `{}` ohne gespeicherten Wert oder bei kaputten Daten. */ +export function loadShortcutOverrides(): ShortcutOverrides { + try { + const raw = window.localStorage.getItem(STORAGE_KEY); + if (!raw) return {}; + const parsed: unknown = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; + const out: ShortcutOverrides = {}; + for (const [k, v] of Object.entries(parsed as Record)) { + if (KNOWN_IDS.has(k) && typeof v === "string") out[k as ShortcutId] = v; + } + return out; + } catch { + return {}; + } +} + +/** Speichert die Tastenkombinations-Übersteuerungen (bestes Bemühen). */ +export function saveShortcutOverrides(overrides: ShortcutOverrides): void { + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(overrides)); + } catch { + // Ignorieren (Quota/privates Fenster) — gleiche Bestes-Bemühen-Haltung wie + // die übrigen localStorage-Einstellungen in diesem Projekt. + } +} + +/** Aktuell wirksame Kombination (Übersteuerung falls vorhanden, sonst Default). */ +export function resolveCombo(id: ShortcutId, overrides: ShortcutOverrides): string { + return overrides[id] ?? shortcutDef(id).defaultCombo; +} + +const MODIFIER_KEYS = new Set(["Control", "Meta", "Shift", "Alt"]); + +/** + * Kombination aus einem `keydown`-Event für die Aufnahme-UI („nächste + * Tastenkombination drücken"). `null`, solange nur ein reiner Modifikator + * gedrückt ist (kein Ziel-Ereignis) — die UI wartet dann weiter. + */ +export function comboFromEvent(e: KeyboardEvent): string | null { + if (MODIFIER_KEYS.has(e.key)) return null; + const parts: string[] = []; + if (e.ctrlKey || e.metaKey) parts.push("mod"); + if (e.shiftKey) parts.push("shift"); + if (e.altKey) parts.push("alt"); + const key = e.key.length === 1 ? e.key.toLowerCase() : e.key; + parts.push(key); + return parts.join("+"); +} + +/** Prüft ein `keydown`-Event gegen eine Kombinations-Zeichenkette (exakte Modifikator-Übereinstimmung). */ +export function comboMatches(e: KeyboardEvent, combo: string): boolean { + const parts = combo.split("+"); + const key = parts[parts.length - 1]; + const mods = parts.slice(0, -1); + const wantMod = mods.includes("mod"); + const wantShift = mods.includes("shift"); + const wantAlt = mods.includes("alt"); + if ((e.ctrlKey || e.metaKey) !== wantMod) return false; + if (e.shiftKey !== wantShift) return false; + if (e.altKey !== wantAlt) return false; + const k = e.key.length === 1 ? e.key.toLowerCase() : e.key; + return k === key; +} + +/** Kurzform: matcht `e` gegen die (übersteuerte oder Default-)Kombination von `id`. */ +export function matchesShortcut( + e: KeyboardEvent, + id: ShortcutId, + overrides: ShortcutOverrides, +): boolean { + return comboMatches(e, resolveCombo(id, overrides)); +} + +/** Ob `combo` bereits einer ANDEREN Aktion zugewiesen ist — für die Remap-UI (Kollisions-Warnung). */ +export function findConflict( + combo: string, + excludeId: ShortcutId, + overrides: ShortcutOverrides, +): ShortcutId | null { + for (const def of SHORTCUT_DEFS) { + if (def.id === excludeId) continue; + if (resolveCombo(def.id, overrides) === combo) return def.id; + } + return null; +} + +/** Bare-Keys, die system-weit fest für Werkzeug-/Gesten-Steuerung reserviert + * sind (Tab-Feld-Zyklus, Enter-Commit, Escape-Abbruch) und NICHT als neue + * Kombination vergeben werden dürfen — diese Tasten laufen ausserhalb dieses + * Registrys, eine Neu-Zuweisung würde still ins Leere laufen (die alte + * Kontext-Bindung bliebe unverändert bestehen, nur verwirrend doppelt belegt). */ +const RESERVED_BARE_COMBOS = new Set(["Tab", "Enter", "Escape", "Backspace"]); + +export function isReservedCombo(combo: string): boolean { + return RESERVED_BARE_COMBOS.has(combo); +} + +function isMacPlatform(): boolean { + if (typeof navigator === "undefined") return false; + return /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent || ""); +} + +const KEY_DISPLAY_LABELS: Record = { + Delete: "Entf", + Backspace: "Rücktaste", + Escape: "Esc", + Enter: "Enter", + Tab: "Tab", + " ": "Leertaste", + ArrowUp: "↑", + ArrowDown: "↓", + ArrowLeft: "←", + ArrowRight: "→", +}; + +/** Menschenlesbare Darstellung einer Kombination, plattformabhängig (⌘⇧Z auf macOS, Strg+Umschalt+Z sonst). */ +export function formatCombo(combo: string, mac: boolean = isMacPlatform()): string { + const parts = combo.split("+"); + const key = parts[parts.length - 1]; + const mods = parts.slice(0, -1); + const segs: string[] = []; + if (mods.includes("mod")) segs.push(mac ? "⌘" : "Strg"); + if (mods.includes("shift")) segs.push(mac ? "⇧" : "Umschalt"); + if (mods.includes("alt")) segs.push(mac ? "⌥" : "Alt"); + const keyLabel = KEY_DISPLAY_LABELS[key] ?? (key.length === 1 ? key.toUpperCase() : key); + segs.push(keyLabel); + return segs.join(mac ? "" : "+"); +} diff --git a/src/state/objectLock.test.ts b/src/state/objectLock.test.ts new file mode 100644 index 0000000..4ed2ef4 --- /dev/null +++ b/src/state/objectLock.test.ts @@ -0,0 +1,90 @@ +// Objekt-Sperre (`isLocked`/`setLocked`/`setLockedForMembers`) — reine +// Funktionen, s. objectLock.ts. Deckt alle acht `MemberKind`-Arten ab. + +import { describe, it, expect } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import { isLocked, setLocked, setLockedForMembers } from "./objectLock"; +import type { Project, Wall, Drawing2D } from "../model/types"; + +const wall: Wall = { + id: "w1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 4, y: 0 }, + wallTypeId: sampleProject.wallTypes[0]?.id ?? "wt1", + height: 2.6, +}; + +const drawing: Drawing2D = { + id: "d1", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, +}; + +function project(overrides: Partial): Project { + return { ...sampleProject, walls: [wall], drawings2d: [drawing], ...overrides }; +} + +describe("isLocked", () => { + it("liefert false für ein Element ohne locked-Feld (Default/Alt-Daten)", () => { + expect(isLocked(project({}), "wallIds", "w1")).toBe(false); + }); + + it("liefert false für eine unbekannte ID (kein Crash)", () => { + expect(isLocked(project({}), "wallIds", "does-not-exist")).toBe(false); + }); + + it("liefert true, wenn locked explizit gesetzt ist", () => { + const p = project({ walls: [{ ...wall, locked: true }] }); + expect(isLocked(p, "wallIds", "w1")).toBe(true); + }); + + it("funktioniert für drawingIds (Drawing2D)", () => { + const p = project({ drawings2d: [{ ...drawing, locked: true }] }); + expect(isLocked(p, "drawingIds", "d1")).toBe(true); + }); +}); + +describe("setLocked", () => { + it("setzt locked=true immutabel, andere Elemente bleiben unverändert", () => { + const otherWall: Wall = { ...wall, id: "w2" }; + const p = project({ walls: [wall, otherWall] }); + const next = setLocked(p, "wallIds", "w1", true); + expect(next).not.toBe(p); + expect(next.walls.find((w) => w.id === "w1")?.locked).toBe(true); + expect(next.walls.find((w) => w.id === "w2")?.locked).toBeUndefined(); + // Ursprüngliches Projekt unverändert (Immutabilität). + expect(p.walls.find((w) => w.id === "w1")?.locked).toBeUndefined(); + }); + + it("setzt locked=false zum Entsperren", () => { + const p = project({ walls: [{ ...wall, locked: true }] }); + const next = setLocked(p, "wallIds", "w1", false); + expect(next.walls[0].locked).toBe(false); + }); + + it("ist ein No-Op für eine unbekannte ID", () => { + const p = project({}); + const next = setLocked(p, "wallIds", "does-not-exist", true); + expect(next.walls).toEqual(p.walls); + }); +}); + +describe("setLockedForMembers", () => { + it("sperrt mehrere Elementarten in einem Zug", () => { + const p = project({}); + const next = setLockedForMembers(p, { wallIds: ["w1"], drawingIds: ["d1"] }, true); + expect(isLocked(next, "wallIds", "w1")).toBe(true); + expect(isLocked(next, "drawingIds", "d1")).toBe(true); + }); + + it("leere/fehlende Felder werden übersprungen (kein Crash)", () => { + const p = project({}); + const next = setLockedForMembers(p, { wallIds: [] }, true); + expect(next.walls).toEqual(p.walls); + }); +}); diff --git a/src/state/objectLock.ts b/src/state/objectLock.ts new file mode 100644 index 0000000..b8e9773 --- /dev/null +++ b/src/state/objectLock.ts @@ -0,0 +1,92 @@ +// Objekt-Sperre (Nutzer-Wunsch: „Kein Objekt-Lock" aus der 2D-Lücken- +// Recherche) — anders als der Ebenen-/Geschoss-Sperrmodus (`DisplayMode`, +// s. `panels/displayMode.ts`, rein session-lokal/ephemer) ist das hier ein +// PERSISTIERTES Feld (`locked?: boolean`) direkt am Element. Deckt dieselben +// acht Elementarten ab wie `groupActions.ts` `MemberKind` (Wand/2D-Zeichnung/ +// Decke/Raum/Treppe/Stütze/Dach/Öffnung) — ein gesperrtes Element lässt sich +// nicht anwählen (daher auch nicht verschieben/bearbeiten/löschen), s. +// `useMouseSelectionHandlers.ts` `onPlanSelect`/`onPlanMarquee`. +// +// Reines Modul: keine React-/Store-Abhängigkeit, wie `groupActions.ts`. +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { Project } from "../model/types"; +import type { MemberKind } from "./groupActions"; + +/** Ist das Element (Art + ID) gesperrt? `false` für unbekannte/fehlende IDs. */ +export function isLocked(project: Project, kind: MemberKind, id: string): boolean { + switch (kind) { + case "wallIds": + return !!project.walls.find((w) => w.id === id)?.locked; + case "drawingIds": + return !!project.drawings2d.find((d) => d.id === id)?.locked; + case "ceilingIds": + return !!(project.ceilings ?? []).find((c) => c.id === id)?.locked; + case "roomIds": + return !!(project.rooms ?? []).find((r) => r.id === id)?.locked; + case "stairIds": + return !!(project.stairs ?? []).find((s) => s.id === id)?.locked; + case "columnIds": + return !!(project.columns ?? []).find((c) => c.id === id)?.locked; + case "roofIds": + return !!(project.roofs ?? []).find((r) => r.id === id)?.locked; + case "openingIds": + return !!(project.openings ?? []).find((o) => o.id === id)?.locked; + } +} + +/** Setzt die Sperre eines Elements (immutabel); unbekannte IDs sind ein No-Op. */ +export function setLocked(project: Project, kind: MemberKind, id: string, locked: boolean): Project { + switch (kind) { + case "wallIds": + return { ...project, walls: project.walls.map((w) => (w.id === id ? { ...w, locked } : w)) }; + case "drawingIds": + return { + ...project, + drawings2d: project.drawings2d.map((d) => (d.id === id ? { ...d, locked } : d)), + }; + case "ceilingIds": + return { + ...project, + ceilings: (project.ceilings ?? []).map((c) => (c.id === id ? { ...c, locked } : c)), + }; + case "roomIds": + return { ...project, rooms: (project.rooms ?? []).map((r) => (r.id === id ? { ...r, locked } : r)) }; + case "stairIds": + return { + ...project, + stairs: (project.stairs ?? []).map((s) => (s.id === id ? { ...s, locked } : s)), + }; + case "columnIds": + return { + ...project, + columns: (project.columns ?? []).map((c) => (c.id === id ? { ...c, locked } : c)), + }; + case "roofIds": + return { ...project, roofs: (project.roofs ?? []).map((r) => (r.id === id ? { ...r, locked } : r)) }; + case "openingIds": + return { + ...project, + openings: (project.openings ?? []).map((o) => (o.id === id ? { ...o, locked } : o)), + }; + } +} + +/** + * Setzt die Sperre einer ganzen `GroupMembership`-förmigen Auswahl in EINEM + * Zug (ein Undo-Schritt für "Auswahl sperren/entsperren", nicht einer je + * Element). Reihenfolge/Struktur wie `MemberKind` — jedes Feld optional. + */ +export function setLockedForMembers( + project: Project, + members: Partial>, + locked: boolean, +): Project { + let next = project; + for (const kind of Object.keys(members) as MemberKind[]) { + for (const id of members[kind] ?? []) { + next = setLocked(next, kind, id, locked); + } + } + return next; +} diff --git a/src/state/projectSlice.customPalettes.test.ts b/src/state/projectSlice.customPalettes.test.ts new file mode 100644 index 0000000..5c63983 --- /dev/null +++ b/src/state/projectSlice.customPalettes.test.ts @@ -0,0 +1,126 @@ +/** + * Store-Actions für benutzerdefinierte Farbpaletten (`model/types.ts:: + * CustomPalette`, Farbmischer → „Diese Farbe speichern"). Reine CRUD ohne + * Baking-/Aktiv-Semantik (anders als Stiftsätze) — hier geht es nur um + * Anlegen/Umbenennen/Löschen sowie das Hinzufügen/Entfernen einzelner + * Farben inkl. Dedupe- und Auto-Anlegen-Verhalten. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; + +let clock = 0; +beforeEach(() => { + clock = 1_000_000; + vi.spyOn(Date, "now").mockImplementation(() => clock++); + setState({ + project: { ...sampleProject, components: sampleProject.components.slice(0, 1), customPalettes: [] }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("addCustomPalette", () => { + it("legt eine neue, leere Palette mit Default-Namen an", () => { + getState().addCustomPalette(); + const palettes = getState().project.customPalettes!; + expect(palettes.length).toBe(1); + expect(palettes[0].colors).toEqual([]); + expect(palettes[0].name.length).toBeGreaterThan(0); + }); + + it("mehrere Paletten können nebeneinander existieren", () => { + getState().addCustomPalette(); + getState().addCustomPalette(); + expect(getState().project.customPalettes!.length).toBe(2); + }); +}); + +describe("renameCustomPalette/deleteCustomPalette", () => { + it("benennt genau die angegebene Palette um", () => { + getState().addCustomPalette(); + getState().addCustomPalette(); + const [a, b] = getState().project.customPalettes!; + getState().renameCustomPalette(a.id, "Fassade"); + const after = getState().project.customPalettes!; + expect(after.find((p) => p.id === a.id)?.name).toBe("Fassade"); + expect(after.find((p) => p.id === b.id)?.name).toBe(b.name); + }); + + it("löscht genau die angegebene Palette", () => { + getState().addCustomPalette(); + getState().addCustomPalette(); + const [a, b] = getState().project.customPalettes!; + getState().deleteCustomPalette(a.id); + const after = getState().project.customPalettes!; + expect(after.length).toBe(1); + expect(after[0].id).toBe(b.id); + }); +}); + +describe("addColorToCustomPalette", () => { + it("legt automatisch eine Palette an, wenn keine `paletteId` passt", () => { + getState().addColorToCustomPalette(undefined, "#ff0000"); + const palettes = getState().project.customPalettes!; + expect(palettes.length).toBe(1); + expect(palettes[0].colors).toEqual(["#ff0000"]); + }); + + it("fügt neue Farben VORNE ein (zuletzt gespeichert zuerst)", () => { + getState().addCustomPalette(); + const id = getState().project.customPalettes![0].id; + getState().addColorToCustomPalette(id, "#ff0000"); + getState().addColorToCustomPalette(id, "#00ff00"); + expect(getState().project.customPalettes![0].colors).toEqual(["#00ff00", "#ff0000"]); + }); + + it("dedupliziert case-insensitive: erneutes Speichern verschiebt nur nach vorn", () => { + getState().addCustomPalette(); + const id = getState().project.customPalettes![0].id; + getState().addColorToCustomPalette(id, "#ff0000"); + getState().addColorToCustomPalette(id, "#00ff00"); + getState().addColorToCustomPalette(id, "#FF0000"); + const colors = getState().project.customPalettes![0].colors; + expect(colors).toEqual(["#FF0000", "#00ff00"]); + }); +}); + +describe("removeColorFromCustomPalette", () => { + it("entfernt genau die angegebene Farbe (case-insensitive)", () => { + getState().addCustomPalette(); + const id = getState().project.customPalettes![0].id; + getState().addColorToCustomPalette(id, "#ff0000"); + getState().addColorToCustomPalette(id, "#00ff00"); + getState().removeColorFromCustomPalette(id, "#FF0000"); + expect(getState().project.customPalettes![0].colors).toEqual(["#00ff00"]); + }); +}); + +describe("Sichtbarkeit (Farbwahl-Popover)", () => { + it("setCustomPaletteVisible blendet genau eine eigene Palette aus/ein", () => { + getState().addCustomPalette(); + const id = getState().project.customPalettes![0].id; + // Default: Feld fehlt ⇒ gilt als sichtbar (Bestandsprojekte unverändert). + expect(getState().project.customPalettes![0].visible).toBeUndefined(); + getState().setCustomPaletteVisible(id, false); + expect(getState().project.customPalettes![0].visible).toBe(false); + getState().setCustomPaletteVisible(id, true); + expect(getState().project.customPalettes![0].visible).toBe(true); + }); + + it("setBuiltinPaletteVisible schaltet einzelne Bänke, ohne die anderen anzufassen", () => { + getState().setBuiltinPaletteVisible("ral", false); + expect(getState().project.builtinPaletteBanks).toEqual({ ral: false }); + getState().setBuiltinPaletteVisible("tango", false); + expect(getState().project.builtinPaletteBanks).toEqual({ ral: false, tango: false }); + getState().setBuiltinPaletteVisible("ral", true); + expect(getState().project.builtinPaletteBanks).toEqual({ ral: true, tango: false }); + }); +}); diff --git a/src/state/projectSlice.leaderBendGrips.test.ts b/src/state/projectSlice.leaderBendGrips.test.ts new file mode 100644 index 0000000..25ef4f6 --- /dev/null +++ b/src/state/projectSlice.leaderBendGrips.test.ts @@ -0,0 +1,101 @@ +/** + * Griffe einer mehrsegmentigen Hinweislinie (`leaderBendPoints`) — + * `drawingVertices`/`moveGripOf` in `projectSlice.ts`. Reihenfolge: Anker + * (Index 0) → Knickpunkte (Index 1..N) → Spitze (letzter Index), wie der + * Pfad gerendert wird (s. `plan/generatePlan.leaderBends.test.ts`). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import { drawingVertices } from "./projectSlice"; +import type { Drawing2D } from "../model/types"; + +const leaderNoBends: Drawing2D = { + id: "d-leader-0", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "text", at: { x: 0, y: 0 }, text: "", height: 0.2, angle: 0, leaderTarget: { x: 10, y: 0 } }, +}; + +const leaderTwoBends: Drawing2D = { + id: "d-leader-2", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { + shape: "text", + at: { x: 0, y: 0 }, + text: "", + height: 0.2, + angle: 0, + leaderTarget: { x: 10, y: 0 }, + leaderBendPoints: [{ x: 3, y: 3 }, { x: 6, y: -2 }], + }, +}; + +beforeEach(() => { + setState({ + project: { ...sampleProject, drawings2d: [leaderNoBends, leaderTwoBends] }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +describe("drawingVertices — Hinweislinie mit Knickpunkten", () => { + it("ohne Knicke: weiterhin genau zwei Griffe (Anker, Spitze)", () => { + expect(drawingVertices(leaderNoBends)).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }]); + }); + + it("zwei Knicke: vier Griffe in Reihenfolge Anker→Knick1→Knick2→Spitze", () => { + expect(drawingVertices(leaderTwoBends)).toEqual([ + { x: 0, y: 0 }, + { x: 3, y: 3 }, + { x: 6, y: -2 }, + { x: 10, y: 0 }, + ]); + }); +}); + +describe("moveGripOf — Hinweislinie mit Knickpunkten", () => { + it("Griff 0 verschiebt den Textanker (`at`), Knicke/Spitze bleiben unverändert", () => { + getState().moveGripOf("d-leader-2", null, 0, { x: -5, y: -5 }); + const g = getState().project.drawings2d.find((d) => d.id === "d-leader-2")!.geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.at).toEqual({ x: -5, y: -5 }); + expect(g.leaderBendPoints).toEqual([{ x: 3, y: 3 }, { x: 6, y: -2 }]); + expect(g.leaderTarget).toEqual({ x: 10, y: 0 }); + } + }); + + it("Griff 1 verschiebt NUR den ersten Knickpunkt", () => { + getState().moveGripOf("d-leader-2", null, 1, { x: 1, y: 9 }); + const g = getState().project.drawings2d.find((d) => d.id === "d-leader-2")!.geom; + if (g.shape === "text") { + expect(g.leaderBendPoints).toEqual([{ x: 1, y: 9 }, { x: 6, y: -2 }]); + expect(g.at).toEqual({ x: 0, y: 0 }); + expect(g.leaderTarget).toEqual({ x: 10, y: 0 }); + } + }); + + it("Griff 2 verschiebt NUR den zweiten Knickpunkt", () => { + getState().moveGripOf("d-leader-2", null, 2, { x: 7, y: 7 }); + const g = getState().project.drawings2d.find((d) => d.id === "d-leader-2")!.geom; + if (g.shape === "text") { + expect(g.leaderBendPoints).toEqual([{ x: 3, y: 3 }, { x: 7, y: 7 }]); + } + }); + + it("letzter Griff (Index 3) verschiebt die Spitze (`leaderTarget`), Knicke bleiben", () => { + getState().moveGripOf("d-leader-2", null, 3, { x: 20, y: 20 }); + const g = getState().project.drawings2d.find((d) => d.id === "d-leader-2")!.geom; + if (g.shape === "text") { + expect(g.leaderTarget).toEqual({ x: 20, y: 20 }); + expect(g.leaderBendPoints).toEqual([{ x: 3, y: 3 }, { x: 6, y: -2 }]); + } + }); +}); diff --git a/src/state/projectSlice.objectLock.test.ts b/src/state/projectSlice.objectLock.test.ts new file mode 100644 index 0000000..ad79ed5 --- /dev/null +++ b/src/state/projectSlice.objectLock.test.ts @@ -0,0 +1,87 @@ +/** + * Objekt-Sperre (`Wall.locked`/`Drawing2D.locked`) blockiert die MODIFIKATION + * direkt an den Mutations-Stellen (`moveGrip`/`moveElementBy`/`moveEdge` in + * projectSlice.ts) — bewusst NICHT die Auswahl selbst (sonst keine Möglichkeit + * mehr, ein gesperrtes Element über das Kontextmenü wieder zu entsperren, + * sobald die Selektion einmal woanders hin wechselt). S. auch + * `tools/transform.test.ts` für dieselbe Prüfung bei move/copy/mirror/… + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D, Wall } from "../model/types"; + +const lockedWall: Wall = { + id: "w-locked", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 4, y: 0 }, + wallTypeId: sampleProject.wallTypes[0]?.id ?? "wt1", + height: 2.6, + locked: true, +}; + +const lockedDrawing: Drawing2D = { + id: "d-locked", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 2, y: 0 } }, + locked: true, +}; + +beforeEach(() => { + setState({ + project: { ...sampleProject, walls: [lockedWall], drawings2d: [lockedDrawing] }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +describe("moveGripOf — Objekt-Sperre", () => { + it("gesperrte Wand: Griff-Ziehen ist ein No-Op", () => { + getState().moveGripOf(null, "w-locked", 0, { x: 9, y: 9 }); + const w = getState().project.walls.find((x) => x.id === "w-locked")!; + expect(w.start).toEqual({ x: 0, y: 0 }); + }); + + it("gesperrte 2D-Zeichnung: Griff-Ziehen ist ein No-Op", () => { + getState().moveGripOf("d-locked", null, 0, { x: 9, y: 9 }); + const g = getState().project.drawings2d.find((x) => x.id === "d-locked")!.geom; + expect(g.shape).toBe("line"); + if (g.shape === "line") expect(g.a).toEqual({ x: 0, y: 0 }); + }); +}); + +describe("moveElementByOf — Objekt-Sperre", () => { + it("gesperrte Wand: Körper-Verschieben ist ein No-Op", () => { + getState().moveElementByOf(null, "w-locked", { x: 3, y: 3 }); + const w = getState().project.walls.find((x) => x.id === "w-locked")!; + expect(w.start).toEqual({ x: 0, y: 0 }); + expect(w.end).toEqual({ x: 4, y: 0 }); + }); + + it("gesperrte 2D-Zeichnung: Körper-Verschieben ist ein No-Op", () => { + getState().moveElementByOf("d-locked", null, { x: 3, y: 3 }); + const g = getState().project.drawings2d.find((x) => x.id === "d-locked")!.geom; + expect(g.shape).toBe("line"); + if (g.shape === "line") expect(g.a).toEqual({ x: 0, y: 0 }); + }); +}); + +describe("moveEdgeOf — Objekt-Sperre", () => { + it("gesperrte 2D-Zeichnung: Kanten-Ziehen ist ein No-Op", () => { + getState().moveEdgeOf("d-locked", null, 0, 1, { x: 3, y: 3 }); + const g = getState().project.drawings2d.find((x) => x.id === "d-locked")!.geom; + expect(g.shape).toBe("line"); + if (g.shape === "line") { + expect(g.a).toEqual({ x: 0, y: 0 }); + expect(g.b).toEqual({ x: 2, y: 0 }); + } + }); +}); diff --git a/src/state/projectSlice.polylinePoints.test.ts b/src/state/projectSlice.polylinePoints.test.ts new file mode 100644 index 0000000..da3918a --- /dev/null +++ b/src/state/projectSlice.polylinePoints.test.ts @@ -0,0 +1,134 @@ +/** + * Stützpunkte einer Polylinie einfügen/entfernen (Kontextmenü im Grundriss). + * Schwerpunkt: die Bulge-Buchführung — ein eingefügter Punkt darf einen + * Bogen nicht still zu zwei Geraden machen, und ein entfernter Punkt darf + * die Bulge-Zuordnung der übrigen Segmente nicht verschieben. + */ + +import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import type { Drawing2D } from "../model/types"; +import { bulgeArc } from "../geometry/bulge"; + +const POLY_ID = "poly-test"; + +/** Legt EINE Polylinie als einziges 2D-Element ins Projekt. */ +function setPolyline(geom: Extract) { + const d: Drawing2D = { + id: POLY_ID, + type: "drawing2d", + levelId: sampleProject.drawingLevels[0].id, + categoryCode: sampleProject.layers[0].code, + geom, + }; + setState({ + project: { ...sampleProject, drawings2d: [d] }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +} + +const poly = () => { + const g = getState().project.drawings2d[0].geom; + if (g.shape !== "polyline") throw new Error("keine Polylinie"); + return g; +}; + +beforeEach(() => { + vi.spyOn(Date, "now").mockImplementation(() => 1_000_000); +}); +afterEach(() => vi.restoreAllMocks()); + +describe("insertDrawingPoint", () => { + it("fügt den Punkt im gewählten Segment ein (gerade: exakt am übergebenen Punkt)", () => { + setPolyline({ shape: "polyline", closed: false, pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }] }); + getState().insertDrawingPoint(POLY_ID, 0, { x: 2, y: 0 }); + expect(poly().pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }]); + }); + + it("geschlossene Polylinie: das Schluss-Segment (letzter → erster) ist einfügbar", () => { + setPolyline({ shape: "polyline", closed: true, pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }] }); + getState().insertDrawingPoint(POLY_ID, 2, { x: 2, y: 1.5 }); + expect(poly().pts.length).toBe(4); + expect(poly().pts[3]).toEqual({ x: 2, y: 1.5 }); + }); + + it("offene Polylinie: hinter dem letzten Punkt gibt es kein Segment — no-op", () => { + setPolyline({ shape: "polyline", closed: false, pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }] }); + getState().insertDrawingPoint(POLY_ID, 1, { x: 9, y: 9 }); + expect(poly().pts.length).toBe(2); + }); + + it("Bogen-Segment: teilt den Bogen exakt auf demselben Kreis, statt ihn zu begradigen", () => { + const a = { x: 0, y: 0 }; + const b = { x: 4, y: 0 }; + setPolyline({ shape: "polyline", closed: false, pts: [a, b], bulge: [0.5] }); + const orig = bulgeArc(a, b, 0.5)!; + getState().insertDrawingPoint(POLY_ID, 0, { x: 2, y: 0 }); + + const g = poly(); + expect(g.pts.length).toBe(3); + // Der neue Punkt liegt auf dem ursprünglichen Bogen (Bogenmitte), NICHT + // auf der Sehne — sonst wäre der Bogen zerstört. + const mid = g.pts[1]; + expect(Math.abs(mid.y)).toBeGreaterThan(0.1); + expect(Math.hypot(mid.x - orig.center.x, mid.y - orig.center.y)).toBeCloseTo(orig.r, 9); + + // Beide Teilbögen liegen auf demselben Kreis wie das Original (Mittelpunkt + // + Radius identisch) und behalten die Schwenkrichtung. + for (const [p0, p1, bl] of [ + [g.pts[0], g.pts[1], g.bulge![0]], + [g.pts[1], g.pts[2], g.bulge![1]], + ] as const) { + const half = bulgeArc(p0, p1, bl)!; + expect(half.center.x).toBeCloseTo(orig.center.x, 9); + expect(half.center.y).toBeCloseTo(orig.center.y, 9); + expect(half.r).toBeCloseTo(orig.r, 9); + expect(Math.sign(half.sweep)).toBe(Math.sign(orig.sweep)); + } + // Die zwei Teilschwenks ergeben zusammen den ursprünglichen Schwenk. + const s1 = bulgeArc(g.pts[0], g.pts[1], g.bulge![0])!.sweep; + const s2 = bulgeArc(g.pts[1], g.pts[2], g.bulge![1])!.sweep; + expect(s1 + s2).toBeCloseTo(orig.sweep, 9); + }); +}); + +describe("deleteDrawingPoint", () => { + it("entfernt genau den gewählten Punkt", () => { + setPolyline({ + shape: "polyline", + closed: false, + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }], + }); + getState().deleteDrawingPoint(POLY_ID, 1); + expect(poly().pts).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }]); + }); + + it("entfernt den Bulge-Eintrag desselben Index (Zuordnung bleibt stimmig)", () => { + setPolyline({ + shape: "polyline", + closed: false, + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }, { x: 6, y: 0 }], + bulge: [0.1, 0.2, 0.3], + }); + getState().deleteDrawingPoint(POLY_ID, 1); + expect(poly().bulge).toEqual([0.1, 0.3]); + }); + + it("blockiert, wenn zu wenige Punkte übrig blieben (offen <2, geschlossen <3)", () => { + setPolyline({ shape: "polyline", closed: false, pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }] }); + getState().deleteDrawingPoint(POLY_ID, 0); + expect(poly().pts.length).toBe(2); + + setPolyline({ + shape: "polyline", + closed: true, + pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }], + }); + getState().deleteDrawingPoint(POLY_ID, 0); + expect(poly().pts.length).toBe(3); + }); +}); diff --git a/src/state/projectSlice.textFrameGrips.test.ts b/src/state/projectSlice.textFrameGrips.test.ts new file mode 100644 index 0000000..d17f736 --- /dev/null +++ b/src/state/projectSlice.textFrameGrips.test.ts @@ -0,0 +1,141 @@ +/** + * Eckpunkt-Griffe einer Textspalte (`Drawing2DGeom["text"]` mit `width` + * gesetzt) — Nutzer-Wunsch: "nicht nur ein Griff unten links bei der ersten + * Glyphe" (vorher: `drawingVertices` lieferte für Text IMMER nur `[at]`, + * unabhängig von `width`). Vier Rahmen-Ecken als Griffe (s. + * `text/textFrame.ts` `textFrameCorners`); Ziehen ändert NUR die Spaltenbreite + * (`width`) — InDesign-Textrahmen-Verhalten (Nutzer-Entscheidung), nicht die + * Schriftgrösse. Einzeiliger Text OHNE `width` bleibt beim bisherigen + * Einzel-Anker-Griff (kein Regressions-Risiko für den Alltagsfall). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import { drawingVertices } from "./projectSlice"; +import { textFrameCorners } from "../text/textFrame"; +import type { Drawing2D } from "../model/types"; + +const plainText: Drawing2D = { + id: "d-text-plain", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { shape: "text", at: { x: 1, y: 1 }, text: "Hallo", height: 0.2, angle: 0 }, +}; + +const textBox: Drawing2D = { + id: "d-text-box", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { + shape: "text", + at: { x: 0, y: 0 }, + text: "Ein langer Textspalten-Inhalt, der umbricht", + height: 0.2, + angle: 0, + width: 1.5, + }, +}; + +const rotatedTextBox: Drawing2D = { + id: "d-text-box-rot", + type: "drawing2d", + levelId: "eg", + categoryCode: "00", + geom: { + shape: "text", + at: { x: 5, y: 5 }, + text: "Ein langer Textspalten-Inhalt, der umbricht", + height: 0.2, + angle: Math.PI / 2, + width: 1.5, + }, +}; + +beforeEach(() => { + setState({ + project: { + ...sampleProject, + drawings2d: [plainText, textBox, rotatedTextBox], + }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +describe("drawingVertices — Text", () => { + it("einzeiliger Text OHNE width liefert weiterhin nur den Anker-Griff (kein Regressions-Risiko)", () => { + expect(drawingVertices(plainText)).toEqual([{ x: 1, y: 1 }]); + }); + + it("Textspalte MIT width liefert vier Rahmen-Eck-Griffe (deckt sich mit textFrameCorners)", () => { + const v = drawingVertices(textBox); + expect(v).toHaveLength(4); + const g = textBox.geom as Extract; + const expected = textFrameCorners({ + at: g.at, + text: g.text, + heightM: g.height, + angle: g.angle, + wrapWidth: g.width, + }); + expect(v).toEqual(expected); + }); +}); + +describe("moveGripOf — Textspalten-Eckpunkte (nur Breite, keine Schriftgrösse)", () => { + it("rechte Ecke ziehen ändert NUR width — `at` bleibt fest", () => { + // Index 1 = oben-rechts (s. textFrameCorners-Reihenfolge). Rahmenbreite + // war 1.5 m ab at.x=0 → Ziehen auf x=2.5 macht daraus 2.5 m. + const v = drawingVertices(textBox); + getState().moveGripOf("d-text-box", null, 1, { x: 2.5, y: v[1].y }); + const g = getState().project.drawings2d.find((d) => d.id === "d-text-box")!.geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.width).toBeCloseTo(2.5, 6); + expect(g.at).toEqual({ x: 0, y: 0 }); + } + }); + + it("linke Ecke ziehen verschiebt `at.x` UND ändert width — die RECHTE Kante bleibt fest", () => { + // Index 0 = oben-links. Rechte Kante liegt bei at.x+width = 0+1.5 = 1.5. + // Linke Ecke von x=0 auf x=-0.5 gezogen → neue Breite 2.0, at.x=-0.5. + const v = drawingVertices(textBox); + getState().moveGripOf("d-text-box", null, 0, { x: -0.5, y: v[0].y }); + const g = getState().project.drawings2d.find((d) => d.id === "d-text-box")!.geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.at.x).toBeCloseTo(-0.5, 6); + expect(g.width).toBeCloseTo(2.0, 6); + // Rechte Kante unverändert bei 1.5. + expect(g.at.x + (g.width ?? 0)).toBeCloseTo(1.5, 6); + } + }); + + it("Breite kann nicht unter die Mindestbreite schrumpfen (kein invertiertes/negatives width)", () => { + const v = drawingVertices(textBox); + getState().moveGripOf("d-text-box", null, 1, { x: -10, y: v[1].y }); // weit über die linke Kante hinaus + const g = getState().project.drawings2d.find((d) => d.id === "d-text-box")!.geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.width).toBeGreaterThan(0); + } + }); + + it("Y-Komponente des Zugs wird ignoriert — nur die lokale Breiten-Richtung zählt (auch bei 90° Rotation)", () => { + // Bei angle=90° zeigt die "Breiten-Richtung" (lokale x-Achse) im + // Modell nach +y. Ziehen der rechten Ecke rein in y-Richtung muss die + // Breite ändern, at aber unverändert lassen. + getState().moveGripOf("d-text-box-rot", null, 1, { x: 5, y: 7.5 }); // 2.5 m "weiter" in lokaler Breiten-Richtung + const g = getState().project.drawings2d.find((d) => d.id === "d-text-box-rot")!.geom; + expect(g.shape).toBe("text"); + if (g.shape === "text") { + expect(g.width).toBeCloseTo(2.5, 6); + expect(g.at).toEqual({ x: 5, y: 5 }); + } + }); +}); diff --git a/src/state/projectSlice.textStyles.test.ts b/src/state/projectSlice.textStyles.test.ts new file mode 100644 index 0000000..9770a47 --- /dev/null +++ b/src/state/projectSlice.textStyles.test.ts @@ -0,0 +1,72 @@ +/** + * Textstil-Bibliothek — Store-Aktionen (`patchTextStyle`/`addTextStyle`/ + * `deleteTextStyle`). Die reine Anwendungslogik (`applyPreset`) ist bereits in + * `text/richText.test.ts` getestet; hier geht es um die CRUD-Verdrahtung im + * Projekt-Store, analog `projectSlice.penSets.test.ts`. `Project.textStyles` + * ist optional (additiv, Fallback `DEFAULT_PRESETS`) — die Aktionen müssen + * daher auch OHNE vorher gesetztes Feld funktionieren (starten dann vom + * Fallback statt von einem leeren Array). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import { DEFAULT_PRESETS } from "../text/richText"; + +beforeEach(() => { + setState({ + project: { ...sampleProject, textStyles: undefined }, + undoStack: [], + redoStack: [], + canUndo: false, + canRedo: false, + }); +}); + +describe("addTextStyle — startet vom Fallback, wenn `textStyles` noch fehlt", () => { + it("legt einen neuen Stil an, seed mit den 4 Default-Presets davor", () => { + getState().addTextStyle(); + const styles = getState().project.textStyles!; + expect(styles.length).toBe(DEFAULT_PRESETS.length + 1); + expect(styles.slice(0, DEFAULT_PRESETS.length)).toEqual(DEFAULT_PRESETS); + expect(styles[styles.length - 1].marks.sizePt).toBe(10); + }); +}); + +describe("patchTextStyle — merged Marks statt zu ersetzen", () => { + it("ändert nur das gepatchte Marks-Feld, lässt die übrigen unverändert", () => { + getState().addTextStyle(); + const id = getState().project.textStyles![DEFAULT_PRESETS.length].id; + getState().patchTextStyle(id, { marks: { bold: true } }); + getState().patchTextStyle(id, { marks: { italic: true } }); + const style = getState().project.textStyles!.find((s) => s.id === id)!; + expect(style.marks.bold).toBe(true); + expect(style.marks.italic).toBe(true); + expect(style.marks.sizePt).toBe(10); // unverändert vom Anlegen + }); + + it("ändert den Namen (label) unabhängig von marks", () => { + getState().addTextStyle(); + const id = getState().project.textStyles![DEFAULT_PRESETS.length].id; + getState().patchTextStyle(id, { label: "Firmenstil" }); + expect(getState().project.textStyles!.find((s) => s.id === id)?.label).toBe("Firmenstil"); + }); +}); + +describe("deleteTextStyle — entfernt genau den einen Stil", () => { + it("löscht einen selbst angelegten Stil, lässt die Default-Presets unberührt", () => { + getState().addTextStyle(); + const id = getState().project.textStyles![DEFAULT_PRESETS.length].id; + getState().deleteTextStyle(id); + const styles = getState().project.textStyles!; + expect(styles.length).toBe(DEFAULT_PRESETS.length); + expect(styles.find((s) => s.id === id)).toBeUndefined(); + }); + + it("kann auch einen der geseedeten Default-Presets löschen (kein Lösch-Schutz — v1 nicht live-verknüpft)", () => { + getState().addTextStyle(); // seedet textStyles zuerst mit DEFAULT_PRESETS + const titleId = getState().project.textStyles!.find((s) => s.id === "title")!.id; + getState().deleteTextStyle(titleId); + expect(getState().project.textStyles!.find((s) => s.id === "title")).toBeUndefined(); + }); +}); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index d0fbdf7..0952b59 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -14,6 +14,7 @@ import { recomputeFloorElevations, } from "../model/types"; import type { + BuiltinPaletteBank, ColorPen, Component, Drawing2D, @@ -37,7 +38,17 @@ import { commitTransform } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; import { centroid as roomCentroid } from "../geometry/roomArea"; -import { bulgeFromSagittaPoint, bulgePointAt } from "../geometry/bulge"; +import { bulgeArc, bulgeBetweenAngles, bulgeFromSagittaPoint, bulgePointAt, pointOnCircle } from "../geometry/bulge"; +import { + DEFAULT_SCALE_DENOMINATOR, + DIM_DEFAULTS_MM, + dimTextOffsetFromPoint, + dimTextPos, + mmToModel, + modelToMm, +} from "../model/dimension"; +import { textFrameCorners } from "../text/textFrame"; +import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText"; import { t } from "../i18n"; import type { StoreApi } from "./store"; import { createHistorySlice, pushHistoryPatch } from "./historySlice"; @@ -49,8 +60,14 @@ export interface ProjectSlice { project: Project; // ── Projekt direkt setzen (für Werkzeuge/Transformationen aus App) ──────── - /** Ersetzt das Projekt (Teil-/Updater wie React-setState). */ - setProject: (next: Project | ((p: Project) => Project)) => void; + /** + * Ersetzt das Projekt (Teil-/Updater wie React-setState). `coalesceKey`: + * NUR für bekannte Hochfrequenz-Aktionen (Griff-Ziehen, Inline-Text-Tippen) + * — verschmilzt aufeinanderfolgende Aufrufe mit demselben Key innerhalb + * `COALESCE_WINDOW_MS` zu EINEM Undo-Schritt, s. Kommentar bei der + * Implementierung unten. + */ + setProject: (next: Project | ((p: Project) => Project), coalesceKey?: string) => void; // ── Zeichnungsebenen (Levels/Geschosse) ────────────────────────────────── toggleLevelVisible: (id: string) => void; @@ -107,6 +124,9 @@ export interface ProjectSlice { deleteLineStyle: (id: string) => void; importLineStyles: (styles: Omit[]) => void; importHatches: (hatches: Omit[]) => void; + patchTextStyle: (id: string, patch: Partial) => void; + addTextStyle: () => void; + deleteTextStyle: (id: string) => void; // ── Stiftsätze (ArchiCAD-Stiftsatz-Muster, s. model/penSets.ts) ─────────── /** Neuer Stift-Platzhalter (Name, keine Farbe) — landet in JEDEM bestehenden Stiftsatz. */ @@ -127,12 +147,50 @@ export interface ProjectSlice { /** Ersetzt `pens`/legt einen neuen Satz mit der 255er-CAD-Standardpalette an (s. `model/penSets.ts`). */ seedStandardPenSet: () => void; + // ── Benutzerdefinierte Farbpaletten (s. model/types.ts::CustomPalette) ──── + addCustomPalette: () => void; + renameCustomPalette: (id: string, name: string) => void; + deleteCustomPalette: (id: string) => void; + /** + * Fügt `hex` VORNE in die Palette ein (zuletzt gespeicherte Farbe zuerst + * sichtbar) — dedupliziert case-insensitive (erneutes Speichern verschiebt + * die Farbe nur nach vorn, statt sie zu duplizieren). `paletteId` + * unbekannt/undefined ⇒ legt automatisch eine neue Palette an (Farbmischer + * kann so "+" drücken, ohne dass vorher zwingend eine Palette existiert). + */ + addColorToCustomPalette: (paletteId: string | undefined, hex: string) => void; + removeColorFromCustomPalette: (paletteId: string, hex: string) => void; + /** Blendet EINE eigene Palette im Farbwahl-Popover ein/aus (Daten bleiben erhalten). */ + setCustomPaletteVisible: (id: string, visible: boolean) => void; + /** Blendet EINE mitgelieferte Bank (Einfach/Tango/Material/RAL) im Popover ein/aus. */ + setBuiltinPaletteVisible: (bank: BuiltinPaletteBank, visible: boolean) => void; + + // ── Polylinien-Stützpunkte (Kontextmenü im Grundriss) ──────────────────── + /** + * Fügt einen Stützpunkt in das Segment `segIndex` (= zwischen `pts[segIndex]` + * und dem Folgepunkt; bei geschlossener Polylinie ist das letzte Segment der + * Schluss zurück zu `pts[0]`) ein. Bei GERADEM Segment landet der Punkt auf + * `pt` (i. d. R. der auf die Sehne projizierte Klickpunkt), bei einem + * BOGEN-Segment stattdessen exakt auf dem Bogenmittelpunkt — und der Bogen + * wird in zwei Teilbögen mit passenden Bulge-Werten zerlegt, sonst würde der + * Bogen beim Einfügen still zu zwei Geraden zusammenfallen. + */ + insertDrawingPoint: (drawingId: string, segIndex: number, pt: Vec2) => void; + /** + * Entfernt den Stützpunkt `index` (samt zugehörigem Bulge-Eintrag). + * Blockiert (mit Hinweis), wenn zu wenige Punkte übrig blieben: offene + * Polylinie braucht ≥2, geschlossene ≥3. + */ + deleteDrawingPoint: (drawingId: string, index: number) => void; + // ── Editier-Griffe + Body-Move des selektierten Elements ────────────────── moveGripOf: ( drawingId: string | null, wallId: string | null, index: number, pt: Vec2, + /** Papier-Massstab (1:N), nur für den Masszahl-Griff der Bemassung. */ + scaleDenominator?: number, ) => void; moveElementByOf: ( drawingId: string | null, @@ -242,8 +300,18 @@ export interface ProjectSlice { ) => void; // ── Wand-Attribute (Object-Info-Panel) ──────────────────────────────────── - /** Generischer immutabler Patch auf eine Wand (per ID). */ - updateWall: (id: string, patch: Partial) => void; + /** + * Generischer immutabler Patch auf eine Wand (per ID). `coalesceKey` + * optional (Default: kein Coalescing, jeder Aufruf ein eigener Undo- + * Schritt — Panel-Feld-Edits) — der 3D-Höhen-Griff (`App.tsx:: + * onEdit3dWallTop`) übergibt einen festen Schlüssel je Wand, damit EIN + * Drag (viele Maus-Move-Schritte) EINEN Undo-Schritt erzeugt statt vieler. + */ + updateWall: ( + id: string, + patch: Partial, + coalesceKey?: string, + ) => void; /** * Setzt die Gesamtdicke einer EINSCHICHTIGEN Wand. Ansatz: editiert die * Schichtdicke des Wandtyps. Ist der Wandtyp mehrschichtig oder von mehr als @@ -280,10 +348,15 @@ export interface ProjectSlice { patch: Partial, ) => void; - /** Immutable Änderung eines Dachs (Form/Neigung/Überstand/Firstrichtung/Dicke). */ + /** + * Immutable Änderung eines Dachs (Form/Neigung/Überstand/Firstrichtung/ + * Dicke). `coalesceKey` optional — s. `updateWall`-Doc (derselbe Zweck, + * hier vom 3D-First-Griff `App.tsx::onEdit3dRoofPitch` genutzt). + */ updateRoof: ( id: string, patch: Partial, + coalesceKey?: string, ) => void; /** Dach-Eckgriff (3D): Umriss-Ecke `index` auf `pt`, Gegenecke fix (Rechteck). */ moveRoofGrip: (roofId: string, index: number, pt: import("../model/types").Vec2) => void; @@ -804,6 +877,30 @@ export function createProjectSlice( ], })), + patchTextStyle: (id, patch) => + setProject((p) => ({ + ...p, + textStyles: (p.textStyles ?? DEFAULT_PRESETS).map((s) => + s.id === id ? { ...s, ...patch, marks: { ...s.marks, ...patch.marks } } : s, + ), + })), + + addTextStyle: () => + setProject((p) => { + const style: TextStylePreset = { + id: `ts-${Date.now()}`, + label: t("default.textStyleName"), + marks: { sizePt: 10 }, + }; + return { ...p, textStyles: [...(p.textStyles ?? DEFAULT_PRESETS), style] }; + }), + + deleteTextStyle: (id) => + setProject((p) => ({ + ...p, + textStyles: (p.textStyles ?? DEFAULT_PRESETS).filter((s) => s.id !== id), + })), + importHatches: (hatches) => setProject((p) => ({ ...p, @@ -944,13 +1041,124 @@ export function createProjectSlice( seedStandardPenSet: () => setProject((p) => buildStandardPenSet(p)), + addCustomPalette: () => + setProject((p) => ({ + ...p, + customPalettes: [ + ...(p.customPalettes ?? []), + { id: `palette-${Date.now()}`, name: t("default.customPaletteName"), colors: [] }, + ], + })), + + renameCustomPalette: (id, name) => + setProject((p) => ({ + ...p, + customPalettes: p.customPalettes?.map((c) => (c.id === id ? { ...c, name } : c)), + })), + + deleteCustomPalette: (id) => + setProject((p) => ({ + ...p, + customPalettes: p.customPalettes?.filter((c) => c.id !== id), + })), + + addColorToCustomPalette: (paletteId, hex) => + setProject((p) => { + const palettes = p.customPalettes ?? []; + const target = palettes.find((c) => c.id === paletteId); + if (!target) { + const created = { id: `palette-${Date.now()}`, name: t("default.customPaletteName"), colors: [hex] }; + return { ...p, customPalettes: [...palettes, created] }; + } + const withoutDupe = target.colors.filter((c) => c.toLowerCase() !== hex.toLowerCase()); + const updated = { ...target, colors: [hex, ...withoutDupe] }; + return { ...p, customPalettes: palettes.map((c) => (c.id === target.id ? updated : c)) }; + }), + + removeColorFromCustomPalette: (paletteId, hex) => + setProject((p) => ({ + ...p, + customPalettes: p.customPalettes?.map((c) => + c.id === paletteId ? { ...c, colors: c.colors.filter((h) => h.toLowerCase() !== hex.toLowerCase()) } : c, + ), + })), + + setCustomPaletteVisible: (id, visible) => + setProject((p) => ({ + ...p, + customPalettes: p.customPalettes?.map((c) => (c.id === id ? { ...c, visible } : c)), + })), + + setBuiltinPaletteVisible: (bank, visible) => + setProject((p) => ({ + ...p, + builtinPaletteBanks: { ...p.builtinPaletteBanks, [bank]: visible }, + })), + + insertDrawingPoint: (drawingId, segIndex, pt) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => { + if (d.id !== drawingId || d.geom.shape !== "polyline") return d; + const g = d.geom; + const n = g.pts.length; + const last = segIndex === n - 1; + if (segIndex < 0 || segIndex >= n || (last && !g.closed)) return d; + const a = g.pts[segIndex]; + const b = last ? g.pts[0] : g.pts[segIndex + 1]; + // Bogen: exakt über die Kreisgeometrie in der Winkel-Mitte teilen — + // dieselbe Technik, mit der kernel2d Bogen-Segmente zuschneidet + // (`bulgeBetweenAngles`). Eine Näherung über tessellierte Punkte + // (`bulgePointAt`) wäre hier zu ungenau, weil sie auf Stützstellen + // rundet und der Sagitta-Rückschluss den Fehler verstärkt. + const arc = bulgeArc(a, b, g.bulge?.[segIndex] ?? 0); + const aMid = arc ? arc.a0 + arc.sweep / 2 : 0; + const insertPt = arc ? pointOnCircle(arc.center, arc.r, aMid) : pt; + const sweepSign: 1 | -1 = arc && arc.sweep < 0 ? -1 : 1; + const b1 = arc ? bulgeBetweenAngles(arc.center, arc.r, arc.a0, aMid, sweepSign) : 0; + const b2 = arc ? bulgeBetweenAngles(arc.center, arc.r, aMid, arc.a1, sweepSign) : 0; + const pts = [...g.pts.slice(0, segIndex + 1), insertPt, ...g.pts.slice(segIndex + 1)]; + // Bulge-Array nur mitführen, wenn es eines gab (additiv bleiben). + const nextBulge = g.bulge + ? [...g.bulge.slice(0, segIndex), b1, b2, ...g.bulge.slice(segIndex + 1)] + : undefined; + return { ...d, geom: { ...g, pts, ...(nextBulge ? { bulge: nextBulge } : {}) } }; + }), + })), + + deleteDrawingPoint: (drawingId, index) => + setProject((p) => { + const d = p.drawings2d.find((x) => x.id === drawingId); + if (!d || d.geom.shape !== "polyline") return p; + const g = d.geom; + const min = g.closed ? 4 : 3; + if (g.pts.length < min) { + get().notify(t("alert.polylineMinPoints"), "warning"); + return p; + } + if (index < 0 || index >= g.pts.length) return p; + const pts = g.pts.filter((_, i) => i !== index); + // Zwei Segmente werden zu einem: der Bulge des ENTFERNTEN Segments + // fällt weg, das verbleibende behält seinen Wert (die exakte + // Bogenform lässt sich nicht erhalten, wenn ihr Stützpunkt entfällt). + const bulge = g.bulge ? g.bulge.filter((_, i) => i !== index) : undefined; + return { + ...p, + drawings2d: p.drawings2d.map((x) => + x.id === drawingId + ? { ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } } + : x, + ), + }; + }), + // ── Editier-Griffe ───────────────────────────────────────────────────── // Diese Aktionen laufen AD-HOC bei jedem Maus-Move-Schritt eines Drags // (kein Draft/Commit-Muster wie bei den Zeichenwerkzeugen) — daher mit // coalesceKey, damit EIN Drag EINEN Undo-Schritt erzeugt statt vieler. - moveGripOf: (drawingId, wallId, index, pt) => + moveGripOf: (drawingId, wallId, index, pt, scaleDenominator) => setProject( - (p) => moveGrip(p, drawingId, wallId, index, pt), + (p) => moveGrip(p, drawingId, wallId, index, pt, scaleDenominator), `moveGripOf:${drawingId ?? ""}:${wallId ?? ""}:${index}`, ), @@ -1055,11 +1263,14 @@ export function createProjectSlice( setProject((p) => commitTransform(p, sel, op, points, copyMode, count)), // ── Wand-Attribute ───────────────────────────────────────────────────── - updateWall: (id, patch) => - setProject((p) => ({ - ...p, - walls: p.walls.map((w) => (w.id === id ? { ...w, ...patch } : w)), - })), + updateWall: (id, patch, coalesceKey) => + setProject( + (p) => ({ + ...p, + walls: p.walls.map((w) => (w.id === id ? { ...w, ...patch } : w)), + }), + coalesceKey, + ), setWallThickness: (wallId, thickness) => setProject((p) => setWallThickness(p, wallId, thickness)), @@ -1108,11 +1319,14 @@ export function createProjectSlice( })), // ── Dach-Editieren ───────────────────────────────────────────────────── - updateRoof: (id, patch) => - setProject((p) => ({ - ...p, - roofs: (p.roofs ?? []).map((r) => (r.id === id ? { ...r, ...patch } : r)), - })), + updateRoof: (id, patch, coalesceKey) => + setProject( + (p) => ({ + ...p, + roofs: (p.roofs ?? []).map((r) => (r.id === id ? { ...r, ...patch } : r)), + }), + coalesceKey, + ), // Dach-Eckgriff (3D): der gezogene Umriss-Eckpunkt `index` wandert auf `pt`; // die GEGENÜBERLIEGENDE Ecke bleibt fix → der Umriss bleibt ein achsparalleles @@ -1580,7 +1794,8 @@ function resizeGeom( ): import("../model/types").Drawing2DGeom { switch (g.shape) { case "line": - case "xline": { + case "xline": + case "ray": { const { ax, ay, sx, sy } = scaleAround(bbox2([g.a, g.b]), w, h, anchor); const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); return { ...g, a: f(g.a), b: f(g.b) }; @@ -1702,9 +1917,14 @@ function ellipseOrCircle( * arc: Start-/End-Winkel-Griff (Index 0/1, ändern a0/a1) + ein Radius-Griff * auf halbem Bogen (Index 2, ändert r) — siehe {@link moveGrip}. */ -export function drawingVertices(d: import("../model/types").Drawing2D): Vec2[] { +export function drawingVertices( + d: import("../model/types").Drawing2D, + /** Papier-Massstab (1:N) — nur für die Bemassungs-Griffe, deren Lage von + * der in Papier-mm angegebenen Schrifthöhe abhängt. */ + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, +): Vec2[] { const g = d.geom; - if (g.shape === "line" || g.shape === "xline") return [g.a, g.b]; + if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") return [g.a, g.b]; // Polylinie: Eckpunkt-Griffe (Index 0..n-1) PLUS ein Bulge-Griff je Segment // (Index n..; Apex des aktuellen Bogens, oder Sehnen-Mitte bei bulge=0) — // senkrecht zur Sehne ziehen krümmt genau dieses Segment (s. moveGrip). @@ -1767,17 +1987,59 @@ export function drawingVertices(d: import("../model/types").Drawing2D): Vec2[] { const len = Math.hypot(dx, dy) || 1; const nx = (-dy / len) * g.offset, ny = (dx / len) * g.offset; const mid: Vec2 = { x: (a.x + b.x) / 2 + nx, y: (a.y + b.y) / 2 + ny }; - return [...g.pts, mid]; + // Reihenfolge: Kettenpunkte · Offset-Griff · JE SEGMENT ein Masszahl-Griff + // (verschiebt nur die Zahl, s. moveGrip) — dieselbe Ordnung erwartet + // moveGrip beim Auflösen des Index. + const heightM = mmToModel(g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight, scaleDenominator); + const textGrips = g.pts.slice(0, -1).map((p0, i) => { + const off = g.textOffsetsMm?.[i]; + return dimTextPos( + p0, + g.pts[i + 1], + g.offset, + heightM, + off + ? { along: mmToModel(off.along, scaleDenominator), perp: mmToModel(off.perp, scaleDenominator) } + : undefined, + ); + }); + return [...g.pts, mid, ...textGrips]; } // Kote: EIN Griff an der Dreieck-Spitze (zum Verschieben; siehe moveGrip). if (g.shape === "kote") return [g.at]; - // Text: Griff 0 am Ankerpunkt; trägt der Text einen Leader, zusätzlich Griff - // 1 an dessen Zielpunkt (Pfeilspitze unabhängig verschiebbar; s. moveGrip). + // Detail-/Schnitt-Verweis: EIN Griff am Kreis-Zentrum (zum Verschieben). + if (g.shape === "detailref") return [g.at]; + // Massstabsbalken: EIN Griff an der linken unteren Ecke (zum Verschieben). + if (g.shape === "scalebar") return [g.at]; + // Punkt-/Knotenmarker: EIN Griff am Zentrum (zum Verschieben). + if (g.shape === "pointmarker") return [g.at]; + // Text: Griff 0 am Ankerpunkt; trägt der Text einen Leader, zusätzlich ein + // Griff je Knickpunkt (`leaderBendPoints`, falls gesetzt) und ein + // ABSCHLIESSENDER Griff an der Spitze (Pfeilspitze unabhängig verschiebbar; + // s. moveGrip) — Reihenfolge Anker→Knicke→Spitze, wie der Pfad gerendert wird. // Text-entlang-Pfad: die Pfadpunkte SELBST sind die Griffe (wie polyline), // ersetzt das Anker/Leader-Griffmodell komplett (schliessen sich aus). + // Textspalte (`width` gesetzt, kein Leader/Pfad): VIER Rahmen-Eckpunkte als + // Griffe (Nutzer-Wunsch: "nicht nur ein Griff unten links bei der ersten + // Glyphe") — Ziehen ändert NUR die Spaltenbreite (InDesign-Verhalten, + // Nutzer-Entscheidung), s. `moveGrip`. Dieselbe Rahmen-Berechnung wie der + // Auswahl-Rahmen im Grundriss (`text/textFrame.ts`), damit Griffe und + // sichtbarer Rahmen immer übereinstimmen. if (g.shape === "text") { if (g.pathPts) return [...g.pathPts]; - return g.leaderTarget ? [g.at, g.leaderTarget] : [g.at]; + if (g.leaderTarget) return [g.at, ...(g.leaderBendPoints ?? []), g.leaderTarget]; + if (g.width && g.width > 0) { + return textFrameCorners({ + at: g.at, + text: g.text, + heightM: g.height, + angle: g.angle, + marks: g.marks, + doc: g.doc, + wrapWidth: g.width, + }); + } + return [g.at]; } // Block-Instanz: EIN Griff am Einfügepunkt (Rotation läuft über move/mirror, // kein eigener Rotations-Griff in v1; s. moveGrip). @@ -1827,14 +2089,20 @@ function moveGrip( wallId: string | null, index: number, pt: Vec2, + /** Papier-Massstab (1:N) — nur für den Masszahl-Griff, s. `drawingVertices`. */ + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, ): Project { + // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht + // ziehen (s. Kommentar bei `onPlanSelect` in useMouseSelectionHandlers.ts). + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; if (drawingId) { return { ...project, drawings2d: project.drawings2d.map((d) => { if (d.id !== drawingId) return d; const g = d.geom; - if (g.shape === "line" || g.shape === "xline") { + if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { return { ...d, geom: index === 0 ? { ...g, a: pt } : { ...g, b: pt } }; } if (g.shape === "polyline") { @@ -1867,12 +2135,30 @@ function moveGrip( const pts = g.pts.map((p, i) => (i === index ? pt : p)); return { ...d, geom: { ...g, pts } }; } - const a = g.pts[0], b = g.pts[g.pts.length - 1]; - const dx = b.x - a.x, dy = b.y - a.y; - const len = Math.hypot(dx, dy) || 1; - const nx = -dy / len, ny = dx / len; - const offset = (pt.x - a.x) * nx + (pt.y - a.y) * ny; - return { ...d, geom: { ...g, offset } }; + if (index === g.pts.length) { + const a = g.pts[0], b = g.pts[g.pts.length - 1]; + const dx = b.x - a.x, dy = b.y - a.y; + const len = Math.hypot(dx, dy) || 1; + const nx = -dy / len, ny = dx / len; + const offset = (pt.x - a.x) * nx + (pt.y - a.y) * ny; + return { ...d, geom: { ...g, offset } }; + } + // Masszahl-Griff: verschiebt NUR die Zahl des betroffenen Segments + // (Geometrie bleibt unangetastet) und rastet nahe der Standardlage + // ein, s. `model/dimension.ts::dimTextOffsetFromPoint`. + const seg = index - g.pts.length - 1; + if (seg < 0 || seg >= g.pts.length - 1) return d; + const height = mmToModel(g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight, scaleDenominator); + const m = dimTextOffsetFromPoint(g.pts[seg], g.pts[seg + 1], g.offset, height, pt); + // Zurück in Papier-mm speichern (Einheit des Modells). + const next = { + along: modelToMm(m.along, scaleDenominator), + perp: modelToMm(m.perp, scaleDenominator), + }; + const textOffsetsMm = Array.from({ length: g.pts.length - 1 }, (_, i) => + i === seg ? next : (g.textOffsetsMm?.[i] ?? { along: 0, perp: 0 }), + ); + return { ...d, geom: { ...g, textOffsetsMm } }; } if (g.shape === "rect" || g.shape === "image") { const corners = [ @@ -1886,19 +2172,63 @@ function moveGrip( const max = { x: Math.max(pt.x, opp.x), y: Math.max(pt.y, opp.y) }; return { ...d, geom: { ...g, min, max } }; } - // Text: Griff 0 = Ankerpunkt; Griff 1 (nur bei Leader) = Zielpunkt; - // trägt der Text einen Pfad, adressiert der Index einen Pfadpunkt. + // Text: Griff 0 = Ankerpunkt; bei Leader zusätzlich ein Griff je + // Knickpunkt UND ein ABSCHLIESSENDER Griff am Zielpunkt (Reihenfolge + // wie `drawingVertices`: Anker→Knicke→Spitze); trägt der Text einen + // Pfad, adressiert der Index einen Pfadpunkt; Textspalte (kein + // Leader/Pfad, `width` gesetzt) hat 4 Rahmen-Eck-Griffe (s. + // drawingVertices) — dieselbe Reihenfolge (pathPts > leaderTarget > + // Breiten-Ecken > einzelner Anker) MUSS hier gespiegelt werden, sonst + // adressiert ein Griff-Index das falsche Verhalten. if (g.shape === "text") { if (g.pathPts) { const pathPts = g.pathPts.map((pp, i) => (i === index ? pt : pp)); return { ...d, geom: { ...g, pathPts } }; } - return index === 1 && g.leaderTarget - ? { ...d, geom: { ...g, leaderTarget: pt } } - : { ...d, geom: { ...g, at: pt } }; + if (g.leaderTarget) { + const bends = g.leaderBendPoints ?? []; + const tipIndex = bends.length + 1; + if (index === 0) return { ...d, geom: { ...g, at: pt } }; + if (index === tipIndex) return { ...d, geom: { ...g, leaderTarget: pt } }; + if (index > 0 && index < tipIndex) { + const leaderBendPoints = bends.map((bp, i) => (i === index - 1 ? pt : bp)); + return { ...d, geom: { ...g, leaderBendPoints } }; + } + return d; + } + if (g.width && g.width > 0 && index >= 0 && index < 4) { + // Nur die Breite ändert sich (InDesign-Textrahmen-Verhalten, + // Nutzer-Entscheidung) — Höhe bleibt inhaltsgetrieben. Ziehen wird + // auf die LOKALE x-Achse projiziert (rotationsfest): linke Ecken + // (Index 0/3, s. textFrameCorners-Reihenfolge oben-links/oben- + // rechts/unten-rechts/unten-links) verschieben zusätzlich `at`, + // damit die RECHTE Kante fest bleibt; rechte Ecken (1/2) lassen + // `at`/die linke Kante fest. + const cos = Math.cos(g.angle); + const sin = Math.sin(g.angle); + const dx = pt.x - g.at.x; + const dy = pt.y - g.at.y; + const localX = dx * cos + dy * sin; + const MIN_WIDTH = 0.1; + const isLeft = index === 0 || index === 3; + if (isLeft) { + const width = Math.max(MIN_WIDTH, g.width - localX); + const at = { x: g.at.x + localX * cos, y: g.at.y + localX * sin }; + return { ...d, geom: { ...g, at, width } }; + } + const width = Math.max(MIN_WIDTH, localX); + return { ...d, geom: { ...g, width } }; + } + return { ...d, geom: { ...g, at: pt } }; } // Kote: der einzige Griff (Index 0) sitzt an der Dreieck-Spitze. if (g.shape === "kote") return { ...d, geom: { ...g, at: pt } }; + // Detail-/Schnitt-Verweis: der einzige Griff (Index 0) sitzt am Kreis-Zentrum. + if (g.shape === "detailref") return { ...d, geom: { ...g, at: pt } }; + // Massstabsbalken: der einzige Griff (Index 0) sitzt an der linken unteren Ecke. + if (g.shape === "scalebar") return { ...d, geom: { ...g, at: pt } }; + // Punkt-/Knotenmarker: der einzige Griff (Index 0) sitzt am Zentrum. + if (g.shape === "pointmarker") return { ...d, geom: { ...g, at: pt } }; // Block-Instanz: der einzige Griff (Index 0) sitzt am Einfügepunkt. if (g.shape === "block") return { ...d, geom: { ...g, at: pt } }; // Kreis: Griff 0 (Ost) bzw. 1 (Nord) — zieht man die beiden Achsen @@ -1958,6 +2288,9 @@ function moveElementBy( wallId: string | null, delta: Vec2, ): Project { + // Objekt-Sperre: s. Kommentar in `moveGrip` oben. + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { return { @@ -1983,6 +2316,12 @@ function moveElementBy( return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "kote": return { ...d, geom: { ...g, at: mv(g.at) } }; + case "detailref": + return { ...d, geom: { ...g, at: mv(g.at) } }; + case "scalebar": + return { ...d, geom: { ...g, at: mv(g.at) } }; + case "pointmarker": + return { ...d, geom: { ...g, at: mv(g.at) } }; case "text": return { ...d, geom: { ...g, at: mv(g.at) } }; default: @@ -2104,6 +2443,9 @@ function moveEdge( bIndex: number, delta: Vec2, ): Project { + // Objekt-Sperre: s. Kommentar in `moveGrip` oben. + if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return project; + if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return project; const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); if (drawingId) { return { diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index 9374817..17c429c 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -43,6 +43,7 @@ import type { Wall, WallReferenceLine, } from "../model/types"; +import type { DetailLevel } from "../ui/TopBar"; import { localToLv95 } from "../io/lv95"; import { resolveForeground, @@ -239,6 +240,8 @@ export interface OpeningInfo { lintelLines?: "keine" | "innen" | "aussen" | "beide"; /** Zugewiesener Tür-/Fenstertyp (Bibliothek, `Opening.typeId`) oder undefined. */ typeId?: string; + /** Per-Element-Übersteuerung der Detailstufe; fehlt → Ansichts-Detailstufe gilt. */ + detailLevel?: DetailLevel; /** Aufgelöste absolute UK/OK (Meter). */ zBottom: number; zTop: number; @@ -489,6 +492,23 @@ export interface Selection { column?: ColumnInfo; /** Kontext-Objekt-Attribute (nur bei `kind === "contextObject"`). */ contextObject?: ContextObjectInfo; + /** + * Detail-/Schnitt-Verweis-Attribute (nur bei `kind === "drawing2d"` mit + * `geom.shape === "detailref"`). + */ + detailRef?: DetailRefInfo; +} + +/** + * Detail-/Schnitt-Verweis-Attribute (Drawing2D `{shape:"detailref"}`) fürs + * Object-Info-/Attribute-Panel: Bezeichner + Blattverknüpfung (samt der + * verfügbaren Blätter für das Auswahl-Dropdown). + */ +export interface DetailRefInfo { + label: string; + sheetLayoutId?: string; + sheetLabel?: string; + availableLayouts: { id: string; name: string }[]; } /** @@ -526,8 +546,12 @@ function isClosedGeom(g: Drawing2DGeom): boolean { ); } -/** Bounding-Box einer 2D-Form. */ -function geomBBox(g: Drawing2DGeom): SelectionBBox { +/** + * Bounding-Box einer 2D-Form. Exportiert, weil auch die Editier-Werkzeuge sie + * brauchen (Ausrichten/Verteilen, `editors/align.ts`) — dieselbe Herleitung + * wie fürs Attribut-Panel, damit beide Seiten nie auseinanderlaufen. + */ +export function geomBBox(g: Drawing2DGeom): SelectionBBox { let minX = Infinity, minY = Infinity, maxX = -Infinity, @@ -541,6 +565,7 @@ function geomBBox(g: Drawing2DGeom): SelectionBBox { switch (g.shape) { case "line": case "xline": + case "ray": acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); break; @@ -585,8 +610,14 @@ function geomBBox(g: Drawing2DGeom): SelectionBBox { case "kote": case "text": case "block": + case "detailref": + case "pointmarker": acc(g.at.x, g.at.y); break; + case "scalebar": + acc(g.at.x, g.at.y); + acc(g.at.x + g.segmentLength * g.segments, g.at.y); + break; } if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; return { minX, minY, maxX, maxY }; @@ -882,6 +913,7 @@ function openingSelection(project: Project, o: Opening): Selection { doorType: o.doorType, lintelLines: o.lintelLines, typeId: o.typeId, + detailLevel: o.detailLevel, zBottom: ext.zBottom, zTop: ext.zTop, frameLine: o.frameLine, @@ -1215,8 +1247,19 @@ function drawingSelection(project: Project, d: Drawing2D): Selection { hatchSource: closed ? d.hatchSource : undefined, closed, isImage: d.geom.shape === "image", - opacity: d.geom.shape === "image" ? d.geom.opacity ?? 1 : undefined, + // Deckkraft: beim BILD die eigene Bild-Deckkraft, sonst die + // Objekt-Transparenz des Elements (`Drawing2D.opacity`). + opacity: d.geom.shape === "image" ? (d.geom.opacity ?? 1) : d.opacity, bbox: geomBBox(d.geom), + detailRef: + d.geom.shape === "detailref" + ? { + label: d.geom.label, + sheetLayoutId: d.geom.sheetLayoutId, + sheetLabel: d.geom.sheetLabel, + availableLayouts: (project.layouts ?? []).map((l) => ({ id: l.id, name: l.name })), + } + : undefined, }; } diff --git a/src/state/useExportHandlers.ts b/src/state/useExportHandlers.ts index f33f881..eea233d 100644 --- a/src/state/useExportHandlers.ts +++ b/src/state/useExportHandlers.ts @@ -10,11 +10,14 @@ import type { CategoryDisplayResolver } from "../plan/generatePlan"; import type { DetailLevel } from "../ui/TopBar"; import type { DisplayResolver } from "../viewport/Viewport3D"; import { savePlanPdf } from "../export/exportPdf"; +import { savePlanSvg } from "../export/exportSvg"; import { savePlanDxf } from "../export/exportDxf"; import type { ExportPdfDecision } from "../ui/ExportPdfDialog"; import type { ExportDxfDecision } from "../ui/ExportDxfDialog"; import { projectToWorldCoords } from "../model/geoRebase"; import type { Project } from "../model/types"; +import { filterProjectToSelection } from "./exportScope"; +import type { GroupMembership } from "./groupActions"; export function useExportHandlers(opts: { project: Project; @@ -25,10 +28,13 @@ export function useExportHandlers(opts: { detail: DetailLevel; referenceLines: boolean; planColorMode: "color" | "mono"; + /** Aktuelle Auswahl (alle Arten) — für den „nur Auswahl exportieren"-Scope. */ + selectionMembers: Partial; setExportOpen: (open: boolean) => void; setExportDxfOpen: (open: boolean) => void; }): { onExportPdf: (decision: ExportPdfDecision) => Promise; + onExportSvg: (decision: ExportPdfDecision) => void; onExportDxf: (decision: ExportDxfDecision) => void; } { const { @@ -40,19 +46,26 @@ export function useExportHandlers(opts: { detail, referenceLines, planColorMode, + selectionMembers, setExportOpen, setExportDxfOpen, } = opts; + const scopedProject = (selectionOnly: boolean): Project => + selectionOnly ? filterProjectToSelection(project, selectionMembers) : project; + const onExportPdf = async (decision: ExportPdfDecision) => { const plan = generatePlan( - project, + scopedProject(decision.selectionOnly), activeLevelId, visibleCodes, categoryDisplay, detail, referenceLines, planColorMode === "mono", + true, // includeGlobal (Default, explizit weil forPrint danach folgt) + undefined, // scaleDenominator (Default — der ECHTE Export-Massstab wirkt separat in savePlanPdf) + true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen ); await savePlanPdf(plan, { scaleDenominator: decision.scaleDenominator, @@ -65,6 +78,31 @@ export function useExportHandlers(opts: { setExportOpen(false); }; + // SVG-Export: dieselbe Plan-Erzeugung + denselben Massstab/Papier/ + // Ausrichtung wie der PDF-Export (Nutzer-Wunsch „Kein SVG-Export"), nur + // ohne den jsPDF/svg2pdf-Umweg — reiner Download des Druck-SVG. + const onExportSvg = (decision: ExportPdfDecision) => { + const plan = generatePlan( + scopedProject(decision.selectionOnly), + activeLevelId, + visibleCodes, + categoryDisplay, + detail, + referenceLines, + planColorMode === "mono", + true, // includeGlobal (Default) + undefined, // scaleDenominator (Default) + true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen + ); + savePlanSvg(plan, { + scaleDenominator: decision.scaleDenominator, + paper: decision.paper, + orientation: decision.orientation, + fileName: `${project.name}-${activeLevelName}`, + }); + setExportOpen(false); + }; + // DXF-Export: erzeugt den Plan mit EXAKT denselben Eingaben wie die Ansicht und // schreibt ihn als Modell-Space-DXF in echten Metern (1:1). Layer aus den // Kategorie-Ebenen; jede Entity auf ihrem Kategorie-Layer. @@ -74,7 +112,7 @@ export function useExportHandlers(opts: { // damit die Datei in anderer CAD-Software lagerichtig ankommt — auch wenn // lokal nahe (0,0) gezeichnet wurde. Ohne Bezug bleibt alles lokal. // (Der Papier-/Layout-Export bleibt bewusst in lokalen Koordinaten.) - const exportProject = projectToWorldCoords(project); + const exportProject = projectToWorldCoords(scopedProject(decision.selectionOnly)); const plan = generatePlan( exportProject, activeLevelId, @@ -83,6 +121,9 @@ export function useExportHandlers(opts: { detail, referenceLines, planColorMode === "mono", + true, // includeGlobal (Default) + undefined, // scaleDenominator (Default) + true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen ); savePlanDxf(plan, exportProject, { title: activeLevelName, @@ -92,5 +133,5 @@ export function useExportHandlers(opts: { setExportDxfOpen(false); }; - return { onExportPdf, onExportDxf }; + return { onExportPdf, onExportSvg, onExportDxf }; } diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 6363292..2be193c 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -38,6 +38,8 @@ export function useGripEditing(opts: { selectedDrawingIds: string[]; levelId: string; visibleCodes: Set; + /** Papier-Massstab (1:N) — die Bemassungs-Griffe hängen daran (Papier-mm). */ + scaleDenominator: number; snap: SnapSettings; setDraft: (draft: ToolDraft | null) => void; snapFor: (raw: Vec2, pxPerMeter: number, mods: ToolMods) => SnapResult | null; @@ -47,7 +49,13 @@ export function useGripEditing(opts: { moveStairBy: (id: string, delta: Vec2) => void; moveRoomGrip: (id: string, index: number, pt: Vec2) => void; moveCeilingGrip: (id: string, index: number, pt: Vec2) => void; - moveGripOf: (drawingId: string | null, wallId: string | null, index: number, pt: Vec2) => void; + moveGripOf: ( + drawingId: string | null, + wallId: string | null, + index: number, + pt: Vec2, + scaleDenominator?: number, + ) => void; moveRoomEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void; moveCeilingEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void; moveEdgeOf: ( @@ -76,6 +84,7 @@ export function useGripEditing(opts: { selectedDrawingIds, levelId, visibleCodes, + scaleDenominator, snap, setDraft, snapFor, @@ -191,7 +200,7 @@ export function useGripEditing(opts: { }; for (const id of effectiveDrawingIds) { const d = project.drawings2d.find((x) => x.id === id); - if (d) pushGroup(drawingVertices(d), { drawingId: id }); + if (d) pushGroup(drawingVertices(d, scaleDenominator), { drawingId: id }); } if (effectiveDrawingIds.length === 0) { for (const id of selectedWallIds) { @@ -304,7 +313,7 @@ export function useGripEditing(opts: { for (const id of effectiveDrawingIds) { const d = project.drawings2d.find((x) => x.id === id); if (!d) continue; - const verts = drawingVertices(d); + const verts = drawingVertices(d, scaleDenominator); const g = d.geom; const owner = { drawingId: id }; if (g.shape === "rect" || g.shape === "image") out.push(...ringEdges(verts, owner)); @@ -350,7 +359,7 @@ export function useGripEditing(opts: { const elementCorners = (drawingId: string | null, wallId: string | null): Vec2[] => { if (drawingId) { const d = project.drawings2d.find((x) => x.id === drawingId); - return d ? drawingVertices(d) : []; + return d ? drawingVertices(d, scaleDenominator) : []; } if (wallId) { const w = project.walls.find((x) => x.id === wallId); @@ -388,7 +397,7 @@ export function useGripEditing(opts: { if (id === selfDrawingId) continue; const d = project.drawings2d.find((x) => x.id === id); if (!d) continue; - drawingVertices(d).forEach((v, i) => { + drawingVertices(d, scaleDenominator).forEach((v, i) => { if (near(corner, v)) add2(id, null, i, v); }); } @@ -789,7 +798,13 @@ export function useGripEditing(opts: { // Mehrfachauswahl: welchem Element dieser Griff gehört, kommt aus // `gripOwners` (nicht mehr aus den singulären selectedDrawingId/-WallId). const owner = gripOwners[index]; - moveGripOf(owner?.drawingId ?? selectedDrawingId, owner?.wallId ?? selectedWallId, owner?.localIndex ?? index, pt); + moveGripOf( + owner?.drawingId ?? selectedDrawingId, + owner?.wallId ?? selectedWallId, + owner?.localIndex ?? index, + pt, + scaleDenominator, + ); } }; const applyEdge = (edge: EdgeGrip, delta: Vec2) => { @@ -973,7 +988,7 @@ export function useGripEditing(opts: { } for (const c of moveCoincidentRef.current) { c.pos = { x: c.pos.x + delta.x, y: c.pos.y + delta.y }; - moveGripOf(c.drawingId, c.wallId, c.index, c.pos); + moveGripOf(c.drawingId, c.wallId, c.index, c.pos, scaleDenominator); } }, // Kanten-Griff ziehen. Zwei Verhalten (Zielpunkt jeweils ABSOLUT relativ diff --git a/src/state/useKeyboardShortcuts.ts b/src/state/useKeyboardShortcuts.ts index d2b1fac..5f4c12d 100644 --- a/src/state/useKeyboardShortcuts.ts +++ b/src/state/useKeyboardShortcuts.ts @@ -28,6 +28,8 @@ import { pasteElementClipboard, } from "../editors/elementClipboard"; import type { ElementClipboard, ElementSelectionIds } from "../editors/elementClipboard"; +import { parseClipboardText, serializeClipboardText } from "../editors/elementClipboardSerialize"; +import { matchesShortcut, type ShortcutId, type ShortcutOverrides } from "./keyboardShortcuts"; /** Aktive Transformation (Bewegen/Spiegeln/Drehen) — Form aus useDrawingToolState. */ type ActiveTransform = { @@ -42,21 +44,39 @@ const isEditableTarget = (e: KeyboardEvent): boolean => { return !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable); }; -/** Globaler Undo/Redo-Shortcut: Ctrl+Z / Cmd+Z, Ctrl+Shift+Z / Cmd+Shift+Z bzw. Ctrl+Y für redo. */ -export function useUndoRedoShortcut(undo: () => void, redo: () => void): void { +/** + * Globaler Undo/Redo-Shortcut: rebindbare Haupt-Kombination (Default Ctrl/ + * Cmd+Z bzw. Ctrl/Cmd+Shift+Z, s. `state/keyboardShortcuts.ts::SHORTCUT_DEFS`) + * + fest verdrahtete Ctrl/Cmd+Y-Zusatzbelegung für Redo (Excel/Windows- + * Konvention, bleibt IMMER aktiv, unabhängig von einer Übersteuerung). + */ +export function useUndoRedoShortcut( + undo: () => void, + redo: () => void, + overrides: ShortcutOverrides, +): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { - const mod = e.ctrlKey || e.metaKey; - const key = e.key.toLowerCase(); - if (!mod || (key !== "z" && key !== "y")) return; if (isEditableTarget(e)) return; - e.preventDefault(); - if (key === "y" || (key === "z" && e.shiftKey)) redo(); - else undo(); + if (matchesShortcut(e, "redo", overrides)) { + e.preventDefault(); + redo(); + return; + } + if (matchesShortcut(e, "undo", overrides)) { + e.preventDefault(); + undo(); + return; + } + const mod = e.ctrlKey || e.metaKey; + if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === "y") { + e.preventDefault(); + redo(); + } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [undo, redo]); + }, [undo, redo, overrides]); } /** @@ -141,28 +161,31 @@ export function useCommandTabShortcut( * Ebenen-Art über ein Ref (sonst müsste der Effekt bei jedem Render neu * registrieren). */ +/** Reihenfolge/Zuordnung Ziffer→Werkzeug — Ids der rebindbaren Kombination in `keyboardShortcuts.ts`. */ +const TOOL_SHORTCUT_IDS: { id: ShortcutId; tool: ToolId }[] = [ + { id: "toolText", tool: "text" }, + { id: "toolLine", tool: "line" }, + { id: "toolCircle", tool: "circle" }, + { id: "toolRect", tool: "rect" }, + { id: "toolPolyline", tool: "polyline" }, + { id: "toolWall", tool: "wall" }, + { id: "toolCeiling", tool: "ceiling" }, + { id: "toolWindow", tool: "window" }, + { id: "toolDoor", tool: "door" }, + { id: "toolRoom", tool: "room" }, +]; + export function useToolNumberShortcuts( onSelectTool: (id: ToolId) => void, isFloor: boolean, engineRef: RefObject, + overrides: ShortcutOverrides, gripDragInfoRef?: RefObject<{ index: number; raw: Vec2 } | null>, edgeDragInfoRef?: RefObject, ): void { - const toolShortcutRef = useRef({ onSelectTool, floor: isFloor }); - toolShortcutRef.current = { onSelectTool, floor: isFloor }; + const toolShortcutRef = useRef({ onSelectTool, floor: isFloor, overrides }); + toolShortcutRef.current = { onSelectTool, floor: isFloor, overrides }; useEffect(() => { - const MAP: Record = { - "1": "text", - "2": "line", - "3": "circle", - "4": "rect", - "5": "polyline", - "6": "wall", - "7": "ceiling", - "8": "window", - "9": "door", - "0": "room", - }; const onKey = (e: KeyboardEvent) => { if (e.ctrlKey || e.metaKey || e.altKey) return; // Ein Punkt-Griff ist bewaffnet (s. useGripEditing.ts) — Zifferntasten @@ -184,11 +207,13 @@ export function useToolNumberShortcuts( empty && !eng?.hasFields() && !eng?.acceptsFreeText(); if (!cmdLineFreeToSwitch) return; } - const id = MAP[e.key]; - if (!id) return; + const match = TOOL_SHORTCUT_IDS.find(({ id }) => + matchesShortcut(e, id, toolShortcutRef.current.overrides), + ); + if (!match) return; if (!toolShortcutRef.current.floor) return; // Werkzeuge nur auf Geschossen e.preventDefault(); - toolShortcutRef.current.onSelectTool(id); + toolShortcutRef.current.onSelectTool(match.tool); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); @@ -258,6 +283,7 @@ export function useSelectAllAndDeleteShortcut(opts: { activeTransform: ActiveTransform; project: Project; activeLevelId: string; + shortcutOverrides: ShortcutOverrides; selectedDrawingIds: string[]; selectedWallIds: string[]; selectedCeilingIds: string[]; @@ -288,6 +314,7 @@ export function useSelectAllAndDeleteShortcut(opts: { activeTransform, project, activeLevelId, + shortcutOverrides, setSelectedWallIds, setSelectedDrawingIds, setSelectedCeilingIds, @@ -307,7 +334,7 @@ export function useSelectAllAndDeleteShortcut(opts: { if (isEditableTarget(e)) return; // Alles auswählen (alle Bauteilarten des aktiven Geschosses/der Ebene + // die Schnittlinien-Symbole, die auf JEDEM Grundriss erscheinen). - if ((e.ctrlKey || e.metaKey) && (e.key === "a" || e.key === "A")) { + if (matchesShortcut(e, "selectAll", shortcutOverrides)) { const wallIds = project.walls .filter((w) => w.floorId === activeLevelId) .map((w) => w.id); @@ -375,7 +402,12 @@ export function useSelectAllAndDeleteShortcut(opts: { } return; } - if (e.key !== "Delete" && e.key !== "Backspace") return; + // Backspace bleibt fest verdrahtete Zusatzbelegung (bare, kein Modifikator) + // neben der rebindbaren Haupt-Kombination (Default "Delete"). + const isDelete = + matchesShortcut(e, "deleteSelection", shortcutOverrides) || + (e.key === "Backspace" && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey); + if (!isDelete) return; if (activeTransform) return; // während einer Transformation nicht löschen if (hasSelectionToDelete()) { deleteSelection(); @@ -387,6 +419,7 @@ export function useSelectAllAndDeleteShortcut(opts: { }, [ opts.activeTool, opts.activeTransform, + opts.shortcutOverrides, opts.selectedDrawingIds, opts.selectedWallIds, opts.selectedCeilingIds, @@ -425,18 +458,19 @@ export function useSplitJoinShortcut( runSplit: (ids: string[]) => void, setSelectedDrawingIds: (ids: string[]) => void, setSelectedWallIds: (ids: string[]) => void, + overrides: ShortcutOverrides, ): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { - if (!(e.ctrlKey || e.metaKey)) return; - const k = e.key.toLowerCase(); - if (k !== "s" && k !== "j") return; if (isEditableTarget(e)) return; + const isSplit = matchesShortcut(e, "split", overrides); + const isJoin = !isSplit && matchesShortcut(e, "join", overrides); + if (!isSplit && !isJoin) return; const ids = selectedDrawingIds; if (ids.length === 0) return; // nur 2D-Auswahl bedient; Wände → no-op e.preventDefault(); - if (k === "s") { + if (isSplit) { runSplit(ids); return; } @@ -449,7 +483,7 @@ export function useSplitJoinShortcut( window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedDrawingIds, engine]); + }, [selectedDrawingIds, engine, overrides]); } /** @@ -461,6 +495,18 @@ export function useSplitJoinShortcut( * aus — so wandert z. B. importiertes Mobiliar von einem Geschoss auf ein * anderes. Im Textfeld bleibt das native Copy/Paste; ohne Auswahl kein * preventDefault (Browser-Copy bleibt möglich). + * + * OS-Zwischenablage (Nutzer-Wunsch: „kein Copy/Paste zwischen zwei Fenstern/ + * Projekten derselben App"): Kopieren schreibt ZUSÄTZLICH zum React-State + * einen markierten JSON-Text via `navigator.clipboard.writeText` (s. + * `editors/elementClipboardSerialize.ts`) — bestes Bemühen, Fehler (Rechte + * verweigert, API fehlt) werden verschluckt, der In-App-State bleibt der + * verlässliche Pfad. Einfügen liest ZUERST `navigator.clipboard.readText()` + * (deshalb async): parst der Text erfolgreich als unsere Marke, hat er + * Vorrang (ermöglicht Einfügen aus einem ANDEREN Fenster/derselben-App- + * Instanz); scheitert das (fremder Text, keine Berechtigung, API fehlt), + * fällt es auf den In-App-`elementClipboard`-State zurück — unverändertes + * Verhalten für den bisherigen Innerhalb-eines-Fensters-Fall. */ export function useElementClipboardShortcut( sel: ElementSelectionIds, @@ -480,43 +526,58 @@ export function useElementClipboardShortcut( extrudedSolidIds: (ids: string[]) => void; columnIds: (ids: string[]) => void; }, + overrides: ShortcutOverrides, ): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { - if (!(e.ctrlKey || e.metaKey) || e.shiftKey || e.altKey) return; - const k = e.key.toLowerCase(); - if (k !== "c" && k !== "v") return; + const isCopy = matchesShortcut(e, "copyElements", overrides); + const isPaste = !isCopy && matchesShortcut(e, "pasteElements", overrides); + if (!isCopy && !isPaste) return; if (isEditableTarget(e)) return; - if (k === "c") { + if (isCopy) { const clip = collectElementClipboard(project, sel); if (!clip) return; // nichts gewählt → natives Browser-Copy zulassen e.preventDefault(); setElementClipboard(clip); + // Bestes Bemühen, OS-weit verfügbar zu machen — Fehler (Rechte + // verweigert, API fehlt in diesem Webview) verschluckt, der In-App- + // State oben ist bereits gesetzt und bleibt der verlässliche Pfad. + navigator.clipboard?.writeText(serializeClipboardText(clip)).catch(() => {}); return; } - // Einfügen: Klone auf dem aktiven Geschoss, neue IDs, danach ausgewählt. - if (!elementClipboard || isClipboardEmpty(elementClipboard)) return; + // Einfügen: erst OS-Zwischenablage versuchen (ermöglicht Fenster- + // übergreifend), sonst die In-App-Zwischenablage. `preventDefault` + // sofort (synchron) — wir sind hier NIE in einem Textfeld + // (isEditableTarget oben hat das schon ausgeschlossen), also gibt es + // kein natives Paste-Ziel, das verloren gehen könnte. e.preventDefault(); - const { project: next, pastedIds } = pasteElementClipboard( - project, - elementClipboard, - activeLevelId, - ); - setProject(next); - setSelected.wallIds(pastedIds.wallIds); - setSelected.drawingIds(pastedIds.drawingIds); - setSelected.ceilingIds(pastedIds.ceilingIds); - setSelected.roofIds(pastedIds.roofIds); - setSelected.openingIds(pastedIds.openingIds); - setSelected.stairIds(pastedIds.stairIds); - setSelected.roomIds(pastedIds.roomIds); - setSelected.extrudedSolidIds(pastedIds.extrudedSolidIds); - setSelected.columnIds(pastedIds.columnIds); + const paste = (clip: ElementClipboard | null) => { + if (!clip || isClipboardEmpty(clip)) return; + const { project: next, pastedIds } = pasteElementClipboard(project, clip, activeLevelId); + setProject(next); + setSelected.wallIds(pastedIds.wallIds); + setSelected.drawingIds(pastedIds.drawingIds); + setSelected.ceilingIds(pastedIds.ceilingIds); + setSelected.roofIds(pastedIds.roofIds); + setSelected.openingIds(pastedIds.openingIds); + setSelected.stairIds(pastedIds.stairIds); + setSelected.roomIds(pastedIds.roomIds); + setSelected.extrudedSolidIds(pastedIds.extrudedSolidIds); + setSelected.columnIds(pastedIds.columnIds); + }; + if (navigator.clipboard?.readText) { + navigator.clipboard + .readText() + .then((text) => paste(parseClipboardText(text) ?? elementClipboard)) + .catch(() => paste(elementClipboard)); + } else { + paste(elementClipboard); + } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sel, elementClipboard, activeLevelId, project]); + }, [sel, elementClipboard, activeLevelId, project, overrides]); } /** @@ -529,23 +590,27 @@ export function useBooleanOpsShortcut( selectedDrawingIds: string[], drawings2d: Drawing2D[], applyBoolean: (op: (srcs: Drawing2D[]) => BooleanResult) => void, + overrides: ShortcutOverrides, ): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { - if (!(e.ctrlKey || e.metaKey) || !e.shiftKey) return; - const k = e.key.toLowerCase(); - if (k !== "u" && k !== "d" && k !== "i") return; if (isEditableTarget(e)) return; if (selectedDrawingIds.length < 2) return; - e.preventDefault(); - if (k === "u") applyBoolean(unionDrawings); - else if (k === "d") applyBoolean(differenceDrawings); - else applyBoolean(intersectionDrawings); + if (matchesShortcut(e, "booleanUnion", overrides)) { + e.preventDefault(); + applyBoolean(unionDrawings); + } else if (matchesShortcut(e, "booleanDifference", overrides)) { + e.preventDefault(); + applyBoolean(differenceDrawings); + } else if (matchesShortcut(e, "booleanIntersection", overrides)) { + e.preventDefault(); + applyBoolean(intersectionDrawings); + } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedDrawingIds, drawings2d]); + }, [selectedDrawingIds, drawings2d, overrides]); } /** @@ -566,11 +631,16 @@ export function useTransformShortcuts( selectedDrawingIds: string[], selectedExtrudedSolidId: string | null, selectedColumnId: string | null, + selectedCeilingIds: string[], + selectedRoofIds: string[], + selectedStairIds: string[], + selectedRoomIds: string[], engine: CommandEngine, setDraft: (draft: ToolDraft | null) => void, requestCopyCount: (mode: "array" | "distribute") => void, onRunCommand: (name: string) => void, commandLineRef: RefObject, + overrides: ShortcutOverrides, ): void { useEffect(() => { if (activeTool !== "select") return; @@ -593,29 +663,38 @@ export function useTransformShortcuts( return; } // „q" = Messen (Distanz/Winkel) — braucht KEINE Auswahl, daher vor hasSel. - if (e.key.toLowerCase() === "q") { + if (matchesShortcut(e, "measure", overrides)) { onRunCommand("measure"); e.preventDefault(); return; } - // Transformierbar sind Wände, 2D-Zeichnungen, extrudierte Körper und Stützen - // (dieselben Arten wie transformSel). Öffnungen/Treppen laufen bewusst NICHT - // hierüber, sondern über ihre eigenen Bewegpunkte (Grips) — sie sind wand- - // bzw. geschossgebunden. + // Transformierbar sind Wände, 2D-Zeichnungen, extrudierte Körper, Stützen, + // Decken/Dächer/Treppen/Räume (dieselben Arten wie transformSel). Öffnungen + // laufen bewusst NICHT hierüber, sondern über ihre eigenen Bewegpunkte + // (Grips) — sie sind wandgebunden (Position = Abstand entlang der + // Wandachse), kein freier 2D-Punkt. const hasSel = selectedWallIds.length > 0 || !!selectedDrawingId || selectedDrawingIds.length > 0 || !!selectedExtrudedSolidId || - !!selectedColumnId; + !!selectedColumnId || + selectedCeilingIds.length > 0 || + selectedRoofIds.length > 0 || + selectedStairIds.length > 0 || + selectedRoomIds.length > 0; if (!hasSel) return; - const k = e.key.toLowerCase(); // Bewegen/Spiegeln/Drehen laufen ALLE über die interaktive Transformation // (`activeTransform`) mit den U/I/O/P-Kopiermodi (Bewegen/Kopie/Reihe/ // Verteilen). Prompt + Optionen + Live-Feld speisen die Command-Line; die // Kürzel U/I/O/P wirken dort auch bei fokussiertem Eingabefeld (options.key). - const op: TransformOp | null = - k === "m" ? "move" : k === "s" ? "mirror" : k === "d" ? "rotate" : null; + const op: TransformOp | null = matchesShortcut(e, "transformMove", overrides) + ? "move" + : matchesShortcut(e, "transformMirror", overrides) + ? "mirror" + : matchesShortcut(e, "transformRotate", overrides) + ? "rotate" + : null; if (op) { setActiveTransform({ op, copyMode: "move", count: 1, points: [] }); setDraft(null); @@ -633,7 +712,12 @@ export function useTransformShortcuts( selectedDrawingIds, selectedExtrudedSolidId, selectedColumnId, + selectedCeilingIds, + selectedRoofIds, + selectedStairIds, + selectedRoomIds, engine, + overrides, ]); } @@ -650,14 +734,16 @@ export function useGroupShortcut( currentSelection: GroupMembership, selectedGroupIds: string[], applySelection: (mem: GroupMembership, groupIds: string[]) => void, + overrides: ShortcutOverrides, ): void { useEffect(() => { const onKey = (e: KeyboardEvent) => { - if (!(e.ctrlKey || e.metaKey)) return; - if (e.key.toLowerCase() !== "g") return; + const isUngroup = matchesShortcut(e, "ungroup", overrides); + const isGroup = !isUngroup && matchesShortcut(e, "group", overrides); + if (!isUngroup && !isGroup) return; if (isEditableTarget(e)) return; e.preventDefault(); - if (e.shiftKey) { + if (isUngroup) { // Ungruppieren: für jede gewählte Gruppe eine Hülle auflösen; ihre // direkten Mitglieder (+ Untergruppen) werden die neue Auswahl. if (selectedGroupIds.length === 0) return; @@ -684,5 +770,5 @@ export function useGroupShortcut( window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [project, currentSelection, selectedGroupIds]); + }, [project, currentSelection, selectedGroupIds, overrides]); } diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index ce1304c..0146580 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -39,7 +39,10 @@ function selHit(sel: PlanSelection): { kind: MemberKind; id: string } | null { export function useMouseSelectionHandlers(opts: { project: Project; - setProject: (updater: (p: Project) => Project) => void; + /** `coalesceKey`: s. `projectSlice.ts` `setProject` — von `commitTextEdit` + * genutzt, damit EIN Tipp-Vorgang EINEN Undo-Schritt erzeugt (wie beim + * Griff-Ziehen), statt bei jedem Tastendruck einen neuen zu pushen. */ + setProject: (updater: (p: Project) => Project, coalesceKey?: string) => void; activeLevelId: string; visibleCodes: Set; categoryDisplay: CategoryDisplayResolver & DisplayResolver; @@ -158,17 +161,24 @@ export function useMouseSelectionHandlers(opts: { // mehr) — schreibt AUCH einen leeren Zustand zurück (kein Guard mehr), damit // Löschen bis auf null Zeichen sich sofort im Modell spiegelt; das eigentliche // Aufräumen eines leer verlassenen NEUEN Elements übernimmt `closeTextEdit`. + // `coalesceKey`: OHNE das würde JEDER Tastendruck einen eigenen Undo-Schritt + // pushen (bei HISTORY_LIMIT=100 wäre nach 100 Zeichen der Stand VOR dem + // Editieren aus dem Undo-Stack gefallen) — dasselbe Koaleszenz-Muster wie + // beim Griff-Ziehen (`moveGripOf` & Co., s. `projectSlice.ts`). const commitTextEdit = (doc: RichTextDoc) => { const id = editTextId; if (!id) return; - setProject((p) => ({ - ...p, - drawings2d: p.drawings2d.map((d) => - d.id === id && d.geom.shape === "text" - ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } - : d, - ), - })); + setProject( + (p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + d.id === id && d.geom.shape === "text" + ? { ...d, geom: { ...d.geom, doc, text: plainText(doc) } } + : d, + ), + }), + `commitTextEdit:${id}`, + ); }; // Inline-Editor schliessen (Backdrop-Klick/Escape): bleibt das Element leer @@ -245,6 +255,14 @@ export function useMouseSelectionHandlers(opts: { // derselbe Ignorier-Kurzschluss wie beim normalen Sperren oben. const hit = selHit(sel); if (hit && !isInsideActiveGroup(project, hit.kind, hit.id, groupPath)) return; + // Objekt-Sperre (`Wall.locked` & Co., s. `state/objectLock.ts`): bewusst + // NICHT die Auswahl blockieren (sonst kein Weg mehr zurück zum + // Kontextmenü-„Entsperren", sobald die Selektion einmal woanders hin + // wechselt — Sackgasse). Ein gesperrtes Element bleibt anwähl-/ + // inspizierbar; blockiert wird die MODIFIKATION direkt an den + // Mutations-Stellen (`moveGrip`/`moveElementBy` in projectSlice.ts, + // `deleteSelection` in App.tsx) — dieselbe Semantik wie AutoCADs + // Layer-„Lock" (weiterhin wählbar, nicht editierbar). // Shift+Klick: Mehrfach-Auswahl — getroffenes Element zu-/abschalten, den // Rest behalten (Wände und 2D-Zeichnungen unabhängig, gemischte Auswahl // erlaubt). Leerraum-Klick mit Shift lässt die Auswahl unverändert. @@ -417,6 +435,9 @@ export function useMouseSelectionHandlers(opts: { // Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen // (nach CAD-Konvention von PlanView bestimmt). Ersetzt die bisherige Auswahl. const onPlanMarquee = (sel: MarqueeSelection) => { + // Objekt-Sperre: NICHT hier filtern (s. Kommentar bei `onPlanSelect`) — + // Auswahl bleibt für gesperrte Elemente uneingeschränkt möglich, die + // Mutations-Stellen selbst prüfen `isLocked`. const raw: GroupMembership = { wallIds: sel.wallIds, drawingIds: sel.drawingIds ?? [], @@ -473,7 +494,7 @@ export function useMouseSelectionHandlers(opts: { }) => { const wallId = hitTestWall(project, activeLevelId, visibleCodes, info.model); if (wallId && !selectedWallIds.includes(wallId)) setSelectedWallIds([wallId]); - setMenu({ kind: "plan", x: info.clientX, y: info.clientY, wallId }); + setMenu({ kind: "plan", x: info.clientX, y: info.clientY, wallId, model: info.model }); }; // Links-Klick im 3D: per Raycast getroffene Wand wählen (Einzelauswahl). const onViewportSelectWall = (wallId: string | null) => { @@ -587,6 +608,23 @@ export function useMouseSelectionHandlers(opts: { setSelectedSectionLineIds([]); return; } + if (hit.kind === "drawing") { + setSelectedDrawingIds( + additive ? Array.from(new Set([...selectedDrawingIds, hit.id])) : [hit.id], + ); + setSelectedDrawingId(hit.id); + setSelectedWallIds([]); + setSelectedCeilingIds([]); + setSelectedOpeningIds([]); + setSelectedStairIds([]); + setSelectedRoomIds([]); + setSelectedExtrudedSolidIds([]); + setSelectedColumnIds([]); + setSelectedRoofIds([]); + setSelectedContextObjectIds([]); + setSelectedSectionLineIds([]); + return; + } if (hit.kind === "stair") { setSelectedStairIds([hit.id]); setSelectedWallIds([]); diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 2e11af8..b752d1e 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -71,9 +71,36 @@ function singleTransformSel(kind: string, id: string): TransformSelection | null if (kind === "drawing2d") return { wallIds: [], drawingId: id }; if (kind === "extrudedSolid") return { wallIds: [], drawingId: null, extrudedSolidId: id }; if (kind === "column") return { wallIds: [], drawingId: null, columnId: id }; + if (kind === "ceiling") return { wallIds: [], drawingId: null, ceilingIds: [id] }; + // Dach: Move geht (Umriss verschiebt sich), Rotate no-opt bewusst (s. + // TransformSelection.roofIds) — der Host-Aufruf degradiert dafür von + // selbst über `gatherItems`, kein Sonderfall hier nötig. + if (kind === "roof") return { wallIds: [], drawingId: null, roofIds: [id] }; + if (kind === "stair") return { wallIds: [], drawingId: null, stairIds: [id] }; + if (kind === "room") return { wallIds: [], drawingId: null, roomIds: [id] }; return null; } +/** + * Grundriss-Kamera für einen View-Snapshot einsammeln (Bildmitte + Zoom) — + * nur möglich, wenn gerade ein Grundriss gemountet ist (`viewType==="grundriss"`, + * `planViewRef.current` also nicht null); sonst leeres Objekt (kein Feld + * gesetzt), damit `{...captureCameraState(...)}` additiv in ein + * `ViewSnapshotState`-Objektliteral eingemischt werden kann, ohne `undefined`- + * Werte explizit zu setzen. + */ +function captureCameraState( + planViewRef: RefObject, + viewType: ViewType, +): Partial> { + if (viewType !== "grundriss") return {}; + const pv = planViewRef.current; + if (!pv) return {}; + const pxPerMeter = pv.pxPerMeter(); + if (!(pxPerMeter > 0)) return {}; + return { cameraCenter: pv.viewCenterModel(), cameraPxPerMeter: pxPerMeter }; +} + export function usePanelHostBase(opts: { project: Project; setProject: (updater: (p: Project) => Project) => void; @@ -119,6 +146,9 @@ export function usePanelHostBase(opts: { | "patchLineStyle" | "addLineStyle" | "deleteLineStyle" + | "patchTextStyle" + | "addTextStyle" + | "deleteTextStyle" | "patchWallType" | "addWallType" | "deleteWallType" @@ -150,6 +180,7 @@ export function usePanelHostBase(opts: { | "setCeilingThickness" | "updateStair" | "updateRoom" + | "addColorToCustomPalette" >; selectionState: Pick< ReturnType, @@ -240,6 +271,9 @@ export function usePanelHostBase(opts: { patchLineStyle, addLineStyle, deleteLineStyle, + patchTextStyle, + addTextStyle, + deleteTextStyle, patchWallType, addWallType, deleteWallType, @@ -271,6 +305,7 @@ export function usePanelHostBase(opts: { setCeilingThickness, updateStair, updateRoom, + addColorToCustomPalette, } = projectActions; const { updateRoof, @@ -350,6 +385,9 @@ export function usePanelHostBase(opts: { onPatchLineStyle: patchLineStyle, onAddLineStyle: addLineStyle, onDeleteLineStyle: deleteLineStyle, + onPatchTextStyle: patchTextStyle, + onAddTextStyle: addTextStyle, + onDeleteTextStyle: deleteTextStyle, onPatchWallType: patchWallType, onAddWallType: addWallType, onDeleteWallType: deleteWallType, @@ -433,17 +471,20 @@ export function usePanelHostBase(opts: { setElementFillColor(selection.id, color); }, onSetSelectionOpacity: (opacity) => { - // Deckkraft nur bei Bild-Elementen (Drawing2D `{shape:"image"}` im - // Plan, Layout-Annotation `kind:"image"` auf dem Blatt, Kontext-Objekt - // `type:"image"` = importiertes Luftbild). + // Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der + // Bildgeometrie (bestehendes Verhalten, eigenes Feld); bei allen + // übrigen Formen die neue OBJEKT-Transparenz, die auf Striche UND + // Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches + // Feld gesetzt wird, entscheidet die Form. if (selection?.kind === "drawing2d") setProject((p) => ({ ...p, - drawings2d: p.drawings2d.map((d) => - d.id === selection.id && d.geom.shape === "image" + drawings2d: p.drawings2d.map((d) => { + if (d.id !== selection.id) return d; + return d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } - : d, - ), + : { ...d, opacity }; + }), })); else if (selection?.kind === "layoutAnnotation" && activeLayout) patchOpenLayout(activeLayout.id, (l) => @@ -508,6 +549,73 @@ export function usePanelHostBase(opts: { else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); }, + onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex), + onSetDashScale: (drawingId, scale) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => (d.id === drawingId ? { ...d, dashScale: scale } : d)), + })), + onSetDetailRefLabel: (drawingId, label) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + d.id === drawingId && d.geom.shape === "detailref" + ? { ...d, geom: { ...d.geom, label } } + : d, + ), + })), + onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => { + if (d.id !== drawingId || d.geom.shape !== "detailref") return d; + const geom = { ...d.geom }; + if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; + else delete geom.sheetLayoutId; + return { ...d, geom }; + }), + })), + onSetDetailRefSheetLabel: (drawingId, sheetLabel) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + d.id === drawingId && d.geom.shape === "detailref" + ? { ...d, geom: { ...d.geom, sheetLabel } } + : d, + ), + })), + onSetHatchPlacement: (drawingId, patch) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => { + if (d.id !== drawingId) return d; + const next = { ...d }; + // `null` = zurück auf die Ressource (Feld entfernen). + if ("angleDeg" in patch) + patch.angleDeg === null ? delete next.hatchAngleDeg : (next.hatchAngleDeg = patch.angleDeg); + if ("scale" in patch) + patch.scale === null ? delete next.hatchScale : (next.hatchScale = patch.scale); + if ("origin" in patch) + patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin); + return next; + }), + })), + onSetEndMarks: (drawingId, patch) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + d.id === drawingId ? { ...d, endMarks: { ...d.endMarks, ...patch } } : d, + ), + })), + onSetDimensionStyle: (drawingId, patch) => + setProject((p) => ({ + ...p, + drawings2d: p.drawings2d.map((d) => + d.id === drawingId && d.geom.shape === "dimension" + ? { ...d, geom: { ...d.geom, ...patch } } + : d, + ), + })), onSetSelectionBackgroundPen: (penId) => { if (!selection) return; const background = penId ? resolvePenColor(project, penId) : undefined; @@ -658,12 +766,42 @@ export function usePanelHostBase(opts: { geom: { ...d.geom, b: { x: a.x + ux * length, y: a.y + uy * length } }, }); }, + onSetDrawingLineAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "line") return; + const { a, b } = d.geom; + const len = Math.hypot(b.x - a.x, b.y - a.y); + if (len < 1e-9) return; + const rad = (deg * Math.PI) / 180; + updateDrawing2D(selection.id, { + geom: { ...d.geom, b: { x: a.x + Math.cos(rad) * len, y: a.y + Math.sin(rad) * len } }, + }); + }, onSetDrawingCircleRadius: (radius) => { if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; const d = project.drawings2d.find((x) => x.id === selection.id); if (!d || d.geom.shape !== "circle") return; updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); }, + onSetDrawingArcRadius: (radius) => { + if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); + }, + onSetDrawingArcStartAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, a0: (deg * Math.PI) / 180 } }); + }, + onSetDrawingArcEndAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, a1: (deg * Math.PI) / 180 } }); + }, // ── Wand-Attribute (nur bei selektierter Wand) ───────────────────────── onSetWallReferenceLine: (ref) => { if (selection?.kind === "wall") @@ -771,6 +909,9 @@ export function usePanelHostBase(opts: { onSetOpeningLintelLines: (lintelLines) => { if (selection?.kind === "opening") updateOpening(selection.id, { lintelLines }); }, + onSetOpeningDetailLevel: (detailLevel) => { + if (selection?.kind === "opening") updateOpening(selection.id, { detailLevel }); + }, onSetOpeningFrameLine: (v) => { if (selection?.kind === "opening") updateOpening(selection.id, { frameLine: v }); }, @@ -1034,6 +1175,7 @@ export function usePanelHostBase(opts: { enabledOverrideRuleIds: (project.overrideRules ?? []) .filter((r) => r.enabled) .map((r) => r.id), + ...captureCameraState(planViewRef, viewType), }; const snap = captureViewSnapshot(`vs-${Date.now()}`, trimmed, st); // Neuer Ausschnitt landet im aktiven Ordner (falls das Panel einen @@ -1069,6 +1211,7 @@ export function usePanelHostBase(opts: { enabledOverrideRuleIds: (project.overrideRules ?? []) .filter((r) => r.enabled) .map((r) => r.id), + ...captureCameraState(planViewRef, viewType), }; const snap = captureViewSnapshot(`vs-${Date.now()}`, name, st); setProject((p) => ({ @@ -1104,9 +1247,19 @@ export function usePanelHostBase(opts: { st.enabledOverrideRuleIds, ), })); - requestAnimationFrame(() => - planViewRef.current?.applyScale(st.scaleDenominator), - ); + requestAnimationFrame(() => { + planViewRef.current?.applyScale(st.scaleDenominator); + // Kamera NACH `applyScale` restaurieren (nicht statt): `applyScale` + // setzt auch die Papier-Massstab-Referenz für Strichbreiten + // (`setPaperScale`, s. `PlanView.tsx`), hält dabei aber die BISHERIGE + // Bildmitte. `setCamera` schwenkt danach im selben Tick (kein + // sichtbares Doppel-Springen) auf die erfasste Mitte — nur wenn der + // Ausschnitt eine Kamera trägt (Alt-Ausschnitte/3D-Erfassung: Mitte + // bleibt wie bisher unverändert). + if (st.cameraCenter && st.cameraPxPerMeter) { + planViewRef.current?.setCamera(st.cameraCenter, st.cameraPxPerMeter); + } + }); // Klick = Anwenden UND Anwählen: der Ausschnitt bleibt markiert, bis der // Nutzer eine erfasste Grösse ändert (Abweichungs-Effekt löscht ihn dann). setSelectedViewSnapshotId(id); diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index e8d2878..8665c4e 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -98,6 +98,9 @@ export function useProjectActions( const patchLineStyle = useStore((s) => s.patchLineStyle); const addLineStyle = useStore((s) => s.addLineStyle); const deleteLineStyle = useStore((s) => s.deleteLineStyle); + const patchTextStyle = useStore((s) => s.patchTextStyle); + const addTextStyle = useStore((s) => s.addTextStyle); + const deleteTextStyle = useStore((s) => s.deleteTextStyle); const addPen = useStore((s) => s.addPen); const renamePen = useStore((s) => s.renamePen); const deletePen = useStore((s) => s.deletePen); @@ -108,6 +111,15 @@ export function useProjectActions( const patchPenSetColor = useStore((s) => s.patchPenSetColor); const patchPenSetWeight = useStore((s) => s.patchPenSetWeight); const seedStandardPenSet = useStore((s) => s.seedStandardPenSet); + const addCustomPalette = useStore((s) => s.addCustomPalette); + const renameCustomPalette = useStore((s) => s.renameCustomPalette); + const deleteCustomPalette = useStore((s) => s.deleteCustomPalette); + const addColorToCustomPalette = useStore((s) => s.addColorToCustomPalette); + const removeColorFromCustomPalette = useStore((s) => s.removeColorFromCustomPalette); + const setCustomPaletteVisible = useStore((s) => s.setCustomPaletteVisible); + const setBuiltinPaletteVisible = useStore((s) => s.setBuiltinPaletteVisible); + const insertDrawingPoint = useStore((s) => s.insertDrawingPoint); + const deleteDrawingPoint = useStore((s) => s.deleteDrawingPoint); // Wandstile: immutable Patch eines Wandtyps (z. B. Schichtfugen-Stile). Kein // eigener Store-Slice nötig — läuft direkt über setProject wie die übrigen // Ressourcen-Mutationen. @@ -434,6 +446,9 @@ export function useProjectActions( patchLineStyle, addLineStyle, deleteLineStyle, + patchTextStyle, + addTextStyle, + deleteTextStyle, addPen, renamePen, deletePen, @@ -444,6 +459,15 @@ export function useProjectActions( patchPenSetColor, patchPenSetWeight, seedStandardPenSet, + addCustomPalette, + renameCustomPalette, + deleteCustomPalette, + addColorToCustomPalette, + removeColorFromCustomPalette, + setCustomPaletteVisible, + setBuiltinPaletteVisible, + insertDrawingPoint, + deleteDrawingPoint, patchWallType, setOverrideRules, patchCeilingType, diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index 591afe5..65e35ff 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -9,8 +9,8 @@ import { useEffect, useRef, useState } from "react"; import type { RefObject } from "react"; import { t } from "../i18n"; -import { parseDxf } from "../io/dxfParser"; import type { DxfImportResult } from "../io/dxfParser"; +import { parseDxfAsync } from "../io/dxfParserAsync"; import { buildDrawings } from "../ui/ImportDialog"; import type { ImportDecision } from "../ui/ImportDialog"; import { exportScheduleCsv } from "../export/exportSchedule"; @@ -45,7 +45,7 @@ function drawingsBBox( }; for (const d of drawings) { const g = d.geom; - if (g.shape === "line" || g.shape === "xline") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } + if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); } else if (g.shape === "polyline") for (const p of g.pts) acc(p.x, p.y); else if (g.shape === "rect") { acc(g.min.x, g.min.y); acc(g.max.x, g.max.y); } else if (g.shape === "circle" || g.shape === "arc") { @@ -59,6 +59,12 @@ function drawingsBBox( } else if (g.shape === "dimension") { for (const p of g.pts) acc(p.x, p.y); } else if (g.shape === "kote") acc(g.at.x, g.at.y); + else if (g.shape === "detailref") acc(g.at.x, g.at.y); + else if (g.shape === "scalebar") { + acc(g.at.x, g.at.y); + acc(g.at.x + g.segmentLength * g.segments, g.at.y); + } + else if (g.shape === "pointmarker") acc(g.at.x, g.at.y); else if (g.shape === "text") acc(g.at.x, g.at.y); else if (g.shape === "block") acc(g.at.x, g.at.y); } @@ -72,6 +78,7 @@ function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { switch (g.shape) { case "line": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; case "xline": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; + case "ray": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; case "polyline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "rect": return { ...d, geom: { ...g, min: mv(g.min), max: mv(g.max) } }; case "circle": return { ...d, geom: { ...g, center: mv(g.center) } }; @@ -81,6 +88,9 @@ function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { case "spline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "dimension": return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; case "kote": return { ...d, geom: { ...g, at: mv(g.at) } }; + case "detailref": return { ...d, geom: { ...g, at: mv(g.at) } }; + case "scalebar": return { ...d, geom: { ...g, at: mv(g.at) } }; + case "pointmarker": return { ...d, geom: { ...g, at: mv(g.at) } }; case "text": return { ...d, @@ -88,6 +98,7 @@ function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D { ...g, at: mv(g.at), ...(g.leaderTarget ? { leaderTarget: mv(g.leaderTarget) } : {}), + ...(g.leaderBendPoints ? { leaderBendPoints: g.leaderBendPoints.map(mv) } : {}), ...(g.pathPts ? { pathPts: g.pathPts.map(mv) } : {}), }, }; @@ -135,6 +146,27 @@ export function useProjectFileActions( content: string; info: LockInfo | null; } | null>(null); + // Referenz-Identität des zuletzt gespeicherten/geladenen Projekt-Stands. + // `setProject` liefert bei JEDER echten Änderung eine NEUE `Project`-Referenz + // (structural sharing, s. historySlice.ts) — ein reiner `!==`-Vergleich + // genügt daher als billiger "ungespeicherte Änderungen"-Test, ganz ohne + // JSON-Diff. Start = das beim allerersten Render aktive Projekt (Startzustand + // gilt als "gespeichert", noch nichts zu verlieren). + const lastSavedProjectRef = useRef(project); + // Eine verworfene Aktion (Neu/Öffnen), die erst nach Bestätigung des + // "Ungespeicherte Änderungen"-Dialogs ausgeführt wird — s. `guardDiscard`. + const [pendingDiscard, setPendingDiscard] = useState<(() => void) | null>(null); + /** + * Führt `action` (Projekt ERSETZEN — Neu/Öffnen) nur direkt aus, wenn seit + * dem letzten Speichern/Laden nichts geändert wurde; sonst wird sie als + * `pendingDiscard` geparkt und der Nutzer über `UnsavedChangesDialog` + * gefragt (Speichern/Nicht speichern/Abbrechen) — ersetzt das bisherige + * kommentarlose Überschreiben (Bug: Cmd+N löschte bisher stillschweigend). + */ + const guardDiscard = (action: () => void) => { + if (project !== lastSavedProjectRef.current) setPendingDiscard(() => action); + else action(); + }; // Best-effort Lock-Freigabe beim Fenster-Schliessen (sauberes Timing; der // OS-Lock fällt bei Prozessende/Absturz ohnehin automatisch weg). No-op ohne Tauri. @@ -194,16 +226,23 @@ export function useProjectFileActions( r.readAsArrayBuffer(file); return; } + // Async-Zustand (identisches Muster zum DWG-Zweig oben): Dialog öffnet + // sofort und zeigt einen Ladehinweis, während `parseDxf` in einem Web + // Worker läuft — bei sehr grossen Dateien (Kataster-Import einer ganzen + // Stadt, Nutzer-Report 2026-10-08) blockierte das zuvor für die GESAMTE + // Parse-Dauer den Haupt-Thread/die UI (s. `io/dxfParserAsync.ts`). + setImportState({ fileName: file.name, isDwg: false, parsed: null, loading: true }); const r = new FileReader(); r.onload = () => { - let parsed: DxfImportResult | null = null; - try { - parsed = parseDxf(String(r.result ?? "")); - } catch (err) { - console.error("DXF-Import fehlgeschlagen:", err); - parsed = { meshes: [], contours: [] }; - } - setImportState({ fileName: file.name, isDwg: false, parsed }); + parseDxfAsync(String(r.result ?? "")) + .then((parsed) => { + setImportState({ fileName: file.name, isDwg: false, parsed, loading: false }); + }) + .catch((err) => { + console.error("DXF-Import fehlgeschlagen:", err); + const parsed: DxfImportResult = { meshes: [], contours: [] }; + setImportState({ fileName: file.name, isDwg: false, parsed, loading: false }); + }); }; r.readAsText(file); }; @@ -217,24 +256,33 @@ export function useProjectFileActions( // Shape-Sanity-Check (walls/layers als Array), damit ein fremdes/kaputtes // JSON nicht die App zerlegt. Alte „.json"-Projekte bleiben ladbar (Filter // erlaubt beide Endungen). - const onSaveProject = () => { + // Liefert `true`, wenn wirklich gespeichert wurde (nicht bei abgebrochenem + // nativem Dialog) — `guardDiscard`-Aufrufer verlassen sich darauf, um NICHT + // zu verwerfen, wenn der Nutzer den Speichern-Dialog abbricht. + const onSaveProject = (): Promise => { const json = JSON.stringify(project, null, 2); - void saveProjectFile(json, project.name, (path) => + return saveProjectFile(json, project.name, (path) => addRecentProject(path, project.name || "modell"), - ); + ).then((saved) => { + if (saved) lastSavedProjectRef.current = project; + return saved; + }); }; // „Neu" (Datei-Menü): leeres Projekt, wie am Startbildschirm — löst dabei // einen evtl. gehaltenen Datei-Lock der bisherigen Projektdatei und vergisst - // deren Pfad (das leere Projekt ist noch NICHT gespeichert). - const onNewProject = () => { + // deren Pfad (das leere Projekt ist noch NICHT gespeichert). Über + // `guardDiscard`: bei ungespeicherten Änderungen erst der Dialog, s. o. + const onNewProject = () => guardDiscard(() => { releaseCurrentProjectLock(); setProject(emptyProject); - }; + lastSavedProjectRef.current = emptyProject; + }); // Übernimmt ein neues, noch UNGESPEICHERTES Projekt aus Vorlagen-Inhalt // (Musterhaus ODER eine gewählte `.obpt`-Datei): grobe Form-Prüfung wie beim // normalen Öffnen, aber bewusst OHNE Pfad/Lock zu setzen — die Vorlage // bleibt unangetastet, das nächste „Speichern" fragt nach einem neuen Ort. + // Ersetzt ebenfalls das bisherige Projekt → über `guardDiscard`. const applyTemplateContent = (content: string): boolean => { try { const parsed = JSON.parse(content) as Partial; @@ -242,8 +290,11 @@ export function useProjectFileActions( console.warn("Vorlagen-Datei hat kein gültiges Projekt-Format (walls/layers fehlen)."); return false; } - releaseCurrentProjectLock(); - setProject(parsed as Project); + guardDiscard(() => { + releaseCurrentProjectLock(); + setProject(parsed as Project); + lastSavedProjectRef.current = parsed as Project; + }); return true; } catch (err) { console.error("Vorlage konnte nicht geladen werden:", err); @@ -254,10 +305,12 @@ export function useProjectFileActions( // als Start eines neuen Projekts. `structuredClone`, damit spätere Bearbeitung // nicht das gemeinsame Modul-Singleton mutiert (es dient auch als Store- // Startzustand, s. state/projectSlice.ts). - const onNewProjectFromSample = () => { + const onNewProjectFromSample = () => guardDiscard(() => { releaseCurrentProjectLock(); - setProject(structuredClone(sampleProject)); - }; + const next = structuredClone(sampleProject); + setProject(next); + lastSavedProjectRef.current = next; + }); // „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst // das versteckte `` (projectTemplateFileInputRef). const onNewProjectFromTemplate = () => { @@ -301,11 +354,14 @@ export function useProjectFileActions( console.warn("Projekt-Datei hat kein gültiges Projekt-Format (walls/layers fehlen)."); return; } - releaseCurrentProjectLock(); - setProject(parsed as Project); - openedProjectPathRef.current = path; - projectLockOwnedRef.current = lockOwned; - addRecentProject(path, (parsed as Project).name || "modell"); + guardDiscard(() => { + releaseCurrentProjectLock(); + setProject(parsed as Project); + lastSavedProjectRef.current = parsed as Project; + openedProjectPathRef.current = path; + projectLockOwnedRef.current = lockOwned; + addRecentProject(path, (parsed as Project).name || "modell"); + }); } catch (err) { console.error("Projekt-Import fehlgeschlagen:", err); } @@ -408,8 +464,11 @@ export function useProjectFileActions( } // Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue // Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei. - releaseCurrentProjectLock(); - setProject(parsed as Project); + guardDiscard(() => { + releaseCurrentProjectLock(); + setProject(parsed as Project); + lastSavedProjectRef.current = parsed as Project; + }); } catch (err) { console.error("Projekt-Import fehlgeschlagen:", err); } @@ -459,6 +518,8 @@ export function useProjectFileActions( projectLockOwnedRef, lockConflict, setLockConflict, + pendingDiscard, + setPendingDiscard, openImportForFile, onSaveProject, onNewProject, diff --git a/src/state/viewSnapshots.test.ts b/src/state/viewSnapshots.test.ts index 0121dcd..b34472b 100644 --- a/src/state/viewSnapshots.test.ts +++ b/src/state/viewSnapshots.test.ts @@ -68,6 +68,58 @@ describe("viewSnapshots — captureViewSnapshot", () => { }); }); +describe("viewSnapshots — Kamera (cameraCenter/cameraPxPerMeter)", () => { + it("captureViewSnapshot übernimmt eine gegebene Kamera", () => { + const st = { ...sampleState(), cameraCenter: { x: 3, y: -4 }, cameraPxPerMeter: 72 }; + const snap = captureViewSnapshot("vs-1", "Mit Kamera", st); + expect(snap.cameraCenter).toEqual({ x: 3, y: -4 }); + expect(snap.cameraPxPerMeter).toBe(72); + }); + + it("captureViewSnapshot lässt die Kamera weg, wenn sie im Kernzustand fehlt", () => { + const snap = captureViewSnapshot("vs-1", "Ohne Kamera", sampleState()); + expect(snap.cameraCenter).toBeUndefined(); + expect(snap.cameraPxPerMeter).toBeUndefined(); + }); + + it("koppelt cameraCenter vom Live-Zustand ab (Kopie, keine Referenz)", () => { + const camera = { x: 1, y: 2 }; + const st = { ...sampleState(), cameraCenter: camera, cameraPxPerMeter: 50 }; + const snap = captureViewSnapshot("a", "n", st); + camera.x = 999; + expect(snap.cameraCenter).toEqual({ x: 1, y: 2 }); + }); + + it("Roundtrip capture → read erhält die Kamera", () => { + const st = { ...sampleState(), cameraCenter: { x: 3, y: -4 }, cameraPxPerMeter: 72 }; + const snap = captureViewSnapshot("vs-1", "Mit Kamera", st); + expect(readViewSnapshot(snap)).toEqual(st); + }); + + it("readViewSnapshot liefert undefined für einen Alt-Ausschnitt ohne Kamera (kein Crash)", () => { + const legacy: ViewSnapshot = { + id: "old", + name: "Alt", + viewType: "grundriss", + view3d: "perspective", + scaleDenominator: 100, + detail: "mittel", + activeLevelId: "floor-1", + layerVisibility: {}, + drawingVisibility: {}, + }; + const st = readViewSnapshot(legacy); + expect(st.cameraCenter).toBeUndefined(); + expect(st.cameraPxPerMeter).toBeUndefined(); + }); + + it("snapshotMatchesLiveState ignoriert eine abweichende Kamera (bewusst ausgenommen)", () => { + const snap = { ...sampleState(), cameraCenter: { x: 0, y: 0 }, cameraPxPerMeter: 50 }; + const live = { ...sampleState(), cameraCenter: { x: 999, y: 999 }, cameraPxPerMeter: 5 }; + expect(snapshotMatchesLiveState(snap, live)).toBe(true); + }); +}); + describe("viewSnapshots — readViewSnapshot", () => { it("Roundtrip: capture → read ergibt denselben Kernzustand", () => { const st = sampleState(); diff --git a/src/state/viewSnapshots.ts b/src/state/viewSnapshots.ts index 088dd38..98b4a33 100644 --- a/src/state/viewSnapshots.ts +++ b/src/state/viewSnapshots.ts @@ -13,7 +13,7 @@ // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import type { OverrideRule, ViewSnapshot } from "../model/types"; +import type { OverrideRule, ViewSnapshot, Vec2 } from "../model/types"; import type { DetailLevel, View3d, ViewType } from "../ui/TopBar"; /** @@ -33,6 +33,13 @@ export interface ViewSnapshotState { drawingVisibility: Record; /** Ids der aktiven (`enabled`) Override-Regeln zum Erfassungszeitpunkt. */ enabledOverrideRuleIds: string[]; + /** + * Grundriss-Kameraposition (Bildmitte in Modell-Metern + Zoom als px/m) — + * fehlt, wenn beim Erfassen kein Grundriss gemountet war (3D-Ansicht/ + * Schnitt) oder bei Alt-Ausschnitten. S. `ViewSnapshot.cameraCenter`. + */ + cameraCenter?: Vec2; + cameraPxPerMeter?: number; } /** @@ -61,6 +68,8 @@ export function captureViewSnapshot( enabledOverrideRuleIds: [...state.enabledOverrideRuleIds], }; if (folder && folder.trim()) snap.folder = folder.trim(); + if (state.cameraCenter) snap.cameraCenter = { ...state.cameraCenter }; + if (state.cameraPxPerMeter !== undefined) snap.cameraPxPerMeter = state.cameraPxPerMeter; return snap; } @@ -83,6 +92,8 @@ export function readViewSnapshot(snap: ViewSnapshot): ViewSnapshotState { enabledOverrideRuleIds: snap.enabledOverrideRuleIds ? [...snap.enabledOverrideRuleIds] : [], + cameraCenter: snap.cameraCenter ? { ...snap.cameraCenter } : undefined, + cameraPxPerMeter: snap.cameraPxPerMeter, }; } @@ -137,6 +148,13 @@ function idSetEqual(a: string[], b: string[]): boolean { * nur EIN Feld ab → `false`. Pure/testbar; der Aufrufer (App.tsx) normalisiert * den gespeicherten Snapshot vorher über `readViewSnapshot`, damit fehlende * optionale Felder (fov/overrides) fair verglichen werden. + * + * ABSICHTLICH ausgenommen: `cameraCenter`/`cameraPxPerMeter`. Anders als die + * übrigen (diskreten) Felder ändert sich die Kamera bei jedem Pan/Zoom in + * winzigen Fliesskomma-Schritten — eine strikte Gleichheitsprüfung würde die + * „bleibt angewählt, bis etwas abweicht"-Anzeige praktisch bei jeder + * Mausbewegung sofort auflösen. Die Kamera wird beim Erfassen/Wiederherstellen + * mitgenommen, zählt aber nicht zur „entspricht exakt"-Definition. */ export function snapshotMatchesLiveState( snap: ViewSnapshotState, diff --git a/src/styles.css b/src/styles.css index 44f24d7..a66d284 100644 --- a/src/styles.css +++ b/src/styles.css @@ -53,6 +53,18 @@ --font: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; --font-mono: "DM Mono", ui-monospace, "SF Mono", monospace; + /* Schrift für GEZEICHNETEN Planinhalt (Text-/Textspalten-Objekte, Raum- + Stempel) — bewusst NICHT `--font` (das ist die App-UI-Schrift für + Buttons/Panels/Dialoge). Deckt sich mit dem Export-Font-Stack + (`TEXT_FONT_FAMILY` in export/sceneToPrintSvg.ts, ebenso + planToPrintSvg.ts/layoutPdf.ts), damit Bildschirm und PDF/Druck + dieselbe Schrift zeigen. Wurde in primitives.tsx (SVG-Textrendering) + bereits referenziert, war aber nie definiert (fiel auf den generischen + `sans-serif`-Fallback zurück) — REGRESSION-Fix für den restlichen, + leichten Versatz zwischen Inline-Editor (der `--font`/Inter nutzte) und + dem statischen Text (effektiv `sans-serif`): unterschiedliche Schriften + haben unterschiedliche Ascent-/Zeilenabstand-Metriken. */ + --font-ui: Helvetica, Arial, sans-serif; } /* Dunkel-Palette als Opt-in (Einstellungen → Darstellung → Dunkelmodus). */ @@ -2104,6 +2116,15 @@ body { fill: var(--sheet); } +/* Sichtbares Hintergrund-Raster (PlanGrid.tsx) — rein dekorativ, dezent + hinter der Zeichnung, unabhängig vom Fang-Raster (`snap.grid`). */ +.plan-grid line { + stroke: var(--line); + stroke-opacity: 0.5; + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + /* CAD-typische Ecken: alle Plan-Striche gehren (miter) statt an dicken Ecken eine Stufe/Butt-Cap-Lücke zu zeigen. Der Miter-Grenzwert verhindert überlange Spitzen bei sehr spitzen Winkeln (dann kappen die Enden rund). Gilt für Poché-Umrisse @@ -2188,6 +2209,19 @@ body { vector-effect: non-scaling-stroke; } +/* Auswahl-Rahmen für Text-Objekte (Nutzer-Wunsch: beim blossen Anwählen, + nicht erst im Editor, soll ein Rahmen sichtbar sein — wie in + LayoutSheet.tsx schon für Blatt-Annotationen). Gestrichelt statt + durchgezogen wie .plan-sel-draw: markiert bewusst eine GESCHÄTZTE Box + (kein echtes Font-Measuring im SVG), keinen exakt nachgezeichneten Umriss. */ +.plan-svg .plan-sel-text-frame { + fill: none; + stroke: var(--accent); + stroke-width: 1.5; + stroke-dasharray: 4 3; + vector-effect: non-scaling-stroke; +} + /* Gruppen-Isolation (Vectorworks „Gruppe betreten"): halbtransparenter Orange-Rahmen (Band) am Rand der ganzen Ansicht, solange eine Gruppe betreten ist — dieselbe visuelle Sprache wie Vectorworks' "Ansichtsbereich"- @@ -3190,7 +3224,8 @@ body { } .pen-color-popover { padding: 8px; - max-width: 220px; + /* Breit genug für 12 Swatches pro Reihe: 12*20 + 11*3 = 273px + 2*8 Padding. */ + max-width: 292px; } /* Kopfzeile im Popover: Frei/Stift-Umschalter links, getipptes Feld (Stiftnummer bzw. #Hex) rechts davon. */ @@ -3214,15 +3249,21 @@ body { .pen-color-input.mono { font-family: var(--font-mono); } +/* Feste Spaltenzahl UND feste Spaltenbreite (NICHT 1fr): mit `1fr` verteilt + sich der Leerraum je nach Spaltenzahl unterschiedlich, der Swatch-Abstand + wirkte dann von Bank zu Bank ungleich; mit `auto-fill` schwankte zusätzlich + die Spaltenzahl je nach verfügbarer Breite. Jetzt gilt überall dasselbe + Raster: genau 12 Swatches pro Reihe, Abstand immer exakt `gap` (einfache + Palette/Tango/Material/RAL/eigene/Stift-Raster sehen identisch aus). */ .pen-color-grid { display: grid; - grid-template-columns: repeat(8, 1fr); + grid-template-columns: repeat(12, 20px); gap: 3px; max-height: 240px; overflow-y: auto; -} -.pen-color-grid-pens { - grid-template-columns: repeat(10, 1fr); + /* Eigener Scroll-Kontext: das Popover selbst wächst nicht mit, lange + Paletten (RAL: 168 Farben) scrollen hier drin. */ + overscroll-behavior: contain; } .pen-color-cell { position: relative; @@ -3249,26 +3290,228 @@ body { pointer-events: none; line-height: 1; } -.pen-color-custom { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - margin-top: 8px; - padding-top: 8px; - border-top: 1px solid var(--border); - font-size: 11px; +/* Hinweiszeile unter der RAL-Palette (Näherungswerte, s. model/color.ts). */ +.pen-color-hint { + margin-top: 6px; + font-size: 10px; + line-height: 1.35; color: var(--muted); } -.pen-color-custom input[type="color"] { - width: 24px; - height: 20px; - border: 1px solid var(--border); - border-radius: 4px; - padding: 0; - cursor: pointer; + +/* ── FreeColorPicker (ui/FreeColorPicker.tsx) — Paletten-Umschalter + Mischer ── */ +.free-color-picker { + display: flex; + flex-direction: column; + gap: 8px; } +/* ── ColorMixer (ui/ColorMixer.tsx) — RGB/CMYK-Kanal-Slider ─────────────── */ +.color-mixer { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 8px; + border-top: 1px solid var(--border); +} +.color-mixer-head { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 2px; + /* Notausgang: passt die Modell-Leiste neben die Vorschau nicht mehr, + rutscht sie auf eine eigene Zeile statt überzulaufen. */ + flex-wrap: wrap; +} + +/* Im Farbwahl-Popover ist der Platz eng (292px): die Segment-Pills + (Bank-Leiste oben, Modell-Leiste im Mischer) bekommen dort weniger + Innenabstand als in den Ressourcen-Tabs, wo Breite kein Thema ist — + sonst passen fünf Modelle (Spektrum/RGB/CMYK/HSL/HSV) nicht in eine Zeile. */ +.pen-color-popover .res-seg { + display: flex; + flex-wrap: wrap; + max-width: 100%; +} +.pen-color-popover .res-seg-btn { + padding: 4px 8px; + letter-spacing: 0; +} +/* Live-Vorschau der aktuell im Mischer eingestellten Farbe — ohne sie sieht + man beim Schieben der Regler nur Zahlen, keine Farbe (Nutzer-Wunsch). */ +.color-mixer-preview { + flex: none; + width: 22px; + height: 22px; + border-radius: 5px; + border: 1px solid var(--border); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.18); +} +.color-mixer-row { + display: grid; + grid-template-columns: 14px 1fr 40px; + align-items: center; + gap: 6px; +} +.color-mixer-label { + font-size: 10px; + font-weight: 600; + color: var(--muted); + text-align: center; +} +.color-mixer-row input[type="range"] { + width: 100%; +} +.color-mixer-num { + width: 40px; + padding: 2px 4px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--input); + color: var(--ink); + font-family: var(--font-mono); + font-size: 10.5px; + text-align: center; +} +/* ── Spektrum-Wähler (ui/SpectrumPicker.tsx) ─────────────────────────────── */ +.spectrum-picker { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 2px; +} +/* Fläche: Sättigung (X) × Hellwert (Y) über der vollgesättigten Farbtonfarbe. */ +.spectrum-area { + position: relative; + height: 110px; + border-radius: 6px; + border: 1px solid var(--border); + cursor: crosshair; + touch-action: none; + overflow: hidden; +} +.spectrum-area-white, +.spectrum-area-black { + position: absolute; + inset: 0; + pointer-events: none; +} +.spectrum-area-white { + background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0)); +} +.spectrum-area-black { + background: linear-gradient(to top, #000, rgba(0, 0, 0, 0)); +} +/* Farbton-Regler (voller Farbkreis als Verlauf). */ +.spectrum-hue { + position: relative; + height: 14px; + border-radius: 999px; + border: 1px solid var(--border); + cursor: ew-resize; + touch-action: none; + background: linear-gradient( + to right, + #f00 0%, + #ff0 17%, + #0f0 33%, + #0ff 50%, + #00f 67%, + #f0f 83%, + #f00 100% + ); +} +/* Griff: heller Ring, auf beiden Untergründen sichtbar. */ +.spectrum-handle { + position: absolute; + width: 12px; + height: 12px; + margin: -6px 0 0 -6px; + border-radius: 50%; + border: 2px solid #fff; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.45); + pointer-events: none; +} +.spectrum-handle-hue { + top: 50%; +} +.color-mixer-hint { + margin-top: 2px; + font-size: 10px; + line-height: 1.35; + color: var(--muted); +} + +/* ── Eigene Paletten: „+"-Zelle im Raster (ui/FreeColorPicker.tsx) + Tab + „Paletten" (ui/resourceManager/PalettesTab.tsx) ───────────────────────── */ +/* „+"-Zelle: sieht wie ein Swatch aus, ist aber eine Aktion (aktuelle Farbe + ablegen) — gestrichelter Rand statt Vollfläche macht das sichtbar. */ +.pen-color-cell-add { + background: transparent; + border: 1px dashed var(--border); + color: var(--accent); + font-size: 13px; + line-height: 1; + display: flex; + align-items: center; + justify-content: center; +} +.pen-color-cell-add:hover { + border-color: var(--accent); +} +/* Farbstreifen-Vorschau einer Bank/Palette im Ressourcen-Tab. */ +.palette-row { + display: flex; + align-items: center; + gap: 8px; +} +.palette-strip { + display: inline-flex; + gap: 2px; +} +.palette-strip-dot { + width: 10px; + height: 10px; + border-radius: 2px; + border: 1px solid rgba(0, 0, 0, 0.15); +} +.palette-colors { + display: flex; + flex-direction: column; + gap: 4px; + margin-top: 8px; +} +.palette-color-row { + display: flex; + align-items: center; + gap: 8px; +} +.palette-color-swatch { + flex: none; + width: 22px; + height: 22px; + border-radius: 5px; + border: 1px solid var(--border); +} +.palette-color-hex { + flex: 1; + font-size: 11.5px; + color: var(--ink); +} +.res-md-row-meta { + margin-left: auto; + font-size: 10.5px; + color: var(--muted); +} +.res-section-label { + margin: 10px 0 4px; + font-size: 10.5px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--muted); +} +/* Kompakter "+"-Knopf für eine neue Palette, gleiche Grösse wie DeleteButton (.res-delete). */ + /* Linienstil-Vorschau (füllt die Vorschau-Zelle). */ .res-line-preview { width: 100%; @@ -5432,6 +5675,16 @@ body { margin-left: 22px; width: calc(100% - 22px); } +/* Freitext-Massstab im PDF-Export-Dialog, direkt unter dem Preset-Dropdown — + `.imp-input` ist sonst für Checkbox-eingerückte Felder gedacht (22px + margin-left), hier ohne Einrückung. */ +.imp-scale-custom { + margin-top: 6px; +} +.imp-scale-custom .imp-input { + margin-left: 0; + width: 100%; +} .imp-note, .imp-warn, .imp-dwg-hint { @@ -5782,6 +6035,128 @@ body { flex: 1; } +/* Befehls-Kürzel-Remap-Sektion (Einstellungen). */ +.settings-alias-remap { + display: flex; + flex-direction: column; + gap: 8px; +} +.settings-alias-list { + display: flex; + flex-direction: column; + gap: 6px; +} +.settings-alias-row { + display: flex; + align-items: center; + gap: 8px; +} +.settings-alias-row .settings-select { + flex: 1; +} +.settings-alias-key { + font-family: var(--mono, ui-monospace, monospace); + font-weight: 600; + min-width: 3ch; + color: var(--ink); +} +.settings-alias-arrow { + color: var(--muted); +} +.settings-alias-key-input { + width: 90px; +} +.settings-alias-new { + padding-top: 6px; + border-top: 1px solid var(--line); +} + +/* Tab-Leiste im Einstellungs-Dialog — gleiche Pillen-Konvention wie .res-tabs. */ +.settings-tabs { + display: flex; + gap: 2px; + padding: 10px 16px 0; + flex: 0 0 auto; + border-bottom: 1px solid var(--line); +} +.settings-tab-btn { + border: none; + background: transparent; + color: var(--muted); + font-family: inherit; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.02em; + padding: 7px 14px; + border-radius: 7px; + cursor: pointer; + transition: background 0.14s, color 0.14s; +} +.settings-tab-btn:hover { + color: var(--ink-2); +} +.settings-tab-btn.active { + background: var(--accent-dim); + color: var(--ink); +} + +/* Tastenkombinations-Remap-Sektion (Einstellungen → Tastenkürzel). */ +.settings-shortcut-remap { + display: flex; + flex-direction: column; + gap: 10px; +} +.settings-shortcut-category + .settings-shortcut-category { + margin-top: 4px; + padding-top: 10px; + border-top: 1px solid var(--line); +} +.settings-shortcut-category-title { + font-size: 11px; + font-weight: 700; + letter-spacing: 0.03em; + text-transform: uppercase; + color: var(--muted); + margin-bottom: 6px; +} +.settings-shortcut-row { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + padding: 4px 0; +} +.settings-shortcut-label { + flex: 1; + min-width: 140px; + color: var(--ink); +} +.settings-shortcut-combo { + font-family: var(--mono, ui-monospace, monospace); + font-weight: 600; + min-width: 8ch; + text-align: center; + padding: 3px 8px; + border-radius: 6px; + background: var(--field-bg); + color: var(--ink); +} +.settings-shortcut-combo.recording { + background: var(--accent-dim); + color: var(--accent); + animation: settings-shortcut-pulse 1s ease-in-out infinite; +} +@keyframes settings-shortcut-pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.55; } +} +.settings-shortcut-row .imp-warn { + flex-basis: 100%; + display: flex; + align-items: center; + gap: 8px; +} + /* ── App-weites Drop-Feedback ────────────────────────────────────────────── Dezenter Rahmen + Hinweis, solange eine Datei über die App gezogen wird. */ .drop-feedback { @@ -6364,7 +6739,11 @@ body { background: var(--input); color: var(--ink); font-size: 13px; - font-family: var(--font); + /* NICHT --font (App-UI-Schrift) — RichTextEditor bearbeitet immer + GEZEICHNETEN Planinhalt (Text/Textspalte, Raum-Stempel), der mit + --font-ui gerendert/exportiert wird; dieselbe Schrift hier verhindert + einen Ascent-/Zeilenabstand-Versatz zwischen Editor und Ergebnis. */ + font-family: var(--font-ui); line-height: 1.55; outline: none; overflow-y: auto; @@ -7092,9 +7471,12 @@ body { } /* Inline-Text-Editor DIREKT auf dem Blatt (kein schwebendes Fenster) — weisser - Rahmen wie Papier, blauer Rand während der Bearbeitung. `transform: scale()` - (inline, s. LayoutSheet.tsx) bringt die feste 12-pt-Basisgrösse des - RichTextEditor auf die Schriftgrösse der Annotation beim aktuellen Zoom. */ + Rahmen wie Papier, blauer Rand während der Bearbeitung. WYSIWYG: Schrift- + grösse UND Feldhöhe der Textfläche folgen dem echten Blatt-Zoom über + `--rt-font-size`/`--rt-min-height` (inline von LayoutSheet.tsx gesetzt) — + NUR die Textfläche, NICHT die Toolbar (dasselbe Muster wie + .planview-inline-text, s. dort; ersetzt das vorige `transform:scale()` auf + die GANZE Box, das die Toolbar beim Reinzoomen mit aufblies). */ .layout-sheet-inline-text { position: absolute; z-index: 7; @@ -7104,10 +7486,57 @@ body { } .layout-sheet-inline-text .rt-editor { min-height: inherit; + /* Toolbar verlässt den Fluss (s. .rt-toolbar unten) — nur noch die + Textfläche bleibt im normalen Fluss, damit ihre Oberkante GENAU an der + positionierten Box-Oberkante liegt (= Zeilenanfang der Annotation). + `overflow:visible` (Basisregel setzt `hidden`), sonst würde die frei + schwebende Toolbar oben abgeschnitten. `border:none` (Basisregel: 1px) — + jeder Rahmen/jedes Padding auf `.rt-editor`/`.rt-surface` verschiebt den + sichtbaren Text nach rechts/unten relativ zur positionierten Ecke (Bug- + Meldung "Sprung nach rechts oben"); die blaue `outline` auf + `.layout-sheet-inline-text` selbst übernimmt weiterhin die visuelle + Rahmen-Anzeige (outline verschiebt den Inhalt NICHT, da ausserhalb der + Box gezeichnet). */ + display: block; + overflow: visible; + border: none; + /* s. .planview-inline-text .rt-editor — explizite Breite gegen "Wort läuft + aus der Fläche raus statt umzubrechen" (die Aussen-Box hat eine feste + `width` per Inline-Style, aber ohne diese Zeile war das für lange, + leerzeichenlose Wörter nicht garantiert). */ + width: 100%; + box-sizing: border-box; +} +/* REGRESSION-Fix "Editor ist tiefer als der Text": vorher stand die Toolbar + IM normalen Fluss ÜBER der Textfläche (column-flex in .rt-editor) — ihre + feste, zoomunabhängige Höhe (~38px: Padding+Button+Rahmen) schob die + Fläche um diesen Betrag nach unten, während die Positionierung (JS) nur + mit EINER Zeilenhöhe Abstand zur Baseline rechnete. Bei üblichem Zoom ist + eine Zeilenhöhe kleiner als die Toolbar-Höhe → die Fläche landete UNTER + dem eigentlichen Text. Jetzt schwebt die Toolbar frei OBERHALB der Box, + ausserhalb ihres Flusses — sie verschiebt die Textfläche nicht mehr. */ +.layout-sheet-inline-text .rt-toolbar { + position: absolute; + left: 0; + right: 0; + bottom: 100%; + margin-bottom: 4px; + border: 1px solid var(--border); + border-radius: 6px; + box-shadow: var(--shadow-1); } .layout-sheet-inline-text .rt-surface { - min-height: 1.4em; - padding: 2px 4px; + font-size: var(--rt-font-size, 16px); + line-height: 1.25; /* deckt sich mit primitives.tsx "drawingText" (fontSize*1.25) */ + min-height: var(--rt-min-height, 1.4em); + padding: 0; /* kein Padding — verschiebt sonst den Text relativ zur Anker-Ecke */ + /* s. .planview-inline-text .rt-surface — harter Umbruch auch mitten im + Wort statt Überlauf, plus Sicherheitsnetz gegen intrinsische + Mindestbreite. */ + width: 100%; + box-sizing: border-box; + overflow-wrap: anywhere; + min-width: 0; } /* Inline-Text-Editor auf der 2D-Zeichenfläche (PlanView) — dasselbe Prinzip @@ -7128,18 +7557,60 @@ body { } .planview-inline-text .rt-editor { min-height: inherit; + /* s. .layout-sheet-inline-text .rt-editor — Toolbar verlässt den Fluss, + damit die Textfläche exakt an der positionierten Box-Oberkante beginnt; + `border:none` (Basisregel: 1px), sonst Text-Versatz nach rechts/unten + (Bug-Meldung "Sprung nach rechts oben") — die blaue `outline` auf + `.planview-inline-text` übernimmt die Rahmen-Anzeige. `width:100%` + + `box-sizing:border-box` EXPLIZIT (nicht nur aufs Block-Fill verlassen) — + Bug-Meldung "Wort endet nicht im Feld, läuft einfach raus": die + Aussen-Box (`.planview-inline-text`) hat eine feste `width` (inline + style, aus `wrapWidth`), aber ohne eine explizite Breite HIER konnte ein + einzelnes, sehr langes (leerzeichenloses) Wort die Fläche aufziehen statt + umzubrechen. */ + display: block; + overflow: visible; + border: none; + width: 100%; + box-sizing: border-box; +} +/* REGRESSION-Fix "Editor ist tiefer als der Text" — s. ausführlicher + Kommentar bei .layout-sheet-inline-text .rt-toolbar (identischer Bug, + identischer Fix): die Toolbar schwebt jetzt frei OBERHALB der Textfläche, + ausserhalb ihres Flusses, statt sie nach unten zu schieben. */ +.planview-inline-text .rt-toolbar { + position: absolute; + left: 0; + right: 0; + bottom: 100%; + margin-bottom: 4px; + border: 1px solid var(--border); + border-radius: 6px; + box-shadow: var(--shadow-1); } /* WYSIWYG: die Schriftgrösse UND die Feldhöhe der Textfläche folgen dem echten Zoom (--rt-font-size/--rt-min-height, inline von PlanView.tsx gesetzt, per CSS-Var-Vererbung bis hierher durchgereicht) — NUR die - Textfläche, NICHT die Toolbar (.rt-toolbar bleibt bei ihrer normalen, - immer bedienbaren Grösse). So sieht der getippte Text wie der später - gerenderte aus, ohne dass Buttons/Dropdowns beim Reinzoomen riesig werden - (der vorige Bug mit transform:scale() auf die GANZE Box). */ + Textfläche, NICHT die Toolbar (bleibt bei ihrer normalen, immer + bedienbaren Grösse). `line-height:1.25` deckt sich mit primitives.tsx + "drawingText" (fontSize*1.25) — Basisregel (1.55) würde die Baseline der + ersten Zeile spürbar tiefer setzen als im späteren gerenderten Text. */ .planview-inline-text .rt-surface { font-size: var(--rt-font-size, 13px); + line-height: 1.25; min-height: var(--rt-min-height, 1.4em); - padding: 2px 4px; + padding: 0; /* kein Padding — verschiebt sonst den Text relativ zur Anker-Ecke */ + /* s. .rt-editor oben — dieselbe explizite Breite + harter Umbruch, auch + mitten im Wort, statt aus der Fläche hinauszulaufen (`overflow-wrap: + anywhere` ist die moderne, verlässlichere Variante von `word-break: + break-word` aus der Basisregel; beide zusammen sind robuster als eine + allein). `min-width:0`: Sicherheitsnetz gegen intrinsische Mindestbreite + (verhindert sonst in machen Layout-Kontexten das Schrumpfen unter die + Inhaltsbreite eines einzelnen langen Worts). */ + width: 100%; + box-sizing: border-box; + overflow-wrap: anywhere; + min-width: 0; } /* Text-Werkzeug ohne Spaltenbreite: kein Wortumbruch — die Box wächst in der Breite mit dem Inhalt (Enter erzeugt trotzdem weitere Zeilen), statt am diff --git a/src/text/RichTextEditor.tsx b/src/text/RichTextEditor.tsx index 78547ed..1523b1f 100644 --- a/src/text/RichTextEditor.tsx +++ b/src/text/RichTextEditor.tsx @@ -37,6 +37,16 @@ export interface RichTextEditorProps { onChange: (doc: RichTextDoc) => void; presets?: TextStylePreset[]; autoFocus?: boolean; + /** + * "pt" (Default) — absolute Schriftgrösse, passend für ein schwebendes + * Dialogfenster ohne Zoom-Bezug (TextEditorDialog). "em" — Grösse relativ + * zur geerbten Schriftgrösse des `.rt-surface`-Containers: für die beiden + * Inline-Editoren AUF der Zeichenfläche/dem Blatt (PlanView/LayoutSheet), + * die die Basisgrösse selbst per CSS-Variable aus dem echten Zoom setzen — + * mit "pt" hätte jeder Run diese Vorgabe per Inline-Style überschrieben und + * beim Zoomen nie mitskaliert. S. `renderHtml.ts` `runCssProps`. + */ + sizeUnit?: "pt" | "em"; } // ── DOM ↔ Modell-Offset-Übersetzung ───────────────────────────────────────── @@ -377,6 +387,7 @@ export function RichTextEditor({ onChange, presets, autoFocus, + sizeUnit = "pt", }: RichTextEditorProps): JSX.Element { const editorRef = useRef(null); // Letzter in innerHTML geschriebener serialisierter Zustand — verhindert @@ -396,9 +407,10 @@ export function RichTextEditor({ // ── HTML-Renderer ────────────────────────────────────────────────────────── - const renderHtml = useCallback((d: RichTextDoc): string => { - return docToHtml(d, { basePt: 12, color: "var(--ink)" }); - }, []); + const renderHtml = useCallback( + (d: RichTextDoc): string => docToHtml(d, { basePt: 12, color: "var(--ink)", sizeUnit }), + [sizeUnit], + ); /** * Setzt innerHTML direkt. `suppressInput` steuert, ob das daraus folgende @@ -480,61 +492,9 @@ export function RichTextEditor({ setSelRange(currentSel); }, [renderHtml]); - const handleKeyDown = useCallback( - (e: React.KeyboardEvent) => { - const el = editorRef.current; - if (!el) return; - const currentSel = readSelection(el); - - if (e.key === "Enter") { - e.preventDefault(); - const cur = valueRef.current; - const pos = currentSel?.start ?? plainTextFromDoc(cur).length; - const newDoc = insertParagraphBreak(cur, pos); - onChangeRef.current(newDoc); - const newSel: TextRange = { start: pos + 1, end: pos + 1 }; - setEditorHtml(newDoc, newSel, true); - setSelRange(newSel); - return; - } - - if (e.key === "Backspace") { - if (currentSel && currentSel.start !== currentSel.end) { - return; - } - const pos = currentSel?.start ?? 0; - if (pos === 0) return; - e.preventDefault(); - const cur = valueRef.current; - const newDoc = deleteCharAt(cur, pos - 1); - const newPos = pos - 1; - onChangeRef.current(newDoc); - const newSel: TextRange = { start: newPos, end: newPos }; - setEditorHtml(newDoc, newSel, true); - setSelRange(newSel); - return; - } - - if (e.key === "Delete") { - if (currentSel && currentSel.start !== currentSel.end) { - return; - } - const pos = currentSel?.start ?? 0; - const cur = valueRef.current; - const plain = plainTextFromDoc(cur); - if (pos >= plain.length) return; - e.preventDefault(); - const newDoc = deleteCharAt(cur, pos); - onChangeRef.current(newDoc); - const newSel: TextRange = { start: pos, end: pos }; - setEditorHtml(newDoc, newSel, true); - setSelRange(newSel); - } - }, - [setEditorHtml], - ); - // ── Toolbar-Aktionen ─────────────────────────────────────────────────────── + // Vor `handleKeyDown` definiert (nicht nach ihr wie ursprünglich), damit die + // Tastenkürzel unten (Cmd/Ctrl+B/I/U) `handleToggleMark` referenzieren können. const effectiveRange = useCallback((): TextRange => { if (selRange && selRange.start !== selRange.end) return selRange; @@ -586,6 +546,107 @@ export function RichTextEditor({ [effectivePresets, selRange, setEditorHtml], ); + // ── Tastatur/Einfügen ────────────────────────────────────────────────────── + + const handleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + const el = editorRef.current; + if (!el) return; + + // Standard-WYSIWYG-Kürzel (Cmd auf macOS, Ctrl sonst) — bisher fehlten + // sie komplett, nur die Toolbar-Buttons konnten Marks umschalten. + const mod = e.metaKey || e.ctrlKey; + if (mod && !e.altKey) { + const k = e.key.toLowerCase(); + if (k === "b" || k === "i" || k === "u") { + e.preventDefault(); + handleToggleMark(k === "b" ? "bold" : k === "i" ? "italic" : "underline"); + return; + } + } + + const currentSel = readSelection(el); + + if (e.key === "Enter") { + e.preventDefault(); + const cur = valueRef.current; + const pos = currentSel?.start ?? plainTextFromDoc(cur).length; + const newDoc = insertParagraphBreak(cur, pos); + onChangeRef.current(newDoc); + const newSel: TextRange = { start: pos + 1, end: pos + 1 }; + setEditorHtml(newDoc, newSel, true); + setSelRange(newSel); + return; + } + + if (e.key === "Backspace") { + if (currentSel && currentSel.start !== currentSel.end) { + return; + } + const pos = currentSel?.start ?? 0; + if (pos === 0) return; + e.preventDefault(); + const cur = valueRef.current; + const newDoc = deleteCharAt(cur, pos - 1); + const newPos = pos - 1; + onChangeRef.current(newDoc); + const newSel: TextRange = { start: newPos, end: newPos }; + setEditorHtml(newDoc, newSel, true); + setSelRange(newSel); + return; + } + + if (e.key === "Delete") { + if (currentSel && currentSel.start !== currentSel.end) { + return; + } + const pos = currentSel?.start ?? 0; + const cur = valueRef.current; + const plain = plainTextFromDoc(cur); + if (pos >= plain.length) return; + e.preventDefault(); + const newDoc = deleteCharAt(cur, pos); + onChangeRef.current(newDoc); + const newSel: TextRange = { start: pos, end: pos }; + setEditorHtml(newDoc, newSel, true); + setSelRange(newSel); + } + }, + [setEditorHtml, handleToggleMark], + ); + + /** + * Einfügen (Cmd/Ctrl+V bzw. Kontextmenü). Bisher KEIN eigener Handler — der + * Browser hätte das rohe Zwischenablage-HTML (aus Word/Browser kopiert) + * direkt in die contentEditable geschrieben, am Dokumentmodell vorbei; erst + * das NÄCHSTE `onInput` hätte grob wieder repariert (nur Reintext-Diff, + * s. `rebuildDocFromText`) — mit Risiko kaputter Absatzgrenzen bei + * mehrzeiligem HTML-Paste (fremde `
`-Verschachtelung passt nicht zur + * "ein `
` = ein Absatz"-Annahme von `editorInnerText`). Bewusst NUR + * Reintext einfügen (`text/plain`) statt fremdes Markup zu übernehmen — der + * eingefügte Text erbt die Marks der Umgebung, wie eingetippter Text auch + * (über denselben Zeichen-Diff-Pfad wie `handleInput`). + */ + const handlePaste = useCallback((e: React.ClipboardEvent) => { + e.preventDefault(); + const text = e.clipboardData.getData("text/plain").replace(/\r\n?/g, "\n"); + if (!text) return; + const el = editorRef.current; + if (!el) return; + const cur = valueRef.current; + const plain = plainTextFromDoc(cur); + const sel = readSelection(el) ?? { start: plain.length, end: plain.length }; + const start = Math.max(0, Math.min(sel.start, sel.end)); + const end = Math.max(sel.start, sel.end); + const newPlain = plain.slice(0, start) + text + plain.slice(end); + const newDoc = rebuildDocFromText(cur, newPlain); + onChangeRef.current(newDoc); + const newPos = start + text.length; + const newSel: TextRange = { start: newPos, end: newPos }; + setEditorHtml(newDoc, newSel, true); + setSelRange(newSel); + }, [setEditorHtml]); + // ── Toolbar-Zustand berechnen ────────────────────────────────────────────── const queryRange: TextRange = @@ -613,7 +674,7 @@ export function RichTextEditor({
`; - const inner = p.runs.map((r) => runToHtmlSpan(r, basePt, color)).join(""); + const inner = p.runs.map((r) => runToHtmlSpan(r, basePt, sizeUnit, color)).join(""); return `${inner}
`; } -function runToHtmlSpan(run: TextRun, basePt: number, color?: string): string { - const css = runCssProps(run.marks, basePt); +function runToHtmlSpan(run: TextRun, basePt: number, sizeUnit: "pt" | "em", color?: string): string { + const css = runCssProps(run.marks, basePt, sizeUnit); if (color && !css["color"]) css["color"] = color; const style = cssPropsToString(css); const text = escapeText(run.text) || ""; diff --git a/src/text/textFrame.test.ts b/src/text/textFrame.test.ts new file mode 100644 index 0000000..0cff6c2 --- /dev/null +++ b/src/text/textFrame.test.ts @@ -0,0 +1,83 @@ +// `textFrameCorners` liefert den geschätzten Rahmen (Modell-Meter) eines +// gezeichneten Textes — Grundlage für den Auswahl-Rahmen im Grundriss +// (PlanView.tsx) UND die Eckpunkt-Griffe einer Textspalte (projectSlice.ts +// `drawingVertices`/`moveGrip`). Reiner Helfer, kein React/DOM nötig. + +import { describe, it, expect } from "vitest"; +import { textFrameCorners, type TextFrameInput } from "./textFrame"; +import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "./fontMetrics"; + +// Kein DOM im Testlauf (vitest.config.ts: environment "node") → `document` ist +// nicht definiert, `contentFontBaselineFromTop` fängt das ab und liefert den +// dokumentierten Fallback-Wert — hier explizit ausgelesen statt hart codiert, +// damit der Test bei einer Anpassung des Fallbacks nicht bricht. +const BASELINE_FROM_TOP = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); + +function textInput(overrides: Partial): TextFrameInput { + return { + at: { x: 0, y: 0 }, + text: "Hallo", + heightM: 0.2, + angle: 0, + ...overrides, + }; +} + +describe("textFrameCorners", () => { + it("einzeilig, keine Rotation: Rahmen sitzt oberhalb der Baseline (Ascent-Näherung × heightM)", () => { + const p = textInput({ text: "Hallo" }); + const corners = textFrameCorners(p); + expect(corners).toHaveLength(4); + const ys = corners.map((c) => c.y); + const top = 0.2 * BASELINE_FROM_TOP; + expect(Math.max(...ys)).toBeCloseTo(top, 9); + expect(Math.min(...ys)).toBeCloseTo(top - 0.2 * TEXT_LINE_HEIGHT_MULT, 9); // unten = oben - EINE Zeilenhöhe + }); + + it("Breite wächst mit der Zeichenzahl (längerer Text → breiterer Rahmen)", () => { + const short = textFrameCorners(textInput({ text: "Hi" })); + const long = textFrameCorners(textInput({ text: "Ein deutlich längerer Text" })); + const widthOf = (c: { x: number; y: number }[]) => + Math.max(...c.map((p) => p.x)) - Math.min(...c.map((p) => p.x)); + expect(widthOf(long)).toBeGreaterThan(widthOf(short)); + }); + + it("gesetzte wrapWidth bestimmt die Breite EXAKT (unabhängig von der Zeichenzahl)", () => { + const p = textInput({ text: "Ein langer Textspalten-Inhalt, der umbricht", wrapWidth: 1.5 }); + const corners = textFrameCorners(p); + const xs = corners.map((c) => c.x); + expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(1.5, 9); + }); + + it("mehrzeiliger Text (wrapWidth erzwingt Umbruch) ergibt eine grössere Höhe als einzeilig", () => { + const oneLine = textFrameCorners(textInput({ text: "kurz", wrapWidth: 5 })); + const wrapped = textFrameCorners( + textInput({ text: "eins zwei drei vier fünf sechs sieben acht neun zehn", wrapWidth: 0.6 }), + ); + const heightOf = (c: { x: number; y: number }[]) => + Math.max(...c.map((p) => p.y)) - Math.min(...c.map((p) => p.y)); + expect(heightOf(wrapped)).toBeGreaterThan(heightOf(oneLine)); + }); + + it("Rotation (angle=90°) dreht den Rahmen exakt um `at`, ohne die Fläche zu ändern", () => { + const p0 = textInput({ text: "Hallo", angle: 0 }); + const p90 = textInput({ text: "Hallo", angle: Math.PI / 2 }); + const c0 = textFrameCorners(p0); + const c90 = textFrameCorners(p90); + // Fläche bleibt gleich (Shoelace-Formel), nur die Orientierung dreht sich. + const area = (pts: { x: number; y: number }[]) => { + let a = 0; + for (let i = 0; i < pts.length; i++) { + const j = (i + 1) % pts.length; + a += pts[i].x * pts[j].y - pts[j].x * pts[i].y; + } + return Math.abs(a) / 2; + }; + expect(area(c90)).toBeCloseTo(area(c0), 9); + // Jede Ecke von c0, um 90° CCW um `at`=(0,0) gedreht, muss in c90 wieder auftauchen. + const rotated0 = c0.map((c) => ({ x: -c.y, y: c.x })); + for (const r of rotated0) { + expect(c90.some((c) => Math.abs(c.x - r.x) < 1e-9 && Math.abs(c.y - r.y) < 1e-9)).toBe(true); + } + }); +}); diff --git a/src/text/textFrame.ts b/src/text/textFrame.ts new file mode 100644 index 0000000..5cdc58e --- /dev/null +++ b/src/text/textFrame.ts @@ -0,0 +1,81 @@ +// Geschätzter Rahmen (Modell-Meter) eines gezeichneten Textes — EINE Quelle +// für sowohl die visuelle Anzeige (PlanView.tsx Auswahl-Rahmen/Inline-Editor- +// Anker) als auch die Eckpunkt-Griffe (state/projectSlice.ts drawingVertices/ +// moveGrip). Reines Modul: kein React, kein DOM zwingend nötig +// (`contentFontBaselineFromTop` fällt ohne Canvas sicher auf einen +// Näherungswert zurück, s. dort) — darf daher auch aus dem Store-Slice +// heraus aufgerufen werden. +// +// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). + +import type { Vec2 } from "../model/types"; +import type { Marks, RichTextDoc } from "./richText"; +import { docFromText } from "./richText"; +import { wrapDocToLines } from "./renderHtml"; +import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "./fontMetrics"; + +/** Minimale Felder, die `textFrameCorners` braucht — sowohl `Primitive` + * ("drawingText", PlanView.tsx) als auch `Drawing2DGeom["text"]` + * (projectSlice.ts) erfüllen das strukturell (Primitive ist ein Superset). */ +export interface TextFrameInput { + at: Vec2; + text: string; + /** Schrifthöhe in Modell-Metern. */ + heightM: number; + /** Drehung in Radiant (CCW im Modell). */ + angle: number; + marks?: Marks; + doc?: RichTextDoc; + /** Spaltenbreite in Modell-Metern (Textspalte); fehlt ⇒ Breite geschätzt. */ + wrapWidth?: number; +} + +/** Geschätzter Zeichenbreite-Faktor je Schriftgrösse — deckt sich mit + * `CHAR_WIDTH_FACTOR` in `renderHtml.ts` (dort nicht exportiert; kein echtes + * Font-Measuring im SVG, reicht aber für Rahmen/Griffe). */ +const TEXT_CHAR_WIDTH_FACTOR = 0.55; + +/** + * Vier Eckpunkte (Modell-Meter, Reihenfolge oben-links · oben-rechts · + * unten-rechts · unten-links VOR Rotation) eines groben Rahmens um einen + * gezeichneten Text. Höhe aus der ECHTEN Zeilenzahl (`wrapDocToLines`, + * dieselbe Umbruch-Logik wie beim Rendern in `primitives.tsx` + * "drawingText"), Breite aus der längsten Zeile geschätzt (oder `wrapWidth`, + * falls gesetzt — dann ist die Spaltenbreite exakt bekannt). `at` ist die + * Baseline-links der ERSTEN Zeile; Rotation um `angle` (CCW, Modell-Radiant) + * um genau diesen Punkt, analog zum SVG-`rotate` beim eigentlichen Rendern. + */ +export function textFrameCorners(p: TextFrameInput): Vec2[] { + const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); + const lineHeight = p.heightM * TEXT_LINE_HEIGHT_MULT; + const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined; + const lines = wrapDocToLines(doc, { + x: 0, + y: 0, + lineHeight, + unitPerPt: 1, + basePt: p.heightM, + ...(wrapWidthUnits ? { wrapWidthUnits } : {}), + }); + const maxLineChars = lines.length + ? Math.max(1, ...lines.map((l) => l.tspans.reduce((n, t) => n + t.text.length, 0))) + : 1; + const width = + wrapWidthUnits ?? Math.max(p.heightM, maxLineChars * p.heightM * TEXT_CHAR_WIDTH_FACTOR); + const height = Math.max(1, lines.length) * lineHeight; + // Baseline → Oberkante erste Zeile: echtes Font-Measuring statt der groben + // "ganzes heightM"-Näherung. + const top = p.heightM * contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); + const local: Vec2[] = [ + { x: 0, y: top }, + { x: width, y: top }, + { x: width, y: top - height }, + { x: 0, y: top - height }, + ]; + const cos = Math.cos(p.angle); + const sin = Math.sin(p.angle); + return local.map((l) => ({ + x: p.at.x + l.x * cos - l.y * sin, + y: p.at.y + l.x * sin + l.y * cos, + })); +} diff --git a/src/tools/curves.test.ts b/src/tools/curves.test.ts index c71281b..6006bc8 100644 --- a/src/tools/curves.test.ts +++ b/src/tools/curves.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { ellipsePts, sampleBezierChain, sampleCatmullRom } from "./curves"; +import { ellipsePts, sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "./curves"; describe("ellipsePts", () => { it("liegt auf der Ellipse (rotation 0): Ost/Nord-Punkte bei rx/ry", () => { @@ -89,3 +89,52 @@ describe("sampleCatmullRom", () => { expect(out.length).toBe(pts.length * 6); }); }); + +describe("sampleUniformBSpline (Kontrollpunkt-/CV-Modus)", () => { + it("weniger als 3 Punkte: Rohpunkte unverändert (Gummiband-Vorschau, wie sampleCatmullRom)", () => { + const pts = [{ x: 0, y: 0 }, { x: 3, y: 4 }]; + expect(sampleUniformBSpline(pts, false, 8)).toEqual(pts); + }); + + it("offen, geklemmt: berührt exakt Start- und Endpunkt", () => { + const pts = [{ x: 0, y: 0 }, { x: 2, y: 5 }, { x: 6, y: 5 }, { x: 8, y: 0 }]; + const out = sampleUniformBSpline(pts, false, 10); + expect(out[0]).toEqual(pts[0]); + const last = out[out.length - 1]; + expect(last.x).toBeCloseTo(8, 9); + expect(last.y).toBeCloseTo(0, 9); + }); + + it("offen, geklemmt: berührt die INNEREN Kontrollpunkte NICHT (Gegensatz zu Catmull-Rom, das interpoliert)", () => { + // Zwei Kontrollpunkte weit ausserhalb der Verbindungslinie Start-Ende — + // eine interpolierende Kurve (Catmull-Rom) würde exakt durch sie + // verlaufen; die B-Spline-Kurve wird nur "angezogen". + const pts = [{ x: 0, y: 0 }, { x: 2, y: 10 }, { x: 6, y: 10 }, { x: 8, y: 0 }]; + const out = sampleUniformBSpline(pts, false, 20); + const touchesInner = out.some( + (p) => Math.hypot(p.x - 2, p.y - 10) < 1e-6 || Math.hypot(p.x - 6, p.y - 10) < 1e-6, + ); + expect(touchesInner).toBe(false); + // Bleibt aber innerhalb der konvexen Hülle der Kontrollpunkte (y ≤ 10). + for (const p of out) expect(p.y).toBeLessThanOrEqual(10 + 1e-9); + }); + + it("zwei effektive Kontrollpunkte (Start/Ende mehrfach dupliziert) ergeben eine echte Gerade", () => { + // Mit 3 kollinearen Punkten bleibt die Kurve (als Kombination kollinearer + // Kontrollpunkte) exakt auf der Verbindungsgeraden. + const pts = [{ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 6, y: 0 }]; + const out = sampleUniformBSpline(pts, false, 8); + for (const p of out) expect(p.y).toBeCloseTo(0, 9); + expect(out[0]).toEqual(pts[0]); + expect(out[out.length - 1]).toEqual(pts[2]); + }); + + it("geschlossen (periodisch): liefert keinen doppelten Schlusspunkt UND berührt keinen der Kontrollpunkte", () => { + const pts = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]; + const out = sampleUniformBSpline(pts, true, 6); + expect(out.length).toBe(pts.length * 6); + for (const cp of pts) { + expect(out.some((p) => Math.hypot(p.x - cp.x, p.y - cp.y) < 1e-6)).toBe(false); + } + }); +}); diff --git a/src/tools/curves.ts b/src/tools/curves.ts index 4cd199f..d7ba907 100644 --- a/src/tools/curves.ts +++ b/src/tools/curves.ts @@ -102,3 +102,55 @@ export function sampleCatmullRom(pts: Vec2[], closed: boolean, segsPerSpan = 16) if (!closed) out.push(pts[pts.length - 1]); return out; } + +/** Punkt auf einem uniformen kubischen B-Spline-Segment (Standard-Basis, 4 Kontrollpunkte). */ +function bsplineSegPoint(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 { + const t2 = t * t; + const t3 = t2 * t; + const b0 = (1 - t) ** 3 / 6; + const b1 = (3 * t3 - 6 * t2 + 4) / 6; + const b2 = (-3 * t3 + 3 * t2 + 3 * t + 1) / 6; + const b3 = t3 / 6; + return { + x: p0.x * b0 + p1.x * b1 + p2.x * b2 + p3.x * b3, + y: p0.y * b0 + p1.y * b1 + p2.y * b2 + p3.y * b3, + }; +} + +/** + * Tessellierte Punkte eines kubischen B-Splines über den KONTROLLPUNKTEN + * `pts` — Gegenstück zu `sampleCatmullRom`: die Kurve verläuft NICHT durch + * die inneren Punkte, sie wird nur von ihnen „gezogen" (Kontrollnetz statt + * Durchgangspunkte, wie CV-Modus in AutoCAD/Rhino). Offen: GEKLEMMT — die + * Kurve berührt exakt `pts[0]`/`pts[n-1]` (Rand-Kontrollpunkte werden intern + * je 2× zusätzlich dupliziert, Multiplizität 3 an beiden Enden — der + * Standard-Trick für kubische B-Splines, ohne eine generische + * Knotenvektor-Auswertung/Cox-de-Boor-Rekursion zu brauchen). Geschlossen: + * periodisch (Kontrollpunkte laufen zyklisch um), die Kurve berührt dann + * KEINEN der Punkte. Mit weniger als 3 Punkten identisches + * Fallback-Verhalten wie `sampleCatmullRom` (Rohpunkte, Gummiband-Vorschau). + */ +export function sampleUniformBSpline(pts: Vec2[], closed: boolean, segsPerSpan = 16): Vec2[] { + if (pts.length < 3) return [...pts]; + const out: Vec2[] = []; + if (closed) { + const n = pts.length; + const at = (i: number) => pts[((i % n) + n) % n]; + for (let i = 0; i < n; i++) { + for (let s = 0; s < segsPerSpan; s++) { + out.push(bsplineSegPoint(at(i - 1), at(i), at(i + 1), at(i + 2), s / segsPerSpan)); + } + } + return out; + } + const last = pts[pts.length - 1]; + const padded = [pts[0], pts[0], ...pts, last, last]; + const spans = padded.length - 3; + for (let i = 0; i < spans; i++) { + for (let s = 0; s < segsPerSpan; s++) { + out.push(bsplineSegPoint(padded[i], padded[i + 1], padded[i + 2], padded[i + 3], s / segsPerSpan)); + } + } + out.push(last); + return out; +} diff --git a/src/tools/hudFormat.test.ts b/src/tools/hudFormat.test.ts new file mode 100644 index 0000000..1566fbf --- /dev/null +++ b/src/tools/hudFormat.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { hudSegments } from "./hudFormat"; + +describe("hudSegments — Cursor-HUD-Formatierung (2D + 3D gemeinsam)", () => { + it("liefert L/W bei length+angleDeg ohne Feld-Zustand", () => { + const segs = hudSegments({ at: { x: 0, y: 0 }, length: 3, angleDeg: 45 }, null); + expect(segs).toEqual([ + { text: "L: 3.000m", active: false, locked: false }, + { text: "W: 45.000°", active: false, locked: false }, + ]); + }); + + it("liefert Δx/Δy, wenn dx+dy gesetzt sind (Rechteck-Werkzeug)", () => { + const segs = hudSegments({ at: { x: 0, y: 0 }, dx: 2, dy: 1.5 }, null); + expect(segs).toEqual([ + { text: "Δx: 2.000m", active: false, locked: false }, + { text: "Δy: 1.500m", active: false, locked: false }, + ]); + }); + + it("fällt auf freien Text zurück (z. B. Radius/Fläche), wenn kein L/W/Δ-Paar vorliegt", () => { + const segs = hudSegments({ at: { x: 0, y: 0 }, text: "r: 1.200m" }, null); + expect(segs).toEqual([{ text: "r: 1.200m", active: false, locked: false }]); + }); + + it("liefert nichts ohne jegliche HUD-Angabe", () => { + expect(hudSegments({ at: { x: 0, y: 0 } }, null)).toEqual([]); + }); + + it("spiegelt den Tab-Feld-Zyklus-Zustand (gelockt/live/aktiv), sobald hudFields gesetzt ist", () => { + const segs = hudSegments( + { at: { x: 0, y: 0 }, length: 3, angleDeg: 45 }, + { + fields: [ + { id: "length", value: 5, locked: true, active: false }, + { id: "angle", value: null, locked: false, active: true }, + ], + typed: "", + }, + ); + expect(segs).toEqual([ + { text: "L: 5.000m", active: false, locked: true }, + { text: "W: 45.000°", active: true, locked: false }, + ]); + }); + + it("zeigt den LIVE getippten Text im aktiven Feld statt des gelockten/live Werts", () => { + const segs = hudSegments( + { at: { x: 0, y: 0 }, length: 3, angleDeg: 45 }, + { + fields: [{ id: "length", value: null, locked: false, active: true }], + typed: "2.5", + }, + ); + expect(segs).toEqual([{ text: "L: 2.5m", active: true, locked: false }]); + }); +}); diff --git a/src/tools/hudFormat.ts b/src/tools/hudFormat.ts new file mode 100644 index 0000000..bf7906a --- /dev/null +++ b/src/tools/hudFormat.ts @@ -0,0 +1,72 @@ +// Reine Text-Formatierung des Cursor-HUDs (L/W- bzw. Δx/Δy-Anzeige, VW-Stil, +// s. `plan/planView/overlays.tsx::DraftHud`) — als eigenes Modul extrahiert, +// damit die 3D-Ansicht (`viewport/Wasm3DViewport.tsx`) exakt dieselbe +// Beschriftung/Rundung/Live-Tipp-Logik zeigt wie der 2D-Plan, statt einer +// eigenen (potenziell abweichenden) Zweitimplementierung. Keine DOM-/SVG- +// Abhängigkeit — reine Werte rein, Segmente raus. + +import type { ToolDraft } from "./types"; + +/** Ein Segment des Cursor-HUDs (z. B. "L: 3.000m"), + Tab-Zyklus-Zustand. */ +export interface HudSeg { + text: string; + active: boolean; + locked: boolean; +} + +/** Tab-Feld-Zyklus-Zustand der Befehlszeile (s. `ui/CommandLine.tsx`). */ +export interface HudFieldsState { + fields: { id: string; value: number | null; locked: boolean; active: boolean }[]; + typed: string; +} + +/** + * Berechnet die anzuzeigenden HUD-Segmente aus `draft.hud` + optionalem + * Tab-Feld-Zyklus-Zustand (`hudFields`, s. `CommandLine`). Mit Feldern + * spiegelt jedes Segment dessen Live-/Lock-/Tipp-Zustand (VW-Verhalten: der + * getippte Text erscheint sofort im aktiven Feld); ohne Felder fällt es auf + * die einfache Δx/Δy- bzw. L/W-Anzeige zurück, zuletzt auf `hud.text`. + * Leeres Array = kein HUD zu zeichnen. + */ +export function hudSegments( + hud: NonNullable, + hudFields: HudFieldsState | null, +): HudSeg[] { + const liveFor = (id: string): number | null => + id === "length" + ? (hud.length ?? null) + : id === "angle" + ? (hud.angleDeg ?? null) + : id === "width" + ? (hud.dx ?? null) + : id === "height" + ? (hud.dy ?? null) + : null; + const labelFor = (id: string): string => + id === "length" ? "L" : id === "angle" ? "W" : id === "width" ? "Δx" : id === "height" ? "Δy" : id; + const segs: HudSeg[] = []; + if (hudFields && hudFields.fields.length > 0) { + for (const f of hudFields.fields) { + const label = labelFor(f.id); + const unit = f.id === "angle" ? "°" : "m"; + const typedHere = f.active && hudFields.typed.trim() !== ""; + const value = typedHere + ? hudFields.typed + : f.value != null + ? f.value.toFixed(3) + : (liveFor(f.id)?.toFixed(3) ?? "—"); + segs.push({ text: `${label}: ${value}${unit}`, active: f.active, locked: f.locked }); + } + return segs; + } + if (hud.dx != null && hud.dy != null) { + segs.push({ text: `Δx: ${hud.dx.toFixed(3)}m`, active: false, locked: false }); + segs.push({ text: `Δy: ${hud.dy.toFixed(3)}m`, active: false, locked: false }); + } else if (hud.length != null && hud.angleDeg != null) { + segs.push({ text: `L: ${hud.length.toFixed(3)}m`, active: false, locked: false }); + segs.push({ text: `W: ${hud.angleDeg.toFixed(3)}°`, active: false, locked: false }); + } else if (hud.text) { + segs.push({ text: hud.text, active: false, locked: false }); + } + return segs; +} diff --git a/src/tools/snapping.test.ts b/src/tools/snapping.test.ts index 4b9e090..ec2402d 100644 --- a/src/tools/snapping.test.ts +++ b/src/tools/snapping.test.ts @@ -12,7 +12,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { computeSnap, snapCommonAngle, wallLayerBoundarySegments } from "./snapping"; import { DEFAULT_SNAP } from "./types"; -import type { Drawing2D, Project, Vec2, Wall } from "../model/types"; +import type { Ceiling, Column, Drawing2D, Project, Roof, Room, Stair, Vec2, Wall } from "../model/types"; /** Minimalprojekt mit einer dreischichtigen Wand (0.1 / 0.15 / 0.2 m). */ function wallProject(wall: Wall): Project { @@ -413,3 +413,297 @@ describe("computeSnap — Teilpunkte (divide) nach Verweilen", () => { expect(result?.kind).not.toBe("divide"); }); }); + +// ── Raum-/Decken-/Dach-/Treppen-/Stützen-Umrisse (bisher komplett blind) ──── + +function bimSnapProject(overrides: Partial): Project { + return { ...drawProject([]), ...overrides }; +} + +function ceiling(outline: Vec2[], openings?: Vec2[][]): Ceiling { + return { id: "c1", type: "ceiling", floorId: "eg", categoryCode: "20", outline, openings, wallTypeId: "wt1" }; +} + +function room(boundary: Vec2[]): Room { + return { id: "r1", type: "room", floorId: "eg", categoryCode: "20", siaCategory: "HNF", name: "R", boundary, color: "#fff" }; +} + +function roof(outline: Vec2[]): Roof { + return { id: "rf1", type: "roof", floorId: "eg", categoryCode: "20", outline, shape: "flach", pitchDeg: 0, overhang: 0.5, ridgeAxis: "x", thickness: 0.3 }; +} + +function straightStair(): Stair { + return { id: "s1", type: "stair", floorId: "eg", categoryCode: "20", shape: "straight", start: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, runLength: 3, width: 1.2, stepCount: 18 }; +} + +function spiralStair(): Stair { + return { + id: "s2", type: "stair", floorId: "eg", categoryCode: "20", shape: "spiral", + start: { x: 1, y: 0 }, dir: { x: 0, y: 1 }, runLength: 0, width: 1, stepCount: 12, + center: { x: 0, y: 0 }, radius: 1, sweep: 270, + }; +} + +function rectColumn(): Column { + return { id: "col1", type: "column", floorId: "eg", categoryCode: "20", position: { x: 5, y: 5 }, profile: { kind: "rect", width: 0.4, depth: 0.4 }, rotation: 0, height: 2.6 }; +} + +function roundColumn(): Column { + return { id: "col2", type: "column", floorId: "eg", categoryCode: "20", position: { x: -3, y: -3 }, profile: { kind: "round", radius: 0.25 }, rotation: 0, height: 2.6 }; +} + +describe("computeSnap — Raum-/Decken-/Dach-Umriss (Endpunkt/Kante)", () => { + it("fängt eine Raum-Ecke", () => { + const p = bimSnapProject({ rooms: [room([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }])] }); + const r = snapAt(p, { x: 4.02, y: 0.01 }); + expect(r?.kind).toBe("endpoint"); + expect(r!.point).toEqual({ x: 4, y: 0 }); + }); + + it("fängt den Lotfusspunkt auf einer Raumkante (onEdge)", () => { + const p = bimSnapProject({ rooms: [room([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }])] }); + // x=1.3 bewusst NICHT der Kantenmittelpunkt (x=2, sonst gewönne "midpoint"). + const r = snapAt(p, { x: 1.3, y: 0.02 }); + expect(r?.kind).toBe("onEdge"); + expect(r!.point.x).toBeCloseTo(1.3, 6); + expect(r!.point.y).toBeCloseTo(0, 6); + }); + + it("fängt eine Decken-Ecke UND eine Aussparungs-Ecke", () => { + const p = bimSnapProject({ + ceilings: [ceiling([{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }], [[{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]])], + }); + const outer = snapAt(p, { x: 4.02, y: 0.01 }); + expect(outer?.point).toEqual({ x: 4, y: 0 }); + const hole = snapAt(p, { x: 1.98, y: 1.01 }); + expect(hole?.point).toEqual({ x: 2, y: 1 }); + }); + + it("fängt eine Dach-Ecke", () => { + const p = bimSnapProject({ roofs: [roof([{ x: 0, y: 0 }, { x: 6, y: 0 }, { x: 6, y: 8 }, { x: 0, y: 8 }])] }); + const r = snapAt(p, { x: 0.02, y: 8.01 }); + expect(r?.point).toEqual({ x: 0, y: 8 }); + }); +}); + +describe("computeSnap — Treppen-Umriss", () => { + it("fängt eine Ecke einer geraden Treppe", () => { + const p = bimSnapProject({ stairs: [straightStair()] }); + // Lauf 3m × Breite 1.2m entlang +x ab (0,0), mittig referenziert → Ecke bei (3,0.6). + const r = snapAt(p, { x: 3.01, y: 0.59 }); + expect(r?.kind).toBe("endpoint"); + expect(r!.point.x).toBeCloseTo(3, 6); + expect(r!.point.y).toBeCloseTo(0.6, 6); + }); + + it("fängt das Zentrum einer Wendeltreppe (center aktiv)", () => { + const p = bimSnapProject({ stairs: [spiralStair()] }); + // intersection aus: die beiden radialen Abschlusslinien schneiden sich als + // UNENDLICHE Geraden ebenfalls im Zentrum — hier soll isoliert der + // eigene Kreis-Center-Kandidat (aus `spiral.arcs`) geprüft werden. + const withCenter = { ...DEFAULT_SNAP, center: true, intersection: false }; + const c = snapAt(p, { x: 0.02, y: -0.01 }, withCenter); + expect(c?.kind).toBe("center"); + expect(c!.point).toEqual({ x: 0, y: 0 }); + }); +}); + +describe("computeSnap — Stützen (rechteckig via Kanten, rund via Zentrum)", () => { + it("fängt eine Ecke einer rechteckigen Stütze", () => { + const p = bimSnapProject({ columns: [rectColumn()] }); + const r = snapAt(p, { x: 5.21, y: 5.19 }); + expect(r?.kind).toBe("endpoint"); + expect(r!.point.x).toBeCloseTo(5.2, 6); + expect(r!.point.y).toBeCloseTo(5.2, 6); + }); + + it("fängt das Zentrum einer runden Stütze (center aktiv), keine Vieleck-Ecken", () => { + const p = bimSnapProject({ columns: [roundColumn()] }); + const withCenter = { ...DEFAULT_SNAP, center: true }; + const c = snapAt(p, { x: -2.99, y: -3.01 }, withCenter); + expect(c?.kind).toBe("center"); + expect(c!.point).toEqual({ x: -3, y: -3 }); + }); +}); + +// ── Senkrecht/Tangential/Parallel zu Referenz (Nutzer-Wunsch, s. PENDENZEN) ── +// Alle drei brauchen zwingend einen `lastPoint` — daher hier über einen +// eigenen Helper statt `snapAt` (der `lastPoint` fest auf `null` setzt), und +// mit ansonsten ALLEN Objekt-Snaps aus (isoliert), um Interferenzen mit den +// bereits oben getesteten Fang-Arten auszuschliessen. +const ISOLATED_OFF = { + ...DEFAULT_SNAP, + endpoint: false, + midpoint: false, + intersection: false, + onEdge: false, + center: false, + perpendicular: false, + tangent: false, + parallel: false, + grid: false, + ortho: false, + commonAngles: false, +}; + +function snapFrom( + project: Project, + raw: Vec2, + lastPoint: Vec2 | null, + settings: typeof DEFAULT_SNAP, +) { + return computeSnap({ + raw, + project, + levelId: "eg", + visibleCodes: new Set(["20"]), + settings, + draftPoints: [], + lastPoint, + pxPerMeter: 100, + shift: false, + ctrl: false, + }); +} + +describe("computeSnap — Senkrecht zum letzten Punkt (perpendicular)", () => { + it("fängt den Lotfusspunkt VOM LETZTEN PUNKT aus (nicht vom Cursor)", () => { + const p = drawProject([{ shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }]); + const settings = { ...ISOLATED_OFF, perpendicular: true }; + // lastPoint (2,3) → Lot auf die Linie y=0 liegt bei (2,0); der Cursor muss + // nur NAHE (2,0) sein, nicht selbst auf der Linie. + const r = snapFrom(p, { x: 2.01, y: 0.02 }, { x: 2, y: 3 }, settings); + expect(r?.kind).toBe("perpendicular"); + expect(r!.point.x).toBeCloseTo(2, 6); + expect(r!.point.y).toBeCloseTo(0, 6); + }); + + it("bleibt wirkungslos ohne lastPoint", () => { + const p = drawProject([{ shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }]); + const settings = { ...ISOLATED_OFF, perpendicular: true }; + const r = snapFrom(p, { x: 2.01, y: 0.02 }, null, settings); + expect(r).toBeNull(); + }); +}); + +describe("computeSnap — Tangential an Kreis/Bogen (tangent)", () => { + it("fängt einen der beiden Tangentenpunkte von aussen (rechtwinklig zum Radius)", () => { + const center = { x: 5, y: 0 }; + const r = 2; + const lastPoint = { x: 5, y: 6 }; + const p = drawProject([{ shape: "circle", center, r }]); + const d = Math.hypot(lastPoint.x - center.x, lastPoint.y - center.y); + const thetaCP = Math.atan2(lastPoint.y - center.y, lastPoint.x - center.x); + const angAtC = Math.acos(r / d); + const t1 = { + x: center.x + r * Math.cos(thetaCP + angAtC), + y: center.y + r * Math.sin(thetaCP + angAtC), + }; + const settings = { ...ISOLATED_OFF, tangent: true }; + const result = snapFrom(p, t1, lastPoint, settings); + expect(result?.kind).toBe("tangent"); + expect(result!.point.x).toBeCloseTo(t1.x, 6); + expect(result!.point.y).toBeCloseTo(t1.y, 6); + // Geometrische Gegenprobe: Tangente steht rechtwinklig auf dem Radius. + const toLast = { x: lastPoint.x - result!.point.x, y: lastPoint.y - result!.point.y }; + const toCenter = { x: center.x - result!.point.x, y: center.y - result!.point.y }; + expect(toLast.x * toCenter.x + toLast.y * toCenter.y).toBeCloseTo(0, 6); + }); + + it("bietet keine Tangente an, wenn lastPoint innerhalb des Kreises liegt", () => { + const p = drawProject([{ shape: "circle", center: { x: 0, y: 0 }, r: 2 }]); + const settings = { ...ISOLATED_OFF, tangent: true }; + const r = snapFrom(p, { x: 1, y: 0 }, { x: 0, y: 0 }, settings); + expect(r).toBeNull(); + }); + + it("bietet einen Tangentenpunkt AUSSERHALB der Bogen-Spanne NICHT an", () => { + // Halbkreis 0..180° (a0=0, a1=π): ein von UNTEN (negatives y) angesetzter + // lastPoint hätte seinen Tangentenpunkt ausserhalb dieser Spanne. + const center = { x: 0, y: 0 }; + const r = 1; + const p = drawProject([{ shape: "arc", center, r, a0: 0, a1: Math.PI }]); + const settings = { ...ISOLATED_OFF, tangent: true }; + const lastPoint = { x: 0, y: -5 }; // deutlich unterhalb des Bogens + // Beide Tangentenpunkte einer Kreis-von-unten-Konstruktion liegen im + // UNTEREN Halbkreis (ausserhalb 0..π) — kein Treffer erwartet, egal wo + // der Cursor auf dem (vollen) Kreis steht. + const r1 = snapFrom(p, { x: -0.99, y: -0.14 }, lastPoint, settings); + expect(r1?.kind).not.toBe("tangent"); + }); +}); + +describe("computeSnap — Parallel zu erfasster Referenz (parallel)", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("fängt NICHT parallel, solange die Referenzlinie noch nicht lange genug erfasst wurde", () => { + const p = drawProject([{ shape: "line", a: { x: 0, y: 0 }, b: { x: 9, y: 0 } }]); + const settings = { ...ISOLATED_OFF, parallel: true, hoverDivideDelayMs: 300 }; + const r = snapFrom(p, { x: 3, y: 0.02 }, { x: 1, y: 5 }, settings); + expect(r?.kind).not.toBe("parallel"); + }); + + it("fängt auf der Parallelen DURCH lastPoint, sobald die Referenz erfasst ist", () => { + const p = drawProject([{ shape: "line", a: { x: 0, y: 0 }, b: { x: 9, y: 0 } }]); + const settings = { ...ISOLATED_OFF, parallel: true, hoverDivideDelayMs: 300 }; + const lastPoint = { x: 1, y: 5 }; + const onLine = { x: 3, y: 0.02 }; + // Erfassen: Cursor lange genug auf DERSELBEN Stelle der Referenzlinie + // halten (zwei Aufrufe, wie bei "divide" — der erste verankert nur den + // Verweil-Beginn, erst der zweite NACH Ablauf der Verweilzeit erfasst). + snapFrom(p, onLine, lastPoint, settings); + vi.advanceTimersByTime(350); + snapFrom(p, onLine, lastPoint, settings); + // Jetzt zum eigentlichen Zielbereich bewegen: die Parallele zu y=0 durch + // lastPoint (1,5) ist die Gerade y=5 — der Cursor muss dort fangen (die + // Erfassung bleibt STICKY bestehen), NICHT mehr auf der Referenzlinie + // selbst sein. + const result = snapFrom(p, { x: 6.01, y: 5.02 }, lastPoint, settings); + expect(result?.kind).toBe("parallel"); + // Projektion auf die Parallele (horizontal, durch lastPoint bei y=5): die + // y-Koordinate wird auf 5 eingerastet, die x-Koordinate folgt frei dem + // Cursor (keine Rundung) — daher x bleibt 6.01, nur y wird zu 5. + expect(result!.point.x).toBeCloseTo(6.01, 6); + expect(result!.point.y).toBeCloseTo(5, 6); + }); + + it("bleibt wirkungslos ohne lastPoint (nur die Referenz wäre erfasst)", () => { + const p = drawProject([{ shape: "line", a: { x: 0, y: 0 }, b: { x: 9, y: 0 } }]); + const settings = { ...ISOLATED_OFF, parallel: true, hoverDivideDelayMs: 300 }; + snapFrom(p, { x: 3, y: 0.02 }, null, settings); + vi.advanceTimersByTime(350); + const result = snapFrom(p, { x: 6, y: 5 }, null, settings); + expect(result?.kind).not.toBe("parallel"); + }); +}); + +describe("computeSnap — Spline (fit- vs. control-Modus)", () => { + const pts = [{ x: 0, y: 0 }, { x: 2, y: 10 }, { x: 6, y: 10 }, { x: 8, y: 0 }]; + + it("fit-Modus (Default): fängt AUF dem inneren Wegpunkt (Catmull-Rom interpoliert, taucht als Vertex der Tessellierung auf)", () => { + const p = drawProject([{ shape: "spline", pts, closed: false, mode: "fit" }]); + const r = snapAt(p, { x: 2, y: 10 }); + expect(r?.kind).toBe("endpoint"); + expect(r!.point.x).toBeCloseTo(2, 6); + expect(r!.point.y).toBeCloseTo(10, 6); + }); + + it("control-Modus: fängt NICHT auf dem inneren Kontrollpunkt (B-Spline berührt/nähert ihn nicht — kein endpoint-/onEdge-Treffer)", () => { + const p = drawProject([{ shape: "spline", pts, closed: false, mode: "control" }]); + const r = snapAt(p, { x: 2, y: 10 }); + expect(r?.kind).not.toBe("endpoint"); + expect(r?.kind).not.toBe("onEdge"); + }); + + it("control-Modus: fängt trotzdem auf dem geklemmten Start-/Endpunkt", () => { + const p = drawProject([{ shape: "spline", pts, closed: false, mode: "control" }]); + const r = snapAt(p, { x: 8, y: 0 }); + expect(r?.point.x).toBeCloseTo(8, 6); + expect(r?.point.y).toBeCloseTo(0, 6); + }); +}); diff --git a/src/tools/snapping.ts b/src/tools/snapping.ts index 4629f05..272f70b 100644 --- a/src/tools/snapping.ts +++ b/src/tools/snapping.ts @@ -11,8 +11,10 @@ import { getWallType, wallTypeThickness } from "../model/types"; import { add, leftNormal, lineIntersect, normalize, scale, sub } from "../model/geometry"; import { wallReferenceOffset } from "../model/wall"; import { centroid as roomCentroid } from "../geometry/roomArea"; +import { columnFootprint } from "../geometry/column"; +import { stairOutline } from "../geometry/stair"; import type { SnapKind, SnapResult, SnapSettings } from "./types"; -import { sampleBezierChain, sampleCatmullRom } from "./curves"; +import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "./curves"; const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y); const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); @@ -30,6 +32,9 @@ const PRIORITY: Record = { extension: 0, angle: 0, divide: 3, + perpendicular: 1, + tangent: 1, + parallel: 1, }; export interface SnapInput { @@ -81,6 +86,14 @@ export function wallLayerBoundarySegments(project: Project, wall: Wall): Seg[] { return out; } +/** Kanten eines geschlossenen Polygons (Schlusspunkt nicht dupliziert). */ +function closedPolySegs(pts: Vec2[]): Seg[] { + const segs: Seg[] = []; + for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]); + if (pts.length > 2) segs.push([pts[pts.length - 1], pts[0]]); + return segs; +} + /** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente). */ function collectSegments(input: SnapInput): Seg[] { const segs: Seg[] = []; @@ -90,6 +103,38 @@ function collectSegments(input: SnapInput): Seg[] { segs.push([w.start, w.end]); for (const seg of wallLayerBoundarySegments(input.project, w)) segs.push(seg); } + // Raum-/Decken-/Dach-/Treppen-/Stützen-Umrisse: bisher komplett blind (nur + // der Raum-Stempel-Anker war als Endpunkt fangbar, s. u.) — eine Wand oder + // Bemassung liess sich nicht bündig an eine Raum-/Dachkante setzen. + for (const room of input.project.rooms ?? []) { + if (room.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(room.categoryCode)) continue; + segs.push(...closedPolySegs(room.boundary)); + } + for (const c of input.project.ceilings ?? []) { + if (c.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(c.categoryCode)) continue; + segs.push(...closedPolySegs(c.outline)); + for (const hole of c.openings ?? []) segs.push(...closedPolySegs(hole)); + } + for (const r of input.project.roofs ?? []) { + if (r.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(r.categoryCode)) continue; + segs.push(...closedPolySegs(r.outline)); + } + for (const s of input.project.stairs ?? []) { + if (s.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(s.categoryCode)) continue; + const { polygon, spiral } = stairOutline(s, 0); + if (polygon) segs.push(...closedPolySegs(polygon)); + else if (spiral) for (const line of spiral.lines) segs.push(line); // Innen-/Aussenbögen s. collectCircles + } + for (const col of input.project.columns ?? []) { + if (col.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(col.categoryCode)) continue; + if (col.profile.kind === "rect") segs.push(...closedPolySegs(columnFootprint(col))); + // Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten). + } for (const d of input.project.drawings2d) { if (d.levelId !== input.levelId) continue; if (!input.visibleCodes.has(d.categoryCode)) continue; @@ -109,6 +154,15 @@ function collectSegments(input: SnapInput): Seg[] { ]); } } + else if (g.shape === "ray") { + // Wie xline, aber NUR über `b` hinaus verlängert (Anker `a` bleibt fest). + const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y; + const len = Math.hypot(dx, dy); + if (len > 1e-6) { + const ux = dx / len, uy = dy / len, ext = 1000; + segs.push([g.a, { x: g.b.x + ux * ext, y: g.b.y + uy * ext }]); + } + } else if (g.shape === "polyline") { for (let i = 0; i < g.pts.length - 1; i++) segs.push([g.pts[i], g.pts[i + 1]]); if (g.closed && g.pts.length > 2) segs.push([g.pts[g.pts.length - 1], g.pts[0]]); @@ -121,7 +175,7 @@ function collectSegments(input: SnapInput): Seg[] { for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]); } else if (g.shape === "spline") { const closed = g.closed && g.pts.length > 2; - const pts = sampleCatmullRom(g.pts, closed); + const pts = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed); for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]); if (closed) segs.push([pts[pts.length - 1], pts[0]]); } @@ -141,7 +195,11 @@ interface CircleGeom { arc: { a0: number; a1: number } | null; } -/** Sammelt sichtbare Kreise/Bögen des aktiven Geschosses (aus `drawings2d`). */ +/** + * Sammelt sichtbare Kreise/Bögen des aktiven Geschosses: `drawings2d` + * (circle/arc), runde Stützen (Zentrum/Quadranten statt Vieleck-Näherung) + * und die Innen-/Aussenbögen von Wendeltreppen (s. `stairOutline`). + */ function collectCircles(input: SnapInput): CircleGeom[] { const out: CircleGeom[] = []; for (const d of input.project.drawings2d) { @@ -152,6 +210,22 @@ function collectCircles(input: SnapInput): CircleGeom[] { else if (g.shape === "arc") out.push({ center: g.center, r: g.r, arc: { a0: g.a0, a1: g.a1 } }); } + for (const col of input.project.columns ?? []) { + if (col.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(col.categoryCode)) continue; + if (col.profile.kind === "round") { + out.push({ center: col.position, r: col.profile.radius, arc: null }); + } + } + for (const s of input.project.stairs ?? []) { + if (s.floorId !== input.levelId) continue; + if (!input.visibleCodes.has(s.categoryCode)) continue; + const { spiral } = stairOutline(s, 0); + if (!spiral) continue; + for (const a of spiral.arcs) { + out.push({ center: { x: a.cx, y: a.cy }, r: a.r, arc: { a0: a.a0, a1: a.a1 } }); + } + } return out; } @@ -178,6 +252,18 @@ let dwellSegKey: string | null = null; let dwellSince = 0; let dwellRevealedSeg: Seg | null = null; +/** + * „Erfasste" Parallel-Referenz — bewusst SEPARAT vom obigen `dwellRevealedSeg`: + * "divide" soll seine Teilpunkte NUR zeigen, solange der Cursor tatsächlich + * auf der Linie bleibt (reine Hover-Sichtbarkeitshilfe), aber „parallel" + * braucht die Referenzrichtung gerade dann noch, wenn der Cursor die Linie + * schon längst wieder VERLASSEN hat (Richtung Ziel-Punkt). Wird gesetzt, + * sobald "divide"s Verweil-Erkennung eine Strecke freigibt UND `parallel` + * aktiv ist — bleibt danach bestehen, bis eine ANDERE Strecke neu erfasst + * wird (kein Reset beim blossen Wegbewegen). + */ +let acquiredParallelSeg: Seg | null = null; + const segKey = (seg: Seg): string => `${seg[0].x},${seg[0].y}|${seg[1].x},${seg[1].y}`; @@ -241,12 +327,17 @@ export function computeSnap(input: SnapInput): SnapResult | null { }; const needSegs = - settings.midpoint || settings.intersection || settings.onEdge || settings.endpoint; + settings.midpoint || + settings.intersection || + settings.onEdge || + settings.endpoint || + settings.perpendicular || + settings.parallel; const segs = needSegs ? collectSegments(input) : []; // Teilpunkt-Verweilerkennung: braucht dieselben Strecken wie oben. Ohne sie - // (alle vier Objekt-Snap-Arten aus) bleibt "divide" ebenfalls inaktiv — - // konsistent dazu, dass dann ohnehin keine Linien-bezogenen Snaps gelten. + // (alle Objekt-Snap-Arten aus) bleiben "divide"/"parallel" ebenfalls inaktiv + // — konsistent dazu, dass dann ohnehin keine Linien-bezogenen Snaps gelten. const revealed = updateDwell(raw, segs, settings.hoverDivideDelayMs, tolM); if (revealed) { const [a, b] = revealed; @@ -257,6 +348,44 @@ export function computeSnap(input: SnapInput): SnapResult | null { } } + // parallel: sobald "divide"s Verweil-Erkennung eine Strecke freigibt, + // dieselbe Strecke zusätzlich als STICKY Parallel-Referenz übernehmen (s. + // Kommentar bei `acquiredParallelSeg` — bleibt bestehen, auch wenn der + // Cursor die Linie danach wieder verlässt). + if (settings.parallel && revealed) acquiredParallelSeg = revealed; + + // parallel: die erfasste Referenzstrecke liefert nur die RICHTUNG — der + // Fangpunkt liegt auf der Parallelen DURCH den letzten gesetzten Punkt, an + // der Stelle, die dem Cursor am nächsten ist (Projektion von `raw` auf + // diese Gerade). + if (settings.parallel && input.lastPoint && acquiredParallelSeg) { + const [ra, rb] = acquiredParallelSeg; + const dirX = rb.x - ra.x; + const dirY = rb.y - ra.y; + const dirLen = Math.hypot(dirX, dirY); + if (dirLen > 1e-9) { + const ux = dirX / dirLen; + const uy = dirY / dirLen; + const vx = raw.x - input.lastPoint.x; + const vy = raw.y - input.lastPoint.y; + const t = vx * ux + vy * uy; + consider( + { x: input.lastPoint.x + ux * t, y: input.lastPoint.y + uy * t }, + "parallel", + input.lastPoint, + ); + } + } + + // perpendicular: Lotfusspunkt VOM LETZTEN PUNKT (nicht vom Cursor wie + // "onEdge") auf nahe Strecken — die Strecke lastPoint→Fangpunkt steht im + // rechten Winkel zur Referenz-Strecke. + if (settings.perpendicular && input.lastPoint) { + for (const [a, b] of segs) { + consider(perpFoot(input.lastPoint, a, b), "perpendicular", input.lastPoint); + } + } + // endpoint (Strecken-Endpunkte + Draft-Knoten + Raum-Stempel-Anker). if (settings.endpoint) { for (const [a, b] of segs) { @@ -297,29 +426,51 @@ export function computeSnap(input: SnapInput): SnapResult | null { // Kreis-/Bogen-Snaps: Mittelpunkt + Quadranten (Ost/Nord/West/Süd); bei Bögen // nur die Quadranten IM Bogen-Bereich, plus die beiden Bogen-Endpunkte. Center/ - // Quadrant hängen an der `center`-Einstellung, die Endpunkte an `endpoint`. - if (settings.center || settings.endpoint) { + // Quadrant hängen an der `center`-Einstellung, die Endpunkte an `endpoint`, + // die Tangentenpunkte an `tangent` (+ zwingend `lastPoint`). + if (settings.center || settings.endpoint || settings.tangent) { const TAU = Math.PI * 2; const norm = (x: number) => ((x % TAU) + TAU) % TAU; const onCircle = (c: CircleGeom, ang: number): Vec2 => ({ x: c.center.x + c.r * Math.cos(ang), y: c.center.y + c.r * Math.sin(ang), }); + const inArc = (c: CircleGeom, ang: number): boolean => { + if (!c.arc) return true; + const sweep = norm(c.arc.a1 - c.arc.a0) || TAU; + return norm(ang - c.arc.a0) <= sweep + 1e-9; + }; for (const c of collectCircles(input)) { if (settings.center) { consider(c.center, "center"); // Volle CCW-Spanne (0 ⇒ Vollkreis); Quadrant nur, wenn im Bogen liegt. - const sweep = c.arc ? norm(c.arc.a1 - c.arc.a0) || TAU : TAU; for (let q = 0; q < 4; q++) { const ang = q * (Math.PI / 2); - if (c.arc && norm(ang - c.arc.a0) > sweep + 1e-9) continue; - consider(onCircle(c, ang), "quadrant"); + if (inArc(c, ang)) consider(onCircle(c, ang), "quadrant"); } } if (settings.endpoint && c.arc) { consider(onCircle(c, c.arc.a0), "endpoint"); consider(onCircle(c, c.arc.a1), "endpoint"); } + // Tangente von aussen (lastPoint) an den Kreis: klassische Konstruktion + // — zwei Lösungen, Dreieck center/lastPoint/Tangentenpunkt ist bei T + // rechtwinklig, daher angAtC = acos(r/d) der Winkel zwischen center→ + // lastPoint und center→T. Innerhalb/auf dem Kreis (d ≤ r) gibt es keine + // Tangente von aussen. + if (settings.tangent && input.lastPoint) { + const dx = input.lastPoint.x - c.center.x; + const dy = input.lastPoint.y - c.center.y; + const d = Math.hypot(dx, dy); + if (d > c.r + 1e-9) { + const thetaCP = Math.atan2(dy, dx); + const angAtC = Math.acos(Math.min(1, c.r / d)); + for (const sign of [1, -1]) { + const ang = thetaCP + sign * angAtC; + if (inArc(c, ang)) consider(onCircle(c, ang), "tangent", input.lastPoint); + } + } + } } // Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse // wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr). diff --git a/src/tools/tools.ts b/src/tools/tools.ts index cebbc53..a699162 100644 --- a/src/tools/tools.ts +++ b/src/tools/tools.ts @@ -424,6 +424,19 @@ const xlineTool: Tool = { onCancel: (s) => [s, { draft: null, done: true }], }; +// Strahl: Platzhalter-Werkzeug, gekoppelt an den `ray`-Befehl (wie `xline`, +// aber nur einseitig verlängert). Nicht floorOnly (freies 2D-Element). +const rayTool: Tool = { + id: "ray", + labelKey: "tool.ray", + hintKey: () => "tool.ray.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + const polylineTool: Tool = { id: "polyline", labelKey: "tool.polyline", @@ -660,6 +673,74 @@ const koteTool: Tool = { onCancel: (s) => [s, { draft: null, done: true }], }; +// Detail-/Schnitt-Verweis: Platzhalter-Werkzeug, gekoppelt an den +// `detailref`-Befehl (ein Klick → Verweisblase, Label/Blattverknüpfung +// danach im Attribute-Panel). Freies 2D-Element (nicht floorOnly). +const detailrefTool: Tool = { + id: "detailref", + labelKey: "tool.detailref", + hintKey: () => "tool.detailref.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + +// Massstabsbalken: Platzhalter-Werkzeug, gekoppelt an den `scalebar`-Befehl +// (ein Klick, Segmentlänge/-anzahl per Option). Freies 2D-Element. +const scalebarTool: Tool = { + id: "scalebar", + labelKey: "tool.scalebar", + hintKey: () => "tool.scalebar.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + +// Revisionswolke: Platzhalter-Werkzeug, gekoppelt an den `revcloud`-Befehl +// (Punktfolge → Beulen-Kontur). Freies 2D-Element (nicht floorOnly). +const revcloudTool: Tool = { + id: "revcloud", + labelKey: "tool.revcloud", + hintKey: () => "tool.revcloud.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + +// Punkt-/Knotenmarker: Platzhalter-Werkzeug, gekoppelt an den +// `pointmarker`-Befehl (ein Klick → Kreuz-in-Kreis-Symbol). Freies +// 2D-Element (nicht floorOnly). +const pointmarkerTool: Tool = { + id: "pointmarker", + labelKey: "tool.pointmarker", + hintKey: () => "tool.pointmarker.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + +// Wipeout/Maskenregion: Platzhalter-Werkzeug, gekoppelt an den +// `wipeout`-Befehl (Punktfolge, schliesst automatisch → weisse Maskenfläche). +// Freies 2D-Element (nicht floorOnly). +const wipeoutTool: Tool = { + id: "wipeout", + labelKey: "tool.wipeout", + hintKey: () => "tool.wipeout.hint", + init: () => ({ phase: "idle" }), + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], +}; + // Text: Platzhalter-Werkzeug, gekoppelt an den `text`-Befehl (Ankerpunkt → // getippte Zeile). Wie Kreis/Bogen nicht floorOnly (freies 2D-Element). const textTool: Tool = { @@ -740,6 +821,7 @@ const TOOLS: Record = { room: roomTool, line: lineTool, xline: xlineTool, + ray: rayTool, polyline: polylineTool, rect: rectTool, circle: circleTool, @@ -751,6 +833,11 @@ const TOOLS: Record = { bezier: bezierTool, dimension: dimensionTool, kote: koteTool, + detailref: detailrefTool, + scalebar: scalebarTool, + revcloud: revcloudTool, + pointmarker: pointmarkerTool, + wipeout: wipeoutTool, text: textTool, leader: leaderTool, textpath: textpathTool, diff --git a/src/tools/transform.test.ts b/src/tools/transform.test.ts index 7d52f46..11f8cac 100644 --- a/src/tools/transform.test.ts +++ b/src/tools/transform.test.ts @@ -8,9 +8,9 @@ */ import { describe, it, expect } from "vitest"; -import { commitTransform } from "./transform"; +import { commitTransform, rotateGizmoShapes } from "./transform"; import type { TransformSelection } from "./transform"; -import type { Drawing2D, Project } from "../model/types"; +import type { Ceiling, Drawing2D, ExtrudedSolid, Project, Roof, Room, Stair } from "../model/types"; function project(drawings: Drawing2D[]): Project { return { @@ -122,3 +122,351 @@ describe("commitTransform — Mehrfachauswahl (drawingIds)", () => { expect(next.drawings2d.length).toBe(4); // je EINE Kopie pro Element, nicht zwei für d1 }); }); + +// ── BIM-Elemente (Decke/Dach/Treppe/Raum) ─────────────────────────────────── +// Vorher liefen move/rotate/scale/mirror/array NUR auf Wand/2D/ExtrudedSolid/ +// Stütze (`gatherItems`); Decke/Dach/Treppe/Raum hingen an eigenen, isolierten +// Grip-Bewegungen. Deckt die Erweiterung von `gatherItems`/`commitTransform`. + +function ceiling(id: string, outline: { x: number; y: number }[]): Ceiling { + return { id, type: "ceiling", floorId: "eg", categoryCode: "30", outline, wallTypeId: "wt1" }; +} + +function room(id: string, boundary: { x: number; y: number }[]): Room { + return { + id, + type: "room", + floorId: "eg", + categoryCode: "45", + siaCategory: "HNF", + name: "R", + boundary, + color: "#ffffff", + }; +} + +function roof(id: string, outline: { x: number; y: number }[]): Roof { + return { + id, + type: "roof", + floorId: "eg", + categoryCode: "35", + outline, + shape: "flach", + pitchDeg: 0, + overhang: 0.5, + ridgeAxis: "x", + thickness: 0.3, + }; +} + +function straightStair(id: string): Stair { + return { + id, + type: "stair", + floorId: "eg", + categoryCode: "40", + shape: "straight", + start: { x: 0, y: 0 }, + dir: { x: 1, y: 0 }, + runLength: 3, + width: 1.2, + stepCount: 18, + }; +} + +function bimProject(overrides: Partial): Project { + return { ...project([]), ...overrides }; +} + +describe("commitTransform — Decke/Raum (reine Punkt-Geometrie)", () => { + it("move verschiebt den Deckenumriss", () => { + const p = bimProject({ ceilings: [ceiling("c1", [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }])] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, ceilingIds: ["c1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 5, y: 1 }], "move", 1); + expect(next.ceilings![0].outline[0]).toEqual({ x: 5, y: 1 }); + }); + + it("rotate um 90° dreht Deckenumriss UND Aussparungen", () => { + const p = bimProject({ + ceilings: [ + { + ...ceiling("c1", [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }]), + openings: [[{ x: 1, y: 0 }]], + }, + ], + }); + const sel: TransformSelection = { wallIds: [], drawingId: null, ceilingIds: ["c1"] }; + // Drehpunkt Ursprung, 0°→90°. + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }]; + const next = commitTransform(p, sel, "rotate", pts, "move", 1); + const c = next.ceilings![0]; + expect(c.outline[0].x).toBeCloseTo(0, 6); + expect(c.outline[0].y).toBeCloseTo(1, 6); + expect(c.openings![0][0].x).toBeCloseTo(0, 6); + expect(c.openings![0][0].y).toBeCloseTo(1, 6); + }); + + it("Raum: move nimmt den Stempel-Anker mit", () => { + const r = { ...room("r1", [{ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 3, y: 3 }, { x: 0, y: 3 }]), stampAnchor: { x: 1.5, y: 1.5 } }; + const p = bimProject({ rooms: [r] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, roomIds: ["r1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 2, y: 0 }], "move", 1); + expect(next.rooms![0].stampAnchor).toEqual({ x: 3.5, y: 1.5 }); + }); + + it("copy dupliziert mit neuer ID, Original bleibt", () => { + const p = bimProject({ ceilings: [ceiling("c1", [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }])] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, ceilingIds: ["c1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 1, y: 0 }], "copy", 1); + expect(next.ceilings!.length).toBe(2); + expect(next.ceilings![1].id).not.toBe("c1"); + expect(next.ceilings![0].outline[0]).toEqual({ x: 0, y: 0 }); // Original unverändert + }); +}); + +describe("commitTransform — Dach: Rotate/Mirror ausgenommen (Achsen-Invariante)", () => { + it("move verschiebt den Dachumriss", () => { + const p = bimProject({ roofs: [roof("rf1", [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }])] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, roofIds: ["rf1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 1, y: 1 }], "move", 1); + expect(next.roofs![0].outline[0]).toEqual({ x: 1, y: 1 }); + }); + + it("scale skaliert den Dachumriss", () => { + const p = bimProject({ roofs: [roof("rf1", [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }])] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, roofIds: ["rf1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]; // Faktor 2 + const next = commitTransform(p, sel, "scale", pts, "move", 1); + expect(next.roofs![0].outline[2]).toEqual({ x: 8, y: 8 }); + }); + + it("rotate lässt das Dach UNVERÄNDERT (Umriss ist rechteckig/achsgebunden, ridgeAxis würde sonst falsch)", () => { + const original = roof("rf1", [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]); + const p = bimProject({ roofs: [original] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, roofIds: ["rf1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }]; // 90° + const next = commitTransform(p, sel, "rotate", pts, "move", 1); + expect(next.roofs![0]).toEqual(original); + }); + + it("mirror lässt das Dach ebenfalls UNVERÄNDERT", () => { + const original = roof("rf1", [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]); + const p = bimProject({ roofs: [original] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, roofIds: ["rf1"] }; + const next = commitTransform(p, sel, "mirror", [{ x: 0, y: 0 }, { x: 0, y: 1 }], "move", 1); + expect(next.roofs![0]).toEqual(original); + }); + + it("REGRESSION: Dach bleibt auch dann unverändert, wenn ZUSÄTZLICH eine Wand mitselektiert ist (mode:\"move\")", () => { + // `movesOriginal` (mode:"move") liest ceiling/roof/stair/room-IDs direkt + // aus `sel`, nicht aus dem bereits op-gefilterten `items` — ohne eigene + // Ausnahmeprüfung würde eine gemischte Auswahl (Wand + Dach) das Dach + // trotzdem rotieren/spiegeln, sobald IRGENDein anderes Element die + // `items.length === 0`-Kurzschluss-Rückgabe verhindert. + const original = roof("rf1", [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]); + const wall: import("../model/types").Wall = { + id: "w1", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 1, y: 0 }, + wallTypeId: "wt1", + height: 2.5, + }; + const p = bimProject({ roofs: [original], walls: [wall] }); + const sel: TransformSelection = { wallIds: ["w1"], drawingId: null, roofIds: ["rf1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }]; // 90° + const next = commitTransform(p, sel, "rotate", pts, "move", 1); + expect(next.roofs![0]).toEqual(original); + expect(next.walls[0].end.y).toBeCloseTo(1, 6); // Wand hat sich sehr wohl gedreht + }); +}); + +describe("commitTransform — Treppe (Richtung/Umlaufsinn/Skalierung)", () => { + it("move verschiebt Antritt, Laufrichtung bleibt", () => { + const p = bimProject({ stairs: [straightStair("s1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, stairIds: ["s1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 3, y: 4 }], "move", 1); + const s = next.stairs![0]; + expect(s.start).toEqual({ x: 3, y: 4 }); + expect(s.dir.x).toBeCloseTo(1, 6); + expect(s.dir.y).toBeCloseTo(0, 6); + }); + + it("rotate um 90° dreht die Laufrichtung mit", () => { + const p = bimProject({ stairs: [straightStair("s1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, stairIds: ["s1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }]; // 90°, Drehpunkt = Antritt + const next = commitTransform(p, sel, "rotate", pts, "move", 1); + const s = next.stairs![0]; + expect(s.dir.x).toBeCloseTo(0, 6); + expect(s.dir.y).toBeCloseTo(1, 6); + }); + + it("scale zieht Lauflänge/-breite mit, stepCount (Anzahl) bleibt unberührt", () => { + const p = bimProject({ stairs: [straightStair("s1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, stairIds: ["s1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]; // Faktor 2 + const next = commitTransform(p, sel, "scale", pts, "move", 1); + const s = next.stairs![0]; + expect(s.runLength).toBeCloseTo(6, 6); + expect(s.width).toBeCloseTo(2.4, 6); + expect(s.stepCount).toBe(18); + }); + + it("mirror kippt `turn` (L-Treppe) — Umlaufsinn kehrt um", () => { + const l: Stair = { ...straightStair("s1"), shape: "L", run2Length: 2, turn: 1 }; + const p = bimProject({ stairs: [l] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, stairIds: ["s1"] }; + const next = commitTransform(p, sel, "mirror", [{ x: 0, y: 0 }, { x: 0, y: 1 }], "move", 1); + expect(next.stairs![0].turn).toBe(-1); + }); + + it("rotate lässt `turn` UNVERÄNDERT (orientierungserhaltend)", () => { + const l: Stair = { ...straightStair("s1"), shape: "L", run2Length: 2, turn: 1 }; + const p = bimProject({ stairs: [l] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, stairIds: ["s1"] }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }]; + const next = commitTransform(p, sel, "rotate", pts, "move", 1); + expect(next.stairs![0].turn).toBe(1); + }); +}); + +describe("commitTransform — ExtrudedSolid mit Kreis-Profil (REGRESSION: circle.r skalierte nicht mit)", () => { + function circleSolid(id: string): ExtrudedSolid { + return { + id, + type: "extrudedSolid", + levelId: "eg", + points: [{ x: -1, y: 0 }, { x: 0, y: 1 }, { x: 1, y: 0 }, { x: 0, y: -1 }], // grobe Tessellierung + height: 2, + circle: { center: { x: 0, y: 0 }, r: 1 }, + }; + } + + it("scale zieht sowohl points als auch circle.r mit demselben Faktor", () => { + const p = bimProject({ extrudedSolids: [circleSolid("e1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, extrudedSolidId: "e1" }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 3, y: 0 }]; // Faktor 3 + const next = commitTransform(p, sel, "scale", pts, "move", 1); + const s = next.extrudedSolids![0]; + expect(s.circle!.r).toBeCloseTo(3, 6); + expect(s.points[2]).toEqual({ x: 3, y: 0 }); // (1,0) * 3 + }); + + it("copy-Modus: dieselbe Skalierung gilt auch für die neu erzeugte Kopie", () => { + const p = bimProject({ extrudedSolids: [circleSolid("e1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: null, extrudedSolidId: "e1" }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]; // Faktor 2 + const next = commitTransform(p, sel, "scale", pts, "copy", 1); + expect(next.extrudedSolids!.length).toBe(2); + expect(next.extrudedSolids![0].circle!.r).toBeCloseTo(1, 6); // Original unverändert + expect(next.extrudedSolids![1].circle!.r).toBeCloseTo(2, 6); // Kopie skaliert + }); +}); + +describe("commitTransform — Blockinstanz (REGRESSION: scale skalierte nicht mit)", () => { + function blockInstance(id: string, scale?: number): import("../model/types").Drawing2D { + return { + id, + type: "drawing2d", + levelId: "eg", + categoryCode: "20", + geom: { shape: "block", blockDefId: "b1", at: { x: 0, y: 0 }, rotation: 0, ...(scale !== undefined ? { scale } : {}) }, + }; + } + + it("scale multipliziert das bestehende scale-Feld mit dem Faktor", () => { + const p = bimProject({ drawings2d: [blockInstance("d1", 2)] }); + const sel: TransformSelection = { wallIds: [], drawingId: "d1" }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 3, y: 0 }]; // Faktor 3 + const next = commitTransform(p, sel, "scale", pts, "move", 1); + const g = next.drawings2d[0].geom; + if (g.shape === "block") expect(g.scale).toBeCloseTo(6, 6); // 2 * 3 + }); + + it("fehlendes scale-Feld (Default 1) wird korrekt mit dem Faktor multipliziert", () => { + const p = bimProject({ drawings2d: [blockInstance("d1")] }); + const sel: TransformSelection = { wallIds: [], drawingId: "d1" }; + const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2.5, y: 0 }]; // Faktor 2.5 + const next = commitTransform(p, sel, "scale", pts, "move", 1); + const g = next.drawings2d[0].geom; + if (g.shape === "block") expect(g.scale).toBeCloseTo(2.5, 6); + }); +}); + +describe("commitTransform — Objekt-Sperre (locked) wird respektiert", () => { + const lockedWall: import("../model/types").Wall = { + id: "w-locked", + type: "wall", + floorId: "eg", + categoryCode: "20", + start: { x: 0, y: 0 }, + end: { x: 1, y: 0 }, + wallTypeId: "wt1", + height: 2.5, + locked: true, + }; + const freeWall: import("../model/types").Wall = { ...lockedWall, id: "w-free", locked: false }; + + it("mode:\"move\" lässt eine gesperrte Wand unverändert, eine ungesperrte in derselben Auswahl bewegt sich", () => { + const p = bimProject({ walls: [lockedWall, freeWall] }); + const sel: TransformSelection = { wallIds: ["w-locked", "w-free"], drawingId: null }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 5, y: 5 }], "move", 1); + const w1 = next.walls.find((w) => w.id === "w-locked")!; + const w2 = next.walls.find((w) => w.id === "w-free")!; + expect(w1.start).toEqual({ x: 0, y: 0 }); // unverändert + expect(w2.start).toEqual({ x: 5, y: 5 }); // bewegt + }); + + it("copy-Modus: eine gesperrte Wand wird NICHT kopiert (gatherItems filtert sie schon heraus)", () => { + const p = bimProject({ walls: [lockedWall, freeWall] }); + const sel: TransformSelection = { wallIds: ["w-locked", "w-free"], drawingId: null }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 5, y: 5 }], "copy", 1); + // 2 Originale (unverändert unter copy-Modus, s. movesOriginal) + 1 Kopie + // (nur die ungesperrte Wand) = 3 Wände total. + expect(next.walls).toHaveLength(3); + expect(next.walls.filter((w) => w.start.x === 0 && w.start.y === 0)).toHaveLength(2); // beide Originale + expect(next.walls.filter((w) => w.start.x === 5 && w.start.y === 5)).toHaveLength(1); // nur die Kopie der freien Wand + }); + + it("mode:\"move\" lässt einen gesperrten Raum unverändert, auch bei gemischter Auswahl mit einer Wand (REGRESSION: movesOriginal-Zweig)", () => { + const lockedRoom: Room = { ...room("r1", [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }]), locked: true }; + const p = bimProject({ rooms: [lockedRoom], walls: [freeWall] }); + const sel: TransformSelection = { wallIds: ["w-free"], drawingId: null, roomIds: ["r1"] }; + const next = commitTransform(p, sel, "move", [{ x: 0, y: 0 }, { x: 5, y: 5 }], "move", 1); + expect(next.rooms![0].boundary).toEqual(lockedRoom.boundary); // unverändert + expect(next.walls[0].start).toEqual({ x: 5, y: 5 }); // Wand hat sich sehr wohl bewegt + }); +}); + +describe("rotateGizmoShapes — Dreh-Darstellung (Referenz-/Winkel-Strahl + Radius-Kreis)", () => { + it("liefert Referenz-Strahl, Winkel-Strahl und einen Radius-Kreis aus einzelnen Liniensegmenten", () => { + const shapes = rotateGizmoShapes({ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 0, y: 3 }); + expect(shapes[0]).toEqual({ kind: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 0 } }); + expect(shapes[1]).toEqual({ kind: "line", a: { x: 0, y: 0 }, b: { x: 0, y: 3 } }); + // Kreis: ab Index 2 nur noch "line"-Segmente (KEIN "poly" — s. Dateikommentar: + // ein geschlossenes Polygon würde im 2D-SVG-Overlay gefüllt gerendert). + const circleSegs = shapes.slice(2); + expect(circleSegs.length).toBeGreaterThan(16); + for (const seg of circleSegs) { + expect(seg.kind).toBe("line"); + if (seg.kind === "line") { + expect(Math.hypot(seg.a.x, seg.a.y)).toBeCloseTo(3, 6); + expect(Math.hypot(seg.b.x, seg.b.y)).toBeCloseTo(3, 6); + } + } + // Der Kreis schliesst sich (letztes Segment endet wieder am ersten Punkt). + const last = circleSegs[circleSegs.length - 1]; + const first = circleSegs[0]; + if (last.kind === "line" && first.kind === "line") { + expect(last.b).toEqual(first.a); + } + }); + + it("Zentrum == Referenzpunkt (Radius 0): kein Gizmo, leeres Array", () => { + expect(rotateGizmoShapes({ x: 1, y: 1 }, { x: 1, y: 1 }, { x: 5, y: 5 })).toEqual([]); + }); +}); diff --git a/src/tools/transform.ts b/src/tools/transform.ts index 118a0f3..c871a2d 100644 --- a/src/tools/transform.ts +++ b/src/tools/transform.ts @@ -10,21 +10,27 @@ // die App hält den State und wendet `commitTransform` immutabel an. import type { + Ceiling, Column, Drawing2D, Drawing2DGeom, ExtrudedSolid, Project, + Roof, + Room, + Stair, Vec2, Wall, } from "../model/types"; import { wallTypeThickness } from "../model/types"; import { wallCorners } from "../model/geometry"; import { columnFootprint } from "../geometry/column"; +import { stairOutline } from "../geometry/stair"; import type { DraftShape } from "./types"; import { uniqueId } from "./types"; +import type { CommandSelection } from "../commands/types"; -export type TransformOp = "move" | "rotate" | "mirror"; +export type TransformOp = "move" | "rotate" | "mirror" | "scale"; export type CopyMode = "move" | "copy" | "array" | "distribute"; // U / I / O / P /** Welche Auswahl transformiert wird. */ @@ -42,6 +48,50 @@ export interface TransformSelection { extrudedSolidId?: string | null; /** Gewählte Stütze (Tragwerk); von move/copy/mirror gesetzt. */ columnId?: string | null; + /** Gewählte Decken (Mehrfachauswahl). */ + ceilingIds?: string[]; + /** + * Gewählte Dächer (Mehrfachauswahl). Der Umriss ist geometrisch an die + * Weltachsen gebunden (immer ein Rechteck, First folgt `ridgeAxis` „x"/„y") + * — Rotate/Mirror würden diese Invariante brechen (First bliebe trotz + * gedrehtem Umriss achsparallel stehen). `gatherItems` nimmt Dächer daher + * NUR bei move/scale mit, nicht bei rotate/mirror. + */ + roofIds?: string[]; + /** Gewählte Treppen (Mehrfachauswahl). */ + stairIds?: string[]; + /** Gewählte Räume (Mehrfachauswahl). */ + roomIds?: string[]; +} + +/** Auswahl (Befehlskontext) → TransformSelection (gleiche Form, alle Elementarten). */ +export function toTransformSel(sel: CommandSelection): TransformSelection { + return { + wallIds: sel.wallIds, + drawingId: sel.drawingId, + drawingIds: sel.drawingIds, + extrudedSolidId: sel.extrudedSolidId, + columnId: sel.columnId, + ceilingIds: sel.ceilingIds, + roofIds: sel.roofIds, + stairIds: sel.stairIds, + roomIds: sel.roomIds, + }; +} + +/** Hat die Auswahl überhaupt etwas Transformierbares? */ +export function hasTransformSelection(sel: CommandSelection): boolean { + return ( + sel.wallIds.length > 0 || + sel.drawingId !== null || + (sel.drawingIds?.length ?? 0) > 0 || + !!sel.extrudedSolidId || + !!sel.columnId || + (sel.ceilingIds?.length ?? 0) > 0 || + (sel.roofIds?.length ?? 0) > 0 || + (sel.stairIds?.length ?? 0) > 0 || + (sel.roomIds?.length ?? 0) > 0 + ); } /** Vereinigt `drawingId`/`drawingIds` zu einer eindeutigen ID-Menge (dedupliziert). */ @@ -77,6 +127,14 @@ export function transformFn(op: TransformOp, pts: Vec2[], t: number): (p: Vec2) return { x: c.x + dx * cos - dy * sin, y: c.y + dx * sin + dy * cos }; }; } + if (op === "scale") { + // Gleichmässige Skalierung um pts[0]; der Faktor ist das Längenverhältnis + // Referenz→Ziel (getippter Faktor wird vom Befehl in solche Punkte + // übersetzt). `t` interpoliert für die Vorschau/Reihen-Kopien. + const c = pts[0]; + const f = scaleFactor(pts, t); + return (p) => ({ x: c.x + (p.x - c.x) * f, y: c.y + (p.y - c.y) * f }); + } // mirror: Spiegelung an der Geraden pts[0]→pts[1]. const a = pts[0], b = pts[1]; const dx = b.x - a.x, dy = b.y - a.y; @@ -124,22 +182,74 @@ interface SelColumnItem { kind: "column"; column: Column; } -type AnyItem = SelItem | SelDrawingItem | SelExtrudedItem | SelColumnItem; +interface SelCeilingItem { + kind: "ceiling"; + ceiling: Ceiling; +} +interface SelRoofItem { + kind: "roof"; + roof: Roof; +} +interface SelStairItem { + kind: "stair"; + stair: Stair; +} +interface SelRoomItem { + kind: "room"; + room: Room; +} +type AnyItem = + | SelItem + | SelDrawingItem + | SelExtrudedItem + | SelColumnItem + | SelCeilingItem + | SelRoofItem + | SelStairItem + | SelRoomItem; -function gatherItems(project: Project, sel: TransformSelection): AnyItem[] { +// Dach: s. Doku bei TransformSelection.roofIds — Rotate/Mirror ausgenommen +// (Umriss-Achsen-Invariante). EINZIGE Stelle, die das entscheidet — sowohl +// `gatherItems` als auch der „Original bewegen"-Zweig in `commitTransform` +// (der NICHT über `items` läuft, s. dort) müssen dieselbe Funktion befragen, +// sonst bricht die Ausnahme an einer der beiden Stellen unbemerkt wieder. +function roofTransformAllowed(op: TransformOp): boolean { + return op !== "rotate" && op !== "mirror"; +} + +function gatherItems(project: Project, sel: TransformSelection, op: TransformOp): AnyItem[] { const items: AnyItem[] = []; + // Objekt-Sperre (`locked`, s. state/objectLock.ts): gesperrte Elemente + // bleiben anwählbar, aber move/copy/mirror/rotate/scale/array lassen sie + // unangetastet — dieselbe Semantik wie beim Griff-Ziehen (moveGrip/ + // moveElementBy in projectSlice.ts). const ids = new Set(sel.wallIds); - for (const w of project.walls) if (ids.has(w.id)) items.push({ kind: "wall", wall: w }); + for (const w of project.walls) if (ids.has(w.id) && !w.locked) items.push({ kind: "wall", wall: w }); const drawIds = drawingIdSet(sel); - for (const d of project.drawings2d) if (drawIds.has(d.id)) items.push({ kind: "drawing", drawing: d }); + for (const d of project.drawings2d) + if (drawIds.has(d.id) && !d.locked) items.push({ kind: "drawing", drawing: d }); if (sel.extrudedSolidId) { const s = (project.extrudedSolids ?? []).find((x) => x.id === sel.extrudedSolidId); if (s) items.push({ kind: "extrudedSolid", solid: s }); } if (sel.columnId) { const c = (project.columns ?? []).find((x) => x.id === sel.columnId); - if (c) items.push({ kind: "column", column: c }); + if (c && !c.locked) items.push({ kind: "column", column: c }); } + const ceilingIds = new Set(sel.ceilingIds ?? []); + for (const c of project.ceilings ?? []) + if (ceilingIds.has(c.id) && !c.locked) items.push({ kind: "ceiling", ceiling: c }); + if (roofTransformAllowed(op)) { + const roofIds = new Set(sel.roofIds ?? []); + for (const r of project.roofs ?? []) + if (roofIds.has(r.id) && !r.locked) items.push({ kind: "roof", roof: r }); + } + const stairIds = new Set(sel.stairIds ?? []); + for (const s of project.stairs ?? []) + if (stairIds.has(s.id) && !s.locked) items.push({ kind: "stair", stair: s }); + const roomIds = new Set(sel.roomIds ?? []); + for (const r of project.rooms ?? []) + if (roomIds.has(r.id) && !r.locked) items.push({ kind: "room", room: r }); return items; } @@ -150,6 +260,18 @@ function gatherItems(project: Project, sel: TransformSelection): AnyItem[] { * aktuellen Winkel) mit-transformiert und der neue Winkel daraus gemessen wird * — das ergibt für alle drei Operationen die korrekte neue Ausrichtung. */ +/** + * Erkennt, ob `fn` die Umlauf-Orientierung umkehrt (Spiegelung) — via + * Flächenvorzeichen eines Test-Dreiecks unter `fn` (negativ ⇒ Spiegelung). + * Funktioniert für JEDE Isometrie/Similarity (Move/Rotate/Scale erhalten die + * Orientierung, Mirror kehrt sie um), ohne dass eine Operation ihre Spiegel- + * Eigenschaft explizit markieren müsste. + */ +function reversesOrientation(fn: (p: Vec2) => Vec2): boolean { + const p0 = fn({ x: 0, y: 0 }), p1 = fn({ x: 1, y: 0 }), p2 = fn({ x: 0, y: 1 }); + return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) < 0; +} + function mvColumn(col: Column, fn: (p: Vec2) => Vec2): Column { const base = col.position; const rot = col.rotation ?? 0; @@ -160,24 +282,72 @@ function mvColumn(col: Column, fn: (p: Vec2) => Vec2): Column { } /** Bildet jeden Punkt einer 2D-Zeichengeometrie unter `fn` ab (Move/Mirror/Rotate/Array + Block-Rendering). */ +/** + * Wie {@link mvGeom}, zusätzlich für eine SKALIERUNG: `mvGeom` bildet nur + * PUNKTE ab — Radien, Schrifthöhen und der Bemassungs-Abstand sind aber keine + * Punkte und blieben sonst unverändert stehen (ein Kreis behielte unter einer + * 2×-Skalierung seinen Radius). Diese Funktion zieht die betroffenen + * Grössenfelder um denselben Faktor nach. + * + * Bewusst NICHT angefasst: `bulge` (ein Formverhältnis, skaleninvariant) und + * die Papier-mm-Felder von Bemassung/Linienenden — die beziehen sich auf das + * Blatt, nicht aufs Modell, und dürfen beim Skalieren des Objekts gleich + * bleiben. + */ +/** Skalierungsfaktor eines `op:"scale"`-Punkte-Tripels bei Interpolation `t`. */ +export function scaleFactor(pts: Vec2[], t: number): number { + const c = pts[0]; + const ref = Math.hypot(pts[1].x - c.x, pts[1].y - c.y) || 1; + const tgt = Math.hypot(pts[2].x - c.x, pts[2].y - c.y); + return 1 + (tgt / ref - 1) * t; +} + +export const scaleGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2, f: number): Drawing2DGeom => { + const g = mvGeom(geom, fn); + switch (g.shape) { + case "circle": + return { ...g, r: g.r * f }; + case "arc": + return { ...g, r: g.r * f }; + case "ellipse": + return { ...g, rx: g.rx * f, ry: g.ry * f }; + case "dimension": + // `offset` ist der Normalabstand der Masslinie in Modellmass. + return { ...g, offset: g.offset * f }; + case "text": + return { + ...g, + height: g.height * f, + ...(g.width !== undefined ? { width: g.width * f } : {}), + }; + case "scalebar": + // Segmentlänge ist eine ECHTE Modell-Distanz (kein Papier-mm-Feld wie + // bei Kote/Bemassung) — muss bei einer Modell-Skalierung mitwachsen, + // sonst zeigt der Balken nach dem Skalieren die FALSCHE Distanz an. + return { ...g, segmentLength: g.segmentLength * f }; + case "block": + // Blockinstanz-Skalierung (s. Typ-Kommentar in model/types.ts) — + // ohne diesen Fall wäre der `scale`-Befehl auf eine Blockinstanz ein + // kompletter No-Op (kein Feld zum Multiplizieren). + return { ...g, scale: (g.scale ?? 1) * f }; + default: + return g; + } +}; + export const mvGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom => { switch (geom.shape) { case "line": case "xline": + case "ray": return { ...geom, a: fn(geom.a), b: fn(geom.b) }; case "polyline": { const pts = geom.pts.map(fn); if (!geom.bulge) return { ...geom, pts }; // Bulge-Vorzeichen ist rein relativ zur Zeichenrichtung definiert (links // von a→b) — eine Spiegelung kehrt die Umlauf-Orientierung um und muss - // daher auch jeden Bogen umkehren, sonst wandert er auf die falsche - // Seite. Erkannt über die Umlauf-Orientierung eines Test-Dreiecks unter - // `fn` (negativ ⇒ `fn` spiegelt) statt eine Spiegel-Op explizit zu - // markieren — funktioniert für JEDE Isometrie (Move/Rotate/Mirror sind - // alle nur `fn`-Closures, kein eigener Spiegel-Sonderpfad nötig). - const p0 = fn({ x: 0, y: 0 }), p1 = fn({ x: 1, y: 0 }), p2 = fn({ x: 0, y: 1 }); - const signedArea = (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y); - const bulge = signedArea < 0 ? geom.bulge.map((b) => -b) : geom.bulge; + // daher auch jeden Bogen umkehren, sonst wandert er auf die falsche Seite. + const bulge = reversesOrientation(fn) ? geom.bulge.map((b) => -b) : geom.bulge; return { ...geom, pts, bulge }; } case "rect": { @@ -216,6 +386,12 @@ export const mvGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeo return { ...geom, pts: geom.pts.map(fn) }; case "kote": return { ...geom, at: fn(geom.at) }; + case "detailref": + return { ...geom, at: fn(geom.at) }; + case "scalebar": + return { ...geom, at: fn(geom.at) }; + case "pointmarker": + return { ...geom, at: fn(geom.at) }; case "text": // Leader-Ziel bzw. Pfadpunkte (Text-entlang-Pfad) müssen mitwandern, // sonst zeigt der Pfeil/Pfad nach einem Move/Mirror/Rotate/Array auf die @@ -224,6 +400,7 @@ export const mvGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeo ...geom, at: fn(geom.at), ...(geom.leaderTarget ? { leaderTarget: fn(geom.leaderTarget) } : {}), + ...(geom.leaderBendPoints ? { leaderBendPoints: geom.leaderBendPoints.map(fn) } : {}), ...(geom.pathPts ? { pathPts: geom.pathPts.map(fn) } : {}), }; case "block": { @@ -253,6 +430,88 @@ export const mvGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeo } }; +/** Bildet Umriss + Aussparungen einer Decke unter `fn` ab. */ +function mvCeiling(c: Ceiling, fn: (p: Vec2) => Vec2): Ceiling { + return { + ...c, + outline: c.outline.map(fn), + ...(c.openings ? { openings: c.openings.map((hole) => hole.map(fn)) } : {}), + }; +} + +/** + * Bildet den Umriss eines Dachs unter `fn` ab. NUR für Move/Scale aufgerufen + * (s. `TransformSelection.roofIds`) — beide erhalten die Rechteck-/Achsen- + * Invariante des Umrisses, daher genügt reines Punkte-Mapping. + */ +function mvRoof(r: Roof, fn: (p: Vec2) => Vec2): Roof { + return { ...r, outline: r.outline.map(fn) }; +} + +/** Bildet Umriss + Stempel-Anker eines Raums unter `fn` ab. */ +function mvRoom(r: Room, fn: (p: Vec2) => Vec2): Room { + return { + ...r, + boundary: r.boundary.map(fn), + ...(r.stampAnchor ? { stampAnchor: fn(r.stampAnchor) } : {}), + }; +} + +/** + * Transformiert eine Treppe unter `fn` (Skalierungsfaktor `f`, wie bei + * {@link scaleGeom}): Antritt (+ Wendel-Zentrum) wandert mit; die Laufrichtung + * folgt wie bei {@link mvColumn} über einen mit-transformierten Richtungs- + * punkt. `turn` (L-Treppe) und `sweep` (Wendel) sind umlaufsinn-abhängig und + * kippen daher unter einer Spiegelung ({@link reversesOrientation}), bleiben + * aber unter Drehung/Verschiebung/Skalierung unverändert. Lauflänge/-breite/ + * Radius skalieren mit `f`; `totalRise` (eine Gebäudehöhe, Z) bleibt unberührt. + */ +function mvStair(s: Stair, fn: (p: Vec2) => Vec2, f: number): Stair { + const start = fn(s.start); + const tip = fn({ x: s.start.x + s.dir.x, y: s.start.y + s.dir.y }); + const dx = tip.x - start.x, dy = tip.y - start.y; + const len = Math.hypot(dx, dy) || 1; + const flips = reversesOrientation(fn); + return { + ...s, + start, + dir: { x: dx / len, y: dy / len }, + runLength: s.runLength * f, + width: s.width * f, + ...(s.run2Length !== undefined ? { run2Length: s.run2Length * f } : {}), + ...(s.turn !== undefined ? { turn: (flips ? -s.turn : s.turn) as 1 | -1 } : {}), + ...(s.center ? { center: fn(s.center) } : {}), + ...(s.radius !== undefined ? { radius: s.radius * f } : {}), + ...(s.sweep !== undefined ? { sweep: flips ? -s.sweep : s.sweep } : {}), + }; +} + +/** + * Vorschau-Umriss einer Treppe unter `fn`. Gerade/L nutzen den echten + * `stairOutline`-Kern; Wendel liefert dort Bogensegmente statt eines + * Polygons — für die Live-Vorschau genügt ein grob abgetasteter Innen-/ + * Aussenring (kein Anspruch auf die exakte Stufenkontur). + */ +function stairPreviewShapes(stair: Stair, fn: (p: Vec2) => Vec2): DraftShape[] { + if (stair.shape !== "spiral") { + const { polygon } = stairOutline(stair, 0); + return polygon ? [{ kind: "poly", pts: polygon.map(fn), closed: true }] : []; + } + const center = stair.center ?? stair.start; + const rIn = Math.max(0, stair.radius ?? 0); + const rOut = rIn + stair.width; + const sweepDeg = stair.sweep ?? 360; + const a0 = Math.atan2(stair.start.y - center.y, stair.start.x - center.x); + const steps = Math.max(4, Math.round(Math.abs(sweepDeg) / 15)); + const outer: Vec2[] = [], inner: Vec2[] = []; + for (let i = 0; i <= steps; i++) { + const a = a0 + ((sweepDeg * Math.PI) / 180) * (i / steps); + outer.push(fn({ x: center.x + Math.cos(a) * rOut, y: center.y + Math.sin(a) * rOut })); + inner.push(fn({ x: center.x + Math.cos(a) * rIn, y: center.y + Math.sin(a) * rIn })); + } + return [{ kind: "poly", pts: [...outer, ...inner.reverse()], closed: true }]; +} + /** Vorschau-Formen für ein Element unter der Punkt-Transformation `fn`. */ function itemPreview(project: Project, item: AnyItem, fn: (p: Vec2) => Vec2): DraftShape[] { if (item.kind === "wall") { @@ -271,6 +530,18 @@ function itemPreview(project: Project, item: AnyItem, fn: (p: Vec2) => Vec2): Dr if (item.kind === "column") { return [{ kind: "poly", pts: columnFootprint(item.column).map(fn), closed: true }]; } + if (item.kind === "ceiling") { + return [{ kind: "poly", pts: item.ceiling.outline.map(fn), closed: true }]; + } + if (item.kind === "roof") { + return [{ kind: "poly", pts: item.roof.outline.map(fn), closed: true }]; + } + if (item.kind === "room") { + return [{ kind: "poly", pts: item.room.boundary.map(fn), closed: true }]; + } + if (item.kind === "stair") { + return stairPreviewShapes(item.stair, fn); + } const g = mvGeom(item.drawing.geom, fn); switch (g.shape) { case "line": @@ -302,7 +573,7 @@ export function transformPreview( mode: CopyMode, count: number, ): DraftShape[] { - const items = gatherItems(project, sel); + const items = gatherItems(project, sel, op); const shapes: DraftShape[] = []; const instances: number[] = [...copyTs(op, mode, count)]; if (movesOriginal(mode)) instances.push(1); // U: Original an Endlage zeigen @@ -313,6 +584,46 @@ export function transformPreview( return shapes; } +/** Anzahl Segmente des Radius-Kreises in {@link rotateGizmoShapes} — grob + * genug für eine flüssige Draft-Vorschau, fein genug, um rund zu wirken. */ +const ROTATE_GIZMO_CIRCLE_SEGMENTS = 48; + +/** + * Dreh-Gizmo (ArchiCAD/Vectorworks-Stil, Nutzer-Wunsch „bei Drehen auch eine + * Darstellung"): eine Linie vom Zentrum zum FESTEN Referenzpunkt (0°-Basis), + * eine Linie vom Zentrum zum aktuellen Cursor (laufender Winkel) und ein + * Kreis mit Radius = Abstand Zentrum→Referenzpunkt. Der Kreis besteht bewusst + * aus einzelnen `"line"`-Segmenten statt EINES geschlossenen `"poly"` — Letzeres + * rendert im 2D-SVG-Overlay (`plan/planView/overlays.tsx`) IMMER gefüllt + * (`.tool-preview-fill`, auch bei `closed:false` — ein `` kennt keine + * offene Variante) und wäre optisch nicht mehr von der transformierten + * Vorschau-Kontur (ebenfalls oft eine gefüllte Fläche) zu unterscheiden; als + * Liniensegmente bleibt der Kreis ein dünner Ring (`.tool-preview-line`). + * Läuft über denselben `draft.preview`-Kanal wie die transformierte + * Vorschau-Kontur (App.tsx `transformMove` hängt das Ergebnis an), zeichnet + * sich also automatisch in BEIDEN Ansichten (2D-SVG-Overlay UND 3D-Weltraum- + * Linien, s. `plan/toWalls3d.ts::draftWorldLines`) — kein eigener Render-Pfad + * nötig. Leeres Array, wenn Zentrum und Referenzpunkt zusammenfallen (kein + * Radius). + */ +export function rotateGizmoShapes(center: Vec2, refPoint: Vec2, cursor: Vec2): DraftShape[] { + const radius = Math.hypot(refPoint.x - center.x, refPoint.y - center.y); + if (radius < 1e-6) return []; + const circle: Vec2[] = []; + for (let i = 0; i < ROTATE_GIZMO_CIRCLE_SEGMENTS; i++) { + const a = (i / ROTATE_GIZMO_CIRCLE_SEGMENTS) * Math.PI * 2; + circle.push({ x: center.x + Math.cos(a) * radius, y: center.y + Math.sin(a) * radius }); + } + const shapes: DraftShape[] = [ + { kind: "line", a: center, b: refPoint }, + { kind: "line", a: center, b: cursor }, + ]; + for (let i = 0; i < circle.length; i++) { + shapes.push({ kind: "line", a: circle[i], b: circle[(i + 1) % circle.length] }); + } + return shapes; +} + // ── Commit ─────────────────────────────────────────────────────────────────── /** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien). */ @@ -324,39 +635,73 @@ export function commitTransform( mode: CopyMode, count: number, ): Project { - const items = gatherItems(project, sel); + const items = gatherItems(project, sel, op); if (items.length === 0) return project; const wallIds = new Set(sel.wallIds); + // Bei einer Skalierung müssen auch Grössenfelder (Radius/Schrifthöhe/…) + // mitziehen — dafür `scaleGeom` statt `mvGeom` (s. dort); analog für + // Treppen `mvStair` mit dem Skalierungsfaktor statt Faktor 1. + const geomAt = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2, t: number): Drawing2DGeom => + op === "scale" ? scaleGeom(geom, fn, scaleFactor(pts, t)) : mvGeom(geom, fn); + const stairAt = (s: Stair, fn: (p: Vec2) => Vec2, t: number): Stair => + mvStair(s, fn, op === "scale" ? scaleFactor(pts, t) : 1); let walls = project.walls; let drawings2d = project.drawings2d; let extrudedSolids = project.extrudedSolids ?? []; let columns = project.columns ?? []; + let ceilings = project.ceilings ?? []; + let roofs = project.roofs ?? []; + let stairs = project.stairs ?? []; + let rooms = project.rooms ?? []; + const ceilingIds = new Set(sel.ceilingIds ?? []); + const roofIds = new Set(sel.roofIds ?? []); + const stairIds = new Set(sel.stairIds ?? []); + const roomIds = new Set(sel.roomIds ?? []); - // U (move): Original an die Endlage (t=1) transformieren. + // U (move): Original an die Endlage (t=1) transformieren. Objekt-Sperre + // (`locked`) überall mitgeprüft — dieselbe Semantik wie `gatherItems` + // oben (das hier ist ein SEPARATER Pfad, der `items` nicht durchläuft, + // s. Kommentar bei `roofTransformAllowed`-Nutzung als Präzedenzfall für + // genau diese Art von Doppel-Pflege). if (movesOriginal(mode)) { const fn = transformFn(op, pts, 1); - walls = walls.map((w) => (wallIds.has(w.id) ? { ...w, start: fn(w.start), end: fn(w.end) } : w)); + walls = walls.map((w) => + wallIds.has(w.id) && !w.locked ? { ...w, start: fn(w.start), end: fn(w.end) } : w, + ); const moveDrawIds = drawingIdSet(sel); if (moveDrawIds.size > 0) { drawings2d = drawings2d.map((d) => - moveDrawIds.has(d.id) ? { ...d, geom: mvGeom(d.geom, fn) } : d, + moveDrawIds.has(d.id) && !d.locked ? { ...d, geom: geomAt(d.geom, fn, 1) } : d, ); } if (sel.extrudedSolidId) { + // Skalierung: `points` (2D-Tesselierung fürs Grundriss-Polygon) UND der + // echte Radius `circle.r` (den `toWalls3d.ts` für die runde 3D-Extrusion + // nutzt) müssen mitziehen — sonst weicht das 3D-Volumen sichtbar von + // der Grundriss-Kontur ab (nur `center` mitzuführen genügt nicht). + const f1 = op === "scale" ? scaleFactor(pts, 1) : 1; extrudedSolids = extrudedSolids.map((s) => s.id === sel.extrudedSolidId ? { ...s, points: s.points.map(fn), - circle: s.circle ? { ...s.circle, center: fn(s.circle.center) } : undefined, + circle: s.circle ? { ...s.circle, center: fn(s.circle.center), r: s.circle.r * f1 } : undefined, } : s, ); } if (sel.columnId) { - columns = columns.map((c) => (c.id === sel.columnId ? mvColumn(c, fn) : c)); + columns = columns.map((c) => (c.id === sel.columnId && !c.locked ? mvColumn(c, fn) : c)); } + if (ceilingIds.size > 0) + ceilings = ceilings.map((c) => (ceilingIds.has(c.id) && !c.locked ? mvCeiling(c, fn) : c)); + if (roofIds.size > 0 && roofTransformAllowed(op)) { + roofs = roofs.map((r) => (roofIds.has(r.id) && !r.locked ? mvRoof(r, fn) : r)); + } + if (stairIds.size > 0) + stairs = stairs.map((s) => (stairIds.has(s.id) && !s.locked ? stairAt(s, fn, 1) : s)); + if (roomIds.size > 0) rooms = rooms.map((r) => (roomIds.has(r.id) && !r.locked ? mvRoom(r, fn) : r)); } // Kopien anhängen (I/O/P bzw. mirror copy). @@ -364,25 +709,50 @@ export function commitTransform( const newDrawings: Drawing2D[] = []; const newSolids: ExtrudedSolid[] = []; const newColumns: Column[] = []; + const newCeilings: Ceiling[] = []; + const newRoofs: Roof[] = []; + const newStairs: Stair[] = []; + const newRooms: Room[] = []; for (const t of copyTs(op, mode, count)) { const fn = transformFn(op, pts, t); for (const item of items) { - if (item.kind === "wall") { - const w = item.wall; - newWalls.push({ ...w, id: uniqueId("W"), start: fn(w.start), end: fn(w.end) }); - } else if (item.kind === "drawing") { - const d = item.drawing; - newDrawings.push({ ...d, id: uniqueId("dr2d"), geom: mvGeom(d.geom, fn) }); - } else if (item.kind === "column") { - newColumns.push({ ...mvColumn(item.column, fn), id: uniqueId("column") }); - } else { - const s = item.solid; - newSolids.push({ - ...s, - id: uniqueId("extrude"), - points: s.points.map(fn), - circle: s.circle ? { ...s.circle, center: fn(s.circle.center) } : undefined, - }); + switch (item.kind) { + case "wall": { + const w = item.wall; + newWalls.push({ ...w, id: uniqueId("W"), start: fn(w.start), end: fn(w.end) }); + break; + } + case "drawing": { + const d = item.drawing; + newDrawings.push({ ...d, id: uniqueId("dr2d"), geom: geomAt(d.geom, fn, t) }); + break; + } + case "column": + newColumns.push({ ...mvColumn(item.column, fn), id: uniqueId("column") }); + break; + case "ceiling": + newCeilings.push({ ...mvCeiling(item.ceiling, fn), id: uniqueId("C") }); + break; + case "roof": + newRoofs.push({ ...mvRoof(item.roof, fn), id: uniqueId("RF") }); + break; + case "stair": + newStairs.push({ ...stairAt(item.stair, fn, t), id: uniqueId("ST") }); + break; + case "room": + newRooms.push({ ...mvRoom(item.room, fn), id: uniqueId("RM") }); + break; + case "extrudedSolid": { + const s = item.solid; + const f = op === "scale" ? scaleFactor(pts, t) : 1; + newSolids.push({ + ...s, + id: uniqueId("extrude"), + points: s.points.map(fn), + circle: s.circle ? { ...s.circle, center: fn(s.circle.center), r: s.circle.r * f } : undefined, + }); + break; + } } } } @@ -393,5 +763,9 @@ export function commitTransform( drawings2d: newDrawings.length ? [...drawings2d, ...newDrawings] : drawings2d, extrudedSolids: newSolids.length ? [...extrudedSolids, ...newSolids] : extrudedSolids, columns: newColumns.length ? [...columns, ...newColumns] : columns, + ceilings: newCeilings.length ? [...ceilings, ...newCeilings] : ceilings, + roofs: newRoofs.length ? [...roofs, ...newRoofs] : roofs, + stairs: newStairs.length ? [...stairs, ...newStairs] : stairs, + rooms: newRooms.length ? [...rooms, ...newRooms] : rooms, }; } diff --git a/src/tools/types.ts b/src/tools/types.ts index 10d56f5..ab83950 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -18,6 +18,7 @@ export type ToolId = | "room" | "line" | "xline" + | "ray" | "polyline" | "rect" | "circle" @@ -29,6 +30,11 @@ export type ToolId = | "bezier" | "dimension" | "kote" + | "detailref" + | "scalebar" + | "revcloud" + | "pointmarker" + | "wipeout" | "text" | "leader" | "textpath" @@ -55,7 +61,31 @@ export type SnapKind = * übrigen Snap-Arten, sonst würde jede N-tel-Position jeder Linie den * Fang-Kandidatenraum überfluten. */ - | "divide"; + | "divide" + /** + * Lotfusspunkt einer nahen Strecke — NICHT vom Cursor aus wie `onEdge`, + * sondern vom LETZTEN gesetzten Punkt aus konstruiert (die Strecke vom + * letzten Punkt zu diesem Fangpunkt steht im rechten Winkel zur Strecke). + * Nur aktiv, solange ein `lastPoint` existiert. + */ + | "perpendicular" + /** + * Tangentenpunkt an einen nahen Kreis/Bogen, konstruiert vom LETZTEN + * gesetzten Punkt aus (klassische Tangente-von-aussen-Konstruktion, zwei + * Lösungen pro Kreis). Nur aktiv, solange ein `lastPoint` ausserhalb des + * Kreises existiert; bei einem Bogen nur, wenn der Tangentenpunkt selbst + * im Bogen-Bereich liegt. + */ + | "tangent" + /** + * Punkt auf der Parallelen durch den letzten gesetzten Punkt zu einer + * REFERENZ-Strecke — die Referenz muss erst wie bei „divide" durch kurzes + * Verweilen des Cursors „erfasst" werden (dieselbe Verweil-Erkennung). + * Bleibt danach STICKY erfasst, auch wenn der Cursor die Linie wieder + * verlässt (Richtung Zielpunkt) — bis eine andere Strecke neu erfasst + * wird. Nur aktiv, solange ein `lastPoint` existiert. + */ + | "parallel"; export interface SnapResult { /** Gefangener Punkt (Meter). */ @@ -76,9 +106,33 @@ export interface SnapSettings { intersection: boolean; center: boolean; onEdge: boolean; + /** + * Senkrecht zum letzten Punkt (Nutzer-Wunsch: „Senkrecht-/Tangential-/ + * Parallel-zu-Referenz-Modus" fehlt). Bietet den Lotfusspunkt vom letzten + * gesetzten Punkt auf nahe Strecken an — braucht daher zwingend einen + * bereits gesetzten `lastPoint`, sonst wirkungslos. + */ + perpendicular: boolean; + /** Tangentenpunkt an einen nahen Kreis/Bogen, vom letzten Punkt aus konstruiert. */ + tangent: boolean; + /** + * Parallel zu einer per kurzem Hover „erfassten" Referenzstrecke (dieselbe + * Verweil-Erkennung wie `divide`) durch den letzten gesetzten Punkt. + */ + parallel: boolean; grid: boolean; /** Rasterweite in Metern. */ gridSize: number; + /** + * Zeichnet ein sichtbares Hintergrund-Raster in der Planansicht (Nutzer- + * Wunsch: „Kein sichtbares 2D-Zeichenraster" — bisher steuerte `gridSize` + * NUR den Fang, nichts wurde gezeichnet). Unabhängig von `grid` (Fang) — + * rein optisch, beeinflusst keine Snap-Logik. Die tatsächliche Linien- + * dichte richtet sich NICHT nach `gridSize` (bei typischem Zoom viel zu + * fein), sondern adaptiv nach dem Zoom (s. `PlanGrid.tsx` `rulerStep`, + * dieselbe Logik wie die Lineal-Hauptstriche). + */ + showGrid: boolean; /** Ortho/Winkelraster (Shift erzwingt zusätzlich). */ ortho: boolean; /** Winkelraster in Grad (z. B. 90 = H/V). */ @@ -116,8 +170,17 @@ export const DEFAULT_SNAP: SnapSettings = { intersection: true, center: true, onEdge: true, + // Default AUS (anders als endpoint/midpoint/center/onEdge): diese drei sind + // situative Konstruktions-Hilfen (brauchen zwingend einen `lastPoint`/eine + // per Hover erfasste Referenz), keine ständig sinnvollen Fangpunkte wie + // Endpunkt/Mittelpunkt — ein stiller Default-Wechsel für alle Bestands- + // projekte wäre hier unpassend, anders als seinerzeit bei `center`. + perpendicular: false, + tangent: false, + parallel: false, grid: true, gridSize: 0.1, + showGrid: false, ortho: false, angleStep: 90, tolerancePx: 12, diff --git a/src/ui/ColorMixer.tsx b/src/ui/ColorMixer.tsx new file mode 100644 index 0000000..ed06a42 --- /dev/null +++ b/src/ui/ColorMixer.tsx @@ -0,0 +1,197 @@ +// Farbmischer mit fünf Modellen — Segmented-Umschalter zwischen RGB, CMYK, +// HSL, HSV und einem visuellen Spektrum-Wähler; je Kanal ein Slider + +// Zahlenfeld, oben eine Live-Vorschau der aktuellen Farbe. Eigenständig, +// ohne Popover-Hülle — wird von `FreeColorPicker.tsx` eingebettet. +// +// CMYK nutzt, wenn verfügbar, ECHTES ICC-Farbmanagement (`model/colorIcc.ts`, +// lcms-wasm gegen macOS' Generic CMYK Profile) — sonst automatisch die +// vereinfachte Formel (`model/color.ts`) als Fallback (anderes Betriebs- +// system, Datei fehlt, WASM-Ladefehler). Der Hinweistext unten sagt, welcher +// der beiden Fälle gerade aktiv ist. +// +// WARUM EIN PUFFER (`draft`): die Farbe selbst lebt als Hex/RGB beim +// Aufrufer. CMYK (4 Kanäle) und HSL/HSV (Farbton bei Grau/Schwarz/Weiss +// undefiniert) haben aber Freiheitsgrade, die beim Rückrechnen aus RGB +// verloren gehen — ohne Puffer würden beim Ziehen EINES Reglers die anderen +// sichtbar springen (Nutzer-Report zu CMYK). Der Puffer wird nur dann aus +// `color` neu aufgebaut, wenn die Farbe von AUSSEN kommt (Palette, Hex-Feld, +// anderes Modell) — erkannt über die zuletzt selbst gesendete Farbe. + +import { useEffect, useRef, useState } from "react"; +import { + cmykToRgb, + hexToRgb, + hslToRgb, + hsvToRgb, + rgbToCmyk, + rgbToHex, + rgbToHsl, + rgbToHsv, +} from "../model/color"; +import type { Cmyk, Hsl, Hsv, Rgb } from "../model/color"; +import { initIccColorManagement, iccColorManagementAvailable, rgbToCmykIcc, cmykToRgbIcc } from "../model/colorIcc"; +import { SpectrumPicker } from "./SpectrumPicker"; +import { Segmented } from "./resourceManager/fields"; +import { t } from "../i18n"; + +type Mode = "spectrum" | "rgb" | "cmyk" | "hsl" | "hsv"; + +const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v)); + +/** Kanal-Definition einer Modell-Zeile: Feldname, Beschriftung, Wertebereich. */ +interface Channel { + key: keyof T; + label: string; + max: number; +} +const RGB_CHANNELS: Channel[] = [ + { key: "r", label: "R", max: 255 }, + { key: "g", label: "G", max: 255 }, + { key: "b", label: "B", max: 255 }, +]; +const CMYK_CHANNELS: Channel[] = [ + { key: "c", label: "C", max: 100 }, + { key: "m", label: "M", max: 100 }, + { key: "y", label: "Y", max: 100 }, + { key: "k", label: "K", max: 100 }, +]; +const HSL_CHANNELS: Channel[] = [ + { key: "h", label: "H", max: 360 }, + { key: "s", label: "S", max: 100 }, + { key: "l", label: "L", max: 100 }, +]; +const HSV_CHANNELS: Channel[] = [ + { key: "h", label: "H", max: 360 }, + { key: "s", label: "S", max: 100 }, + { key: "v", label: "V", max: 100 }, +]; + +/** RGB→CMYK mit ICC-Vorrang, Formel-Fallback. */ +function toCmyk(rgb: Rgb): Cmyk { + return rgbToCmykIcc(rgb) ?? rgbToCmyk(rgb); +} +/** CMYK→RGB mit ICC-Vorrang, Formel-Fallback. */ +function fromCmyk(cmyk: Cmyk): Rgb { + return cmykToRgbIcc(cmyk) ?? cmykToRgb(cmyk); +} + +/** Alle gepufferten Modelle einer Farbe (s. Modul-Kommentar). */ +interface Draft { + cmyk: Cmyk; + hsl: Hsl; + hsv: Hsv; +} +const draftOf = (rgb: Rgb): Draft => ({ + cmyk: toCmyk(rgb), + hsl: rgbToHsl(rgb), + hsv: rgbToHsv(rgb), +}); + +export function ColorMixer({ color, onChange }: { color: string; onChange: (hex: string) => void }) { + const [mode, setMode] = useState("spectrum"); + // Einmaliger, formularunabhängiger Ladeversuch — mehrere ColorMixer- + // Instanzen (Popover kann mehrfach geöffnet werden) teilen sich das + // gecachte Promise in `colorIcc.ts`, hier nur der lokale Re-Render-Trigger. + const [iccReady, setIccReady] = useState(iccColorManagementAvailable()); + useEffect(() => { + if (iccReady) return; + let cancelled = false; + initIccColorManagement().then((ok) => { + if (!cancelled && ok) setIccReady(true); + }); + return () => { + cancelled = true; + }; + }, [iccReady]); + + const rgb = hexToRgb(color); + const [draft, setDraft] = useState(() => draftOf(rgb)); + const lastEmitted = useRef(null); + useEffect(() => { + if (color === lastEmitted.current) return; + setDraft(draftOf(hexToRgb(color))); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [color]); + + /** Emittiert die Farbe aus einem geänderten Modell und hält den Puffer konsistent. */ + const emit = (next: Partial, nextRgb: Rgb) => { + const hex = rgbToHex(nextRgb); + lastEmitted.current = hex; + // Nur das BEARBEITETE Modell übernimmt die Nutzerwerte 1:1; die übrigen + // werden aus der neuen Farbe abgeleitet (sonst zeigten sie veraltete Werte). + setDraft({ ...draftOf(hexToRgb(hex)), ...next }); + onChange(hex); + }; + + const setRgbChannel = (key: keyof Rgb, v: number) => + emit({}, { ...rgb, [key]: clamp(v, 0, 255) }); + const setCmykChannel = (key: keyof Cmyk, v: number) => { + const cmyk = { ...draft.cmyk, [key]: clamp(v, 0, 100) }; + emit({ cmyk }, fromCmyk(cmyk)); + }; + const setHslChannel = (key: keyof Hsl, v: number) => { + const hsl = { ...draft.hsl, [key]: clamp(v, 0, key === "h" ? 360 : 100) }; + emit({ hsl }, hslToRgb(hsl)); + }; + const setHsvChannel = (key: keyof Hsv, v: number) => { + const hsv = { ...draft.hsv, [key]: clamp(v, 0, key === "h" ? 360 : 100) }; + emit({ hsv }, hsvToRgb(hsv)); + }; + + /** Eine Kanal-Zeile (Beschriftung + Slider + Zahlenfeld). */ + const channelRows = (channels: Channel[], values: T, set: (key: keyof T, v: number) => void) => + channels.map((ch) => { + const value = values[ch.key] as number; + return ( +
+ {ch.label} + set(ch.key, Number(e.target.value))} + /> + set(ch.key, Number(e.target.value))} + /> +
+ ); + }); + + return ( +
+
+ + + value={mode} + onChange={setMode} + options={[ + { value: "spectrum", label: t("colorMixer.spectrum") }, + { value: "rgb", label: "RGB" }, + { value: "cmyk", label: "CMYK" }, + { value: "hsl", label: "HSL" }, + { value: "hsv", label: "HSV" }, + ]} + /> +
+ {mode === "spectrum" && ( + emit({ hsv }, hsvToRgb(hsv))} /> + )} + {mode === "rgb" && channelRows(RGB_CHANNELS, rgb, setRgbChannel)} + {mode === "cmyk" && channelRows(CMYK_CHANNELS, draft.cmyk, setCmykChannel)} + {mode === "hsl" && channelRows(HSL_CHANNELS, draft.hsl, setHslChannel)} + {mode === "hsv" && channelRows(HSV_CHANNELS, draft.hsv, setHsvChannel)} + {mode === "cmyk" && ( +
+ {t(iccReady ? "colorMixer.cmykHintIcc" : "colorMixer.cmykHint")} +
+ )} +
+ ); +} diff --git a/src/ui/ColorSwatchCell.tsx b/src/ui/ColorSwatchCell.tsx new file mode 100644 index 0000000..d7f9012 --- /dev/null +++ b/src/ui/ColorSwatchCell.tsx @@ -0,0 +1,29 @@ +// Eine Popover-Swatch-Zelle — geteilt von `PenColorField.tsx` (Stift-Raster) +// und `FreeColorPicker.tsx` (freie Palette/RAL-Raster), damit beide nicht +// gegenseitig voneinander importieren müssen. + +export function Swatch({ + color, + active, + title, + label, + onClick, +}: { + color: string; + active: boolean; + title: string; + label?: string; + onClick: () => void; +}) { + return ( + + ); +} diff --git a/src/ui/ContextImportDialog.tsx b/src/ui/ContextImportDialog.tsx index 5c62e9a..b2b29d3 100644 --- a/src/ui/ContextImportDialog.tsx +++ b/src/ui/ContextImportDialog.tsx @@ -197,33 +197,16 @@ export function ContextImportDialog({ // Landeskoordinaten schreibt und weitere Importe lagerichtig dazu liegen. // Mit „Neuer Bezugspunkt" (georef) lässt sich der Ursprung später auf einen // beliebigen Modellpunkt verschieben. - let origin: GeoOrigin = geoAnchor + // `origin` steht schon hier VOLLSTÄNDIG fest (aus geoAnchor/refLv95) — + // jede fetch*-Funktion bekommt sie nur durchgereicht und berechnet nie + // eine eigene (s. `originIn ?? makeOrigin(center)`-Muster überall in + // io/*.ts). Die vier Quellen unten sind also NICHT voneinander abhängig + // und laufen parallel statt sequentiell (Nutzer-Report: „dauert etwas + // lange" — bei mehreren gewählten Quellen war die Wartezeit bisher die + // SUMME aller Einzel-Abrufe statt des langsamsten). + const origin: GeoOrigin = geoAnchor ? { e: geoAnchor.lv95.e - geoAnchor.model.x, n: geoAnchor.lv95.n - geoAnchor.model.y } : makeOrigin(refLv95); - const all: GeoFeature[] = []; - // Echte swissBUILDINGS3D-Meshes (v2/v3) landen direkt als ContextObject - // (kein Footprint+Box-Umweg über GeoFeature/featuresToContextObjects). - const extraObjs: ContextObject[] = []; - // Übersprungene Kacheln (zu gross entpackt, Netzwerkfehler o. Ä.) — - // damit „0 Gebäude" von „X Kacheln übersprungen" unterscheidbar bleibt - // statt eines stummen Leer-Ergebnisses (Nutzer-Report). - let buildingsSkipped = 0; - - if (sources.swissBuildings === "flach") { - const r = await fetchBuildings(center, radius, origin); - origin = r.origin; - all.push(...r.features); - } else if (sources.swissBuildings === "v2" || sources.swissBuildings === "v3") { - const r = await fetchBuildings3d( - center, - radius, - origin, - sources.swissBuildings as BuildingsVersion, - ); - origin = r.origin; - extraObjs.push(...r.meshes); - buildingsSkipped = r.skippedTiles; - } const osmSel: OsmSelection = { buildings: sources.osmBuildings, @@ -234,31 +217,68 @@ export function ContextImportDialog({ railway: sources.osmRailway, forest: sources.osmForest, }; - if ( + const wantsOsm = osmSel.buildings || osmSel.roads || osmSel.water || osmSel.green || osmSel.parking || osmSel.railway || - osmSel.forest - ) { - const r = await fetchOsm(center, radius, osmSel, origin); - origin = r.origin; - all.push(...r.features); + osmSel.forest; + // Die Drapierung braucht das Gelände-TIN auch dann, wenn nur „Luftbild + // aufs Gelände" (ohne eigenen Terrain-Haken) gewählt wäre. + const wantsTerrain = sources.swissTerrain || sources.swissImageDrape; + const wantsImage = sources.swissImage || sources.swissImageDrape; + + const buildingsPromise = + sources.swissBuildings === "flach" + ? fetchBuildings(center, radius, origin) + : sources.swissBuildings === "v2" || sources.swissBuildings === "v3" + ? fetchBuildings3d(center, radius, origin, sources.swissBuildings as BuildingsVersion) + : null; + const osmPromise = wantsOsm ? fetchOsm(center, radius, osmSel, origin) : null; + const terrainPromise = wantsTerrain + ? fetchTerrainXyz(center, radius, origin, terrainResolution) + : null; + const imagePromise = wantsImage ? fetchSwissImage(center, radius, origin) : null; + + const [buildingsResult, osmResult, terrainResult, imageResult] = await Promise.all([ + buildingsPromise, + osmPromise, + terrainPromise, + imagePromise, + ]); + + const all: GeoFeature[] = []; + // Echte swissBUILDINGS3D-Meshes (v2/v3) landen direkt als ContextObject + // (kein Footprint+Box-Umweg über GeoFeature/featuresToContextObjects). + const extraObjs: ContextObject[] = []; + // Übersprungene Kacheln (zu gross entpackt, Netzwerkfehler o. Ä.) — + // damit „0 Gebäude" von „X Kacheln übersprungen" unterscheidbar bleibt + // statt eines stummen Leer-Ergebnisses (Nutzer-Report). + let buildingsSkipped = 0; + // KEIN `arr.push(...grosseArray)`: bei einem grossflächigen Import (ganze + // Stadt) können `meshes`/`features` hunderttausende Einträge haben — der + // Spread-Operator sprengt dann die Argumentzahl-Grenze von `push` + // (RangeError "Maximum call stack size exceeded"), dieselbe, bereits + // dokumentierte Falle wie in `swissBuildings3d.ts::concatMeshes`/ + // `dwgParser.ts` (dort an einer echten 2000-Gebäude-Kachel verifiziert). + // Reine `for`-Schleifen sind unbegrenzt sicher. + if (buildingsResult) { + if ("meshes" in buildingsResult) { + for (const m of buildingsResult.meshes) extraObjs.push(m); + buildingsSkipped = buildingsResult.skippedTiles; + } else { + for (const f of buildingsResult.features) all.push(f); + } } + if (osmResult) for (const f of osmResult.features) all.push(f); // Gelände-Höhenraster (echtes swissALTI3D-XYZ, native Auflösung) → Terrain-Mesh. - // Die Drapierung braucht das TIN -> Terrain auch dann holen, wenn nur - // „Luftbild aufs Gelände" (ohne eigenen Terrain-Haken) gewählt wäre. let terrain: TerrainMesh | null = null; - if (sources.swissTerrain || sources.swissImageDrape) { - const r = await fetchTerrainXyz(center, radius, origin, terrainResolution); - origin = r.origin; - if (r.grid) { - const mesh = terrainMeshFromGrid(r.grid); - if (mesh.positions.length >= 9) terrain = mesh; - } + if (terrainResult?.grid) { + const mesh = terrainMeshFromGrid(terrainResult.grid); + if (mesh.positions.length >= 9) terrain = mesh; } // SWISSIMAGE-Luftbild (WMS) → georeferenziertes Rasterbild (EIN ContextImage). @@ -267,22 +287,18 @@ export function ContextImportDialog({ // Textur aufs Gelände (render3d `set_aerial_texture`). // Beide Modi teilen dasselbe Bild; das Bild wird nur EINMAL geladen. let image: ContextObject | null = null; - if (sources.swissImage || sources.swissImageDrape) { - const r = await fetchSwissImage(center, radius, origin); - origin = r.origin; - if (r.dataUrl) { - image = { - id: `img-${Date.now()}`, - type: "image", - name: `Luftbild ${selected.label}`, - layer: "Luftbild", - categoryCode: IMAGE_CATEGORY.code, - src: r.dataUrl, - min: r.min, - max: r.max, - drape: sources.swissImageDrape, - }; - } + if (imageResult?.dataUrl) { + image = { + id: `img-${Date.now()}`, + type: "image", + name: `Luftbild ${selected.label}`, + layer: "Luftbild", + categoryCode: IMAGE_CATEGORY.code, + src: imageResult.dataUrl, + min: imageResult.min, + max: imageResult.max, + drape: sources.swissImageDrape, + }; } if (all.length === 0 && !terrain && !image && extraObjs.length === 0) { @@ -312,7 +328,7 @@ export function ContextImportDialog({ } const objs = featuresToContextObjects(all, selected.label); - objs.push(...extraObjs); + for (const o of extraObjs) objs.push(o); if (terrain) objs.push(terrain); if (image) objs.push(image); onImport(objs); diff --git a/src/ui/ElevationPreview.tsx b/src/ui/ElevationPreview.tsx new file mode 100644 index 0000000..73c3d8f --- /dev/null +++ b/src/ui/ElevationPreview.tsx @@ -0,0 +1,243 @@ +// Frontal-Ansicht (Elevation, SVG) eines Fensters/einer Tür: Rahmen, Flügel/ +// Pfosten (mit Öffnungslinien je Flügel), Verglasungshinweis und Rollladen- +// kasten. Rein aus den Modellwerten gezeichnet — kein Renderer-Roundtrip, +// deterministisch. Ursprünglich Teil von {@link OpeningEditorDialog} (dort +// mit einer echten Öffnungs-Instanz gefüttert); hierher extrahiert, damit +// auch die Typ-Bibliothek (ResourceManager, ohne konkrete Instanz — s. +// `WindowStylesTab`/`DoorStylesTab`) dieselbe Vorschau zeigen kann. Braucht +// dafür nur `opening.width`/`opening.height`, der Rest kommt aus `wt`/`dt`. +// +// Bezeichner englisch, Kommentare/UI-Text deutsch (CONVENTIONS.md). + +import { useMemo } from "react"; +import { t } from "../i18n"; +import type { DoorType, Opening, WindowType } from "../model/types"; +import { sashesOfWindowType, glazingPanesOf } from "../model/types"; + +export function ElevationPreview({ + opening, + wt, + dt, +}: { + opening: Opening; + wt?: WindowType; + dt?: DoorType; +}) { + const geom = useMemo(() => { + const w = Math.max(0.1, opening.width); + const h = Math.max(0.1, opening.height); + const pad = 24; + const boxH = (!dt && wt?.shading?.create ? wt.shading.box.height : 0) || 0; + // Zeichenfläche auf ~260×300 skalieren, Seitenverhältnis erhalten. + const availW = 220; + const availH = 260; + const totalH = h + boxH; + const scale = Math.min(availW / w, availH / totalH); + const px = (m: number) => m * scale; + return { w, h, boxH, pad, scale, px, totalH }; + }, [opening.width, opening.height, wt, dt]); + + const { w, h, boxH, pad, px } = geom; + const svgW = px(w) + pad * 2; + const svgH = px(h + boxH) + pad * 2; + const frameW = px((!dt ? wt?.frameWidth : dt?.frameWidth) ?? 0.06); + const originY = pad + px(boxH); + + // Flügel-/Pfostenaufteilung: gleichmässig (autoWidth) bzw. feste Breiten. + const sashes = !dt && wt ? sashesOfWindowType(wt) : []; + const fixedTotal = sashes.reduce( + (a, s) => a + (s.kind === "pfosten" ? s.postWidth ?? 0.06 : s.autoWidth ? 0 : s.width ?? 0), + 0, + ); + const autoCount = sashes.filter((s) => s.kind === "fluegel" && (s.autoWidth ?? true)).length; + const autoW = autoCount > 0 ? Math.max(0.05, (w - fixedTotal) / autoCount) : 0; + const panes = !dt && wt ? glazingPanesOf(wt) : 1; + + // Segmentbreiten (Meter) je Sash. + const segW = sashes.map((s) => + s.kind === "pfosten" + ? s.postWidth ?? 0.06 + : s.autoWidth ?? true + ? autoW + : s.width ?? autoW, + ); + + const strokeMain = "var(--ink)"; + const strokeMuted = "var(--muted)"; + const glass = "rgba(120,180,220,0.18)"; + + let cursor = 0; + const segEls: JSX.Element[] = []; + sashes.forEach((s, i) => { + const x0 = pad + px(cursor); + const wSeg = px(segW[i]); + cursor += segW[i]; + if (s.kind === "pfosten") { + segEls.push( + , + ); + return; + } + // Flügelrahmen + Glas + Öffnungslinien. + const gx = x0 + frameW * 0.4; + const gy = originY + frameW * 0.4; + const gw = Math.max(1, wSeg - frameW * 0.8); + const gh = Math.max(1, px(h) - frameW * 0.8); + segEls.push( + + + + {/* Verglasung: zusätzliche parallele Glaslinien = Scheibenzahl − 1. */} + {Array.from({ length: Math.max(0, panes - 1) }, (_, k) => ( + + ))} + {/* Öffnungslinien (Dreieck) je nach Anschlag; nicht bei fest. */} + {s.opening !== "fest" && + (s.hingeSide === "right" ? ( + + ) : ( + + ))} + , + ); + }); + + return ( + + {/* Rollladenkasten über der Öffnung (nur Fenster mit shading.create). */} + {boxH > 0 && ( + + )} + {/* Blendrahmen (Aussenkontur). */} + + {/* Für Türen: einfaches Türblatt statt Flügelraster. */} + {dt ? ( + <> + + {dt.leafCount === 2 && ( + + )} + + ) : ( + <> + {segEls} + {/* Oberlicht-Kämpfer (waagrechte Linie transomHeight unter der OK). */} + {!dt && wt && (wt.transomHeight ?? 0) > 0 && ( + + )} + {/* Kämpfer-/Sprossen-Zeilen (mullionRows − 1 waagrechte Teiler im + Hauptfeld unterhalb eines etwaigen Oberlichts). */} + {!dt && + wt && + (() => { + const rows = Math.max(1, Math.round(wt.mullionRows ?? 1)); + if (rows <= 1) return null; + const top = originY + px(wt.transomHeight ?? 0); + const fieldH = px(h) - px(wt.transomHeight ?? 0); + return Array.from({ length: rows - 1 }, (_, k) => ( + + )); + })()} + {/* Sprossen-Spalten (mullionCols − 1 vertikale Teiler im + Hauptfeld unterhalb eines etwaigen Oberlichts). */} + {!dt && + wt && + (() => { + const cols = Math.max(1, Math.round(wt.mullionCols ?? 1)); + if (cols <= 1) return null; + const top = originY + px(wt.transomHeight ?? 0); + const fieldH = px(h) - px(wt.transomHeight ?? 0); + const fieldW = px(w); + return Array.from({ length: cols - 1 }, (_, k) => ( + + )); + })()} + + )} + + ); +} diff --git a/src/ui/ExportDxfDialog.tsx b/src/ui/ExportDxfDialog.tsx index 6e04f69..d1fb808 100644 --- a/src/ui/ExportDxfDialog.tsx +++ b/src/ui/ExportDxfDialog.tsx @@ -13,16 +13,25 @@ import { Dropdown } from "./Dropdown"; /** Entscheidung, die der Dialog beim Bestätigen liefert. */ export interface ExportDxfDecision { includeHatches: boolean; + /** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */ + selectionOnly: boolean; } export interface ExportDxfDialogProps { /** Titel/Geschossname (nur Anzeige im Dialogkopf). */ planTitle: string; + /** s. `ExportPdfDialogProps.selectionCount`. */ + selectionCount?: number; onExport: (decision: ExportDxfDecision) => void; onClose: () => void; } -export function ExportDxfDialog({ planTitle, onExport, onClose }: ExportDxfDialogProps) { +export function ExportDxfDialog({ + planTitle, + selectionCount = 0, + onExport, + onClose, +}: ExportDxfDialogProps) { useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); @@ -32,8 +41,10 @@ export function ExportDxfDialog({ planTitle, onExport, onClose }: ExportDxfDialo }, [onClose]); const [includeHatches, setIncludeHatches] = useState(true); + const [selectionOnly, setSelectionOnly] = useState(false); - const onConfirm = () => onExport({ includeHatches }); + const onConfirm = () => + onExport({ includeHatches, selectionOnly: selectionCount > 0 && selectionOnly }); return (
@@ -73,6 +84,19 @@ export function ExportDxfDialog({ planTitle, onExport, onClose }: ExportDxfDialo
{t("exportDxf.unitsNote")}
+ + {selectionCount > 0 && ( +
+ +
+ )}
diff --git a/src/ui/ExportPdfDialog.tsx b/src/ui/ExportPdfDialog.tsx index aec1de9..b0bd93b 100644 --- a/src/ui/ExportPdfDialog.tsx +++ b/src/ui/ExportPdfDialog.tsx @@ -10,7 +10,7 @@ import { useEffect, useState } from "react"; import { t } from "../i18n"; import { Dropdown } from "./Dropdown"; -import { SCALE_PRESETS } from "./TopBar"; +import { SCALE_PRESETS, parseScaleInput } from "./TopBar"; import type { Orientation, PaperFormat } from "../export/exportPdf"; import { pageSizeMm } from "../export/exportPdf"; @@ -19,6 +19,8 @@ export interface ExportPdfDecision { scaleDenominator: number; paper: PaperFormat; orientation: Orientation; + /** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */ + selectionOnly: boolean; } export interface ExportPdfDialogProps { @@ -31,7 +33,18 @@ export interface ExportPdfDialogProps { * „passt aufs Blatt?"-Warnung. Optional. */ contentMeters?: { w: number; h: number }; + /** + * Anzahl aktuell ausgewählter Elemente (über alle Arten) — > 0 blendet den + * „nur Auswahl exportieren"-Schalter ein (Nutzer-Wunsch: „Export + * exportiert immer den GANZEN Plan"). 0/fehlend: kein Schalter, Export + * bleibt wie bisher immer der ganze Plan. + */ + selectionCount?: number; onExport: (decision: ExportPdfDecision) => void; + /** Zweiter Export-Weg (Nutzer-Wunsch „Kein SVG-Export") — nutzt dieselbe + * Massstab/Papier/Ausrichtung-Auswahl wie der PDF-Export, nur als + * eigenständiger SVG-Download statt eines gerenderten PDF. */ + onExportSvg?: (decision: ExportPdfDecision) => void; onClose: () => void; } @@ -39,7 +52,9 @@ export function ExportPdfDialog({ initialScale, planTitle, contentMeters, + selectionCount = 0, onExport, + onExportSvg, onClose, }: ExportPdfDialogProps) { useEffect(() => { @@ -53,6 +68,20 @@ export function ExportPdfDialog({ const [scale, setScale] = useState(initialScale); const [paper, setPaper] = useState("a4"); const [orientation, setOrientation] = useState("landscape"); + const [selectionOnly, setSelectionOnly] = useState(false); + // Freitext-Massstab (Nutzer-Wunsch: „PDF-Export-Massstab nur 9 feste + // Presets, kein Freitext für z. B. 1:75") — eigenes Feld statt eines + // dritten `__custom__`-Dropdown-Eintrags mit Popup-Prompt (wie im + // TopBar-Vorbild): hier läuft der Dialog bereits selbst als Overlay mit + // eigenem Escape-Handler, ein verschachtelter zweiter Overlay-Dialog + // (`PromptDialog`) würde bei Escape BEIDE schliessen (window-weite + // Listener, keine Bubbling-Trennung). `parseScaleInput` (dieselbe + // Funktion wie im TopBar) akzeptiert „1:75" ODER „75". + const [customScaleText, setCustomScaleText] = useState(""); + const applyCustomScale = () => { + const n = parseScaleInput(customScaleText); + if (n != null) setScale(n); + }; // Passt der Plan im gewählten Massstab aufs Blatt (abzüglich Rand)? Best-effort- // Hinweis; der Export läuft trotzdem (Plan ragt dann über den Blattrand). @@ -67,12 +96,20 @@ export function ExportPdfDialog({ ); })(); - const onConfirm = () => onExport({ scaleDenominator: scale, paper, orientation }); + const decision = (): ExportPdfDecision => ({ + scaleDenominator: scale, + paper, + orientation, + selectionOnly: selectionCount > 0 && selectionOnly, + }); + const onConfirm = () => onExport(decision()); + const onConfirmSvg = () => onExportSvg?.(decision()); - const scaleOptions = SCALE_PRESETS.map((n) => ({ - value: String(n), - label: `1:${n}`, - })); + const inPresets = SCALE_PRESETS.includes(scale); + const scaleOptions = [ + ...(inPresets ? [] : [{ value: String(scale), label: `1:${scale}` }]), + ...SCALE_PRESETS.map((n) => ({ value: String(n), label: `1:${n}` })), + ]; return (
@@ -111,6 +148,19 @@ export function ExportPdfDialog({ triggerClassName="tb-dd-mono" options={scaleOptions} /> +
+ setCustomScaleText(e.target.value)} + onBlur={applyCustomScale} + onKeyDown={(e) => { + if (e.key === "Enter") applyCustomScale(); + }} + /> +
@@ -139,6 +189,19 @@ export function ExportPdfDialog({ />
+ {selectionCount > 0 && ( +
+ +
+ )} + {!fits &&
{t("export.warnFit")}
}
@@ -146,8 +209,13 @@ export function ExportPdfDialog({ + {onExportSvg && ( + + )}
diff --git a/src/ui/FreeColorPicker.tsx b/src/ui/FreeColorPicker.tsx new file mode 100644 index 0000000..c4aefb6 --- /dev/null +++ b/src/ui/FreeColorPicker.tsx @@ -0,0 +1,141 @@ +// Inhalt des „Frei"-Farbwahl-Bereichs — eine Bank-Leiste (mitgelieferte +// Paletten: Einfach/Tango/Material/RAL, dazu JEDE sichtbare eigene Palette +// als eigene Bank) + RGB/CMYK-Mischer für exakte Werte. Reiner Inhalt ohne +// Popover-Hülle (die bringt jeweils der Aufrufer mit) — genutzt vom +// „Frei"-Zweig in `PenColorField.tsx` UND von `PenSwatchPicker.tsx` +// (Stift-Farbdefinition im Stiftsatz-Tab). +// +// BEWUSST kein Dropdown hier drin: das Popover schliesst bei Aussenklick, +// und ein Dropdown rendert sein Menü in ein EIGENES Portal an `document.body` +// — ein Klick darin liegt damit ausserhalb des Popover-DOM und hat das +// Popover sofort mitgeschlossen (Nutzer-Report). Jede Palette ist deshalb +// eine eigene Bank in der Segmented-Leiste, ohne zweite Popover-Ebene. +// +// Verwaltung (anlegen/umbenennen/löschen/ein-/ausblenden, Farben entfernen) +// liegt NICHT hier, sondern im Ressourcen-Manager (`resourceManager/ +// PalettesTab.tsx`) — hier gibt es nur Wählen + „aktuelle Farbe ablegen". +// Alle Projektdaten kommen als PROPS (kein Store-Zugriff): der Ressourcen- +// Manager läuft auch als eigenes natives Fenster ohne gemeinsamen Store. + +import { useState } from "react"; +import { FREE_COLOR_PALETTE } from "../model/penSets"; +import { MATERIAL_PALETTE, RAL_CLASSIC, TANGO_PALETTE } from "../model/color"; +import type { BuiltinPaletteBanks, CustomPalette } from "../model/types"; +import { Swatch } from "./ColorSwatchCell"; +import { ColorMixer } from "./ColorMixer"; +import { Segmented } from "./resourceManager/fields"; +import { t } from "../i18n"; + +export interface FreeColorPickerProps { + color: string; + onChange: (hex: string) => void; + /** Eigene Paletten des Projekts; nur `visible !== false` erscheinen als Bank. */ + customPalettes?: CustomPalette[]; + /** Sichtbarkeit der mitgelieferten Bänke; fehlender Schlüssel = sichtbar. */ + builtinBanks?: BuiltinPaletteBanks; + /** Legt die AKTUELLE Farbe in der angegebenen eigenen Palette ab („+"-Zelle). */ + onSaveColor?: (paletteId: string, hex: string) => void; +} + +/** Eine Bank: fester Satz Farben (mitgeliefert) oder eine eigene Palette. */ +interface Bank { + id: string; + label: string; + entries: { hex: string; title: string }[]; + /** Gesetzt nur bei eigenen Paletten — schaltet die „+"-Zelle frei. */ + paletteId?: string; + hint?: string; +} + +export function FreeColorPicker({ + color, + onChange, + customPalettes, + builtinBanks, + onSaveColor, +}: FreeColorPickerProps) { + const banks: Bank[] = []; + if (builtinBanks?.simple !== false) { + banks.push({ + id: "simple", + label: t("pen.paletteSimple"), + entries: FREE_COLOR_PALETTE.map((hex) => ({ hex, title: hex })), + }); + } + if (builtinBanks?.tango !== false) { + banks.push({ + id: "tango", + label: "Tango", + entries: TANGO_PALETTE.map((c) => ({ hex: c.hex, title: c.name })), + }); + } + if (builtinBanks?.material !== false) { + banks.push({ + id: "material", + label: "Material", + entries: MATERIAL_PALETTE.map((c) => ({ hex: c.hex, title: c.name })), + }); + } + if (builtinBanks?.ral !== false) { + banks.push({ + id: "ral", + label: "RAL", + entries: RAL_CLASSIC.map((c) => ({ hex: c.hex, title: `RAL ${c.code} — ${c.name}` })), + hint: t("pen.ralHint"), + }); + } + for (const p of customPalettes ?? []) { + if (p.visible === false) continue; + banks.push({ + id: `custom-${p.id}`, + label: p.name, + paletteId: p.id, + entries: p.colors.map((hex) => ({ hex, title: hex })), + }); + } + + const [bankId, setBankId] = useState(banks[0]?.id ?? ""); + const active = banks.find((b) => b.id === bankId) ?? banks[0]; + + return ( +
+ {banks.length > 1 && ( + ({ value: b.id, label: b.label }))} + /> + )} + {active && ( + <> +
+ {active.paletteId && onSaveColor && ( + + )} + {active.entries.map((e) => ( + onChange(e.hex)} + /> + ))} +
+ {active.hint &&
{active.hint}
} + {active.paletteId && active.entries.length === 0 && ( +
{t("pen.customEmpty")}
+ )} + + )} + +
+ ); +} diff --git a/src/ui/ImportDialog.tsx b/src/ui/ImportDialog.tsx index c0e20d1..ad6bad9 100644 --- a/src/ui/ImportDialog.tsx +++ b/src/ui/ImportDialog.tsx @@ -178,10 +178,15 @@ export function ImportDialog({ {loading ? ( - // DWG wird gelesen (WASM lädt/parst) → Ladehinweis, nur Abbrechen. + // Datei wird gelesen/geparst (DWG: WASM; DXF: Web Worker, s. + // dxfParserAsync.ts) → Ladehinweis, nur Abbrechen.
-
{t("import.dwg.heading")}
-
{t("import.dwg.loading")}
+
+ {t(isDwg ? "import.dwg.heading" : "import.loading.heading")} +
+
+ {t(isDwg ? "import.dwg.loading" : "import.loading.hint")} +
) : isDwg ? ( // DWG konnte nicht gelesen werden → ODA-Fallback-Hinweis. diff --git a/src/ui/LayoutSheet.tsx b/src/ui/LayoutSheet.tsx index 5c45d59..bff0646 100644 --- a/src/ui/LayoutSheet.tsx +++ b/src/ui/LayoutSheet.tsx @@ -9,7 +9,11 @@ // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). import { useEffect, useRef, useState } from "react"; -import type { PointerEvent as ReactPointerEvent, MouseEvent as ReactMouseEvent } from "react"; +import type { + PointerEvent as ReactPointerEvent, + MouseEvent as ReactMouseEvent, + CSSProperties, +} from "react"; import type { Layout, LayoutAnnotation, @@ -56,6 +60,7 @@ import { import { RichTextEditor } from "../text/RichTextEditor"; import { docFromText } from "../text/richText"; import { wrapDocToLines, type SvgLine } from "../text/renderHtml"; +import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontMetrics"; import { readImageFile, defaultImageSizeMm } from "../io/imageAsset"; import { rasterizePdfPages } from "../io/pdfImport"; import type { ToolId } from "../tools/types"; @@ -88,6 +93,9 @@ export function ViewportPlan({ } try { const codes = visibleCodesFromSnapshot(snap); + // Massstab ZUERST auflösen: er geht in die Plan-Erzeugung ein, weil + // Bemassungs-Feinheiten in Papier-mm angegeben sind (s. model/dimension.ts). + const scaleN = resolveViewportScale(viewport, snap); const plan = generatePlan( project, snap.activeLevelId, @@ -96,8 +104,9 @@ export function ViewportPlan({ snap.detail, false, false, + true, + scaleN, ); - const scaleN = resolveViewportScale(viewport, snap); const print = planToPrintSvg(plan, { scaleDenominator: scaleN, pageWidthMm: viewport.widthMm, @@ -195,8 +204,17 @@ export interface LayoutSheetHandlers { * eines Text-Rahmens sofort inline hineinzuschreiben, s. `inlineEdit`). */ onAddAnnotation: (kind: LayoutAnnotation["kind"], init: LayoutAnnotationPatch) => string; - /** Ändert Felder einer Annotation (Position/Farbe/Strichstärke/Text). */ - onPatchAnnotation: (annotationId: string, patch: LayoutAnnotationPatch) => void; + /** + * Ändert Felder einer Annotation (Position/Farbe/Strichstärke/Text). + * `coalesceKey`: s. `projectSlice.ts` `setProject` — vom Inline-Text-Editor + * genutzt, damit EIN Tipp-Vorgang EINEN Undo-Schritt erzeugt statt bei + * jedem Tastendruck einen neuen zu pushen (s. `inlineEdit`-Block unten). + */ + onPatchAnnotation: ( + annotationId: string, + patch: LayoutAnnotationPatch, + coalesceKey?: string, + ) => void; /** Entfernt eine Annotation per Id. */ onRemoveAnnotation: (annotationId: string) => void; } @@ -947,6 +965,13 @@ export function LayoutSheetView({ style={{ position: "absolute", inset: 0, pointerEvents: "none" }} > {annotations.map((ann) => { + // Während des Inline-Editors NICHT zusätzlich statisch zeichnen + // (nur bei Text-Annotationen möglich, s. `inlineEdit`-Block + // unten) — sonst blieben Reste des alten Umbruchs sichtbar, + // weil das SVG nach geschätzter Zeichenbreite umbricht, der + // Editor-Browser aber nach echter Font-Metrik (leicht andere + // Zeilenumbrüche, Editor-Weiss deckt nicht jede Abweichung). + if (ann.id === inlineEdit?.id) return null; const a = annotPreview && annotPreview.id === ann.id ? annotPreview : ann; return ; })} @@ -1274,10 +1299,25 @@ export function LayoutSheetView({ nach dem Aufziehen) ODER eine per HUD „✎" geöffnete bestehende. Jede Änderung schreibt sofort zurück (`onPatchAnnotation`); ein Klick daneben (Backdrop) oder Escape schliesst nur, es gibt nichts zu - verwerfen. Skaliert die feste 12-pt-Basisgrösse des RichTextEditor - (s. RichTextEditor.tsx `renderHtml`) via CSS-Transform auf die - Schriftgrösse der Annotation UND den aktuellen Blatt-Zoom — Breite - bricht dadurch zoomunabhängig bei `widthMm` um. */} + verwerfen. WYSIWYG: Schriftgrösse UND Feldhöhe folgen dem echten + Blatt-Zoom über die CSS-Variablen `--rt-font-size`/`--rt-min-height` + (identisches Muster wie PlanView.tsx, s. dort) — NUR die Textfläche + skaliert, NICHT die Toolbar. Vorher lief das über ein + `transform:scale()` auf die GANZE Box (inkl. Toolbar, die dadurch + beim Reinzoomen riesig/unbedienbar wurde) UND `RichTextEditor` + schrieb pro Run trotzdem eine ABSOLUTE `pt`-Grösse (per Inline- + `style` auf jedem ``), die die geerbte Container-Grösse + ignoriert hätte, ohne den Transform-Umweg — beides zusammen war der + Bug hinter "Editor ist immer unterschiedlich gross wie der Text". + `sizeUnit="em"` auf `RichTextEditor` lässt Runs jetzt relativ zur + geerbten Grösse skalieren, s. `text/renderHtml.ts`. ZUSÄTZLICHER + Positions-Fix (Folgemeldung "Editor ist tiefer als der Text"): die + Toolbar stand bisher im normalen Fluss ÜBER der Textfläche und + schob sie um ihre eigene, zoomunabhängige Höhe nach unten — bei + üblichem Zoom mehr als die EINE Zeilenhöhe Versatz, mit der die + Box positioniert wird. `.rt-toolbar` schwebt jetzt per CSS + (`position:absolute; bottom:100%`, s. styles.css) OBERHALB der + Fläche, ausserhalb von deren Layout-Fluss. */} {inlineEdit && (() => { const ann = annotations.find((a) => a.id === inlineEdit.id); @@ -1286,16 +1326,29 @@ export function LayoutSheetView({ const widthMm = ann.widthMm ?? 60; const contentHeightMm = annotationBoundsMm(ann).heightMm; const heightMm = Math.max(inlineEdit.minHeightMm, contentHeightMm); - const FONT_PX_AT_12PT = 16; // 12pt @ 96dpi (RichTextEditor-Default). - const scale = (ann.heightMm * tf.scale) / FONT_PX_AT_12PT; - const unscaledWidth = widthMm * (FONT_PX_AT_12PT / ann.heightMm); - const unscaledMinHeight = heightMm * (FONT_PX_AT_12PT / ann.heightMm); - const screen = mmToScreen(tf, { xMm: ann.xMm, yMm: ann.yMm - ann.heightMm }); + const fontSizePx = Math.max(9, ann.heightMm * tf.scale); + const widthPx = widthMm * tf.scale; + const minHeightPx = heightMm * tf.scale; + // Baseline → Box-Oberkante: echtes Font-Measuring statt der groben + // "ganzes heightMm"-Näherung (s. PlanView.tsx, identischer Fix). + const baselineFromTop = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); + const screen = mmToScreen(tf, { + xMm: ann.xMm, + yMm: ann.yMm - ann.heightMm * baselineFromTop, + }); + const cssVars = { + "--rt-font-size": `${fontSizePx}px`, + "--rt-min-height": `${minHeightPx}px`, + } as CSSProperties; const commit = (edited: typeof doc) => - handlers.onPatchAnnotation(ann.id, { - doc: edited, - text: edited.paragraphs.map((p) => p.runs.map((r) => r.text).join("")).join("\n"), - }); + handlers.onPatchAnnotation( + ann.id, + { + doc: edited, + text: edited.paragraphs.map((p) => p.runs.map((r) => r.text).join("")).join("\n"), + }, + `layoutAnnotationText:${ann.id}`, + ); return ( <>
e.stopPropagation()} onKeyDown={(e) => { @@ -1322,7 +1373,7 @@ export function LayoutSheetView({ } }} > - +
); diff --git a/src/ui/OpeningEditorDialog.tsx b/src/ui/OpeningEditorDialog.tsx index c5679d9..58e7df8 100644 --- a/src/ui/OpeningEditorDialog.tsx +++ b/src/ui/OpeningEditorDialog.tsx @@ -10,7 +10,7 @@ // wiederverwendbarer Stil, wirkt auf alle Instanzen) UND INSTANZ-Parameter // (Grösse/Position dieser Öffnung). Bezeichner englisch, UI-Text deutsch. -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useState } from "react"; import { t } from "../i18n"; import type { DoorType, @@ -21,6 +21,7 @@ import type { WindowType, } from "../model/types"; import { getDoorType, getWindowType, sashesOfWindowType, glazingPanesOf } from "../model/types"; +import { ElevationPreview } from "./ElevationPreview"; /** P0-Kategorien der Sidebar, je nach Öffnungsart. */ type CatId = @@ -707,238 +708,3 @@ function TuerblattPanel({ ); } - -// ── Live-Ansicht (Elevation, SVG) ─────────────────────────────────────────── - -/** - * Frontal-Ansicht der Öffnung aus den aktuellen Werten: Rahmen, Flügel/Pfosten - * (mit Öffnungslinien je Flügel), Verglasungshinweis und Rollladenkasten. Rein - * aus den Modellwerten gezeichnet — kein Renderer-Roundtrip, deterministisch. - */ -function ElevationPreview({ - opening, - wt, - dt, -}: { - opening: Opening; - wt?: WindowType; - dt?: DoorType; -}) { - const geom = useMemo(() => { - const w = Math.max(0.1, opening.width); - const h = Math.max(0.1, opening.height); - const pad = 24; - const boxH = (!dt && wt?.shading?.create ? wt.shading.box.height : 0) || 0; - // Zeichenfläche auf ~260×300 skalieren, Seitenverhältnis erhalten. - const availW = 220; - const availH = 260; - const totalH = h + boxH; - const scale = Math.min(availW / w, availH / totalH); - const px = (m: number) => m * scale; - return { w, h, boxH, pad, scale, px, totalH }; - }, [opening.width, opening.height, wt, dt]); - - const { w, h, boxH, pad, px } = geom; - const svgW = px(w) + pad * 2; - const svgH = px(h + boxH) + pad * 2; - const frameW = px((!dt ? wt?.frameWidth : dt?.frameWidth) ?? 0.06); - const originY = pad + px(boxH); - - // Flügel-/Pfostenaufteilung: gleichmässig (autoWidth) bzw. feste Breiten. - const sashes = !dt && wt ? sashesOfWindowType(wt) : []; - const fixedTotal = sashes.reduce( - (a, s) => a + (s.kind === "pfosten" ? s.postWidth ?? 0.06 : s.autoWidth ? 0 : s.width ?? 0), - 0, - ); - const autoCount = sashes.filter((s) => s.kind === "fluegel" && (s.autoWidth ?? true)).length; - const autoW = autoCount > 0 ? Math.max(0.05, (w - fixedTotal) / autoCount) : 0; - const panes = !dt && wt ? glazingPanesOf(wt) : 1; - - // Segmentbreiten (Meter) je Sash. - const segW = sashes.map((s) => - s.kind === "pfosten" - ? s.postWidth ?? 0.06 - : s.autoWidth ?? true - ? autoW - : s.width ?? autoW, - ); - - const strokeMain = "var(--ink)"; - const strokeMuted = "var(--muted)"; - const glass = "rgba(120,180,220,0.18)"; - - let cursor = 0; - const segEls: JSX.Element[] = []; - sashes.forEach((s, i) => { - const x0 = pad + px(cursor); - const wSeg = px(segW[i]); - cursor += segW[i]; - if (s.kind === "pfosten") { - segEls.push( - , - ); - return; - } - // Flügelrahmen + Glas + Öffnungslinien. - const gx = x0 + frameW * 0.4; - const gy = originY + frameW * 0.4; - const gw = Math.max(1, wSeg - frameW * 0.8); - const gh = Math.max(1, px(h) - frameW * 0.8); - segEls.push( - - - - {/* Verglasung: zusätzliche parallele Glaslinien = Scheibenzahl − 1. */} - {Array.from({ length: Math.max(0, panes - 1) }, (_, k) => ( - - ))} - {/* Öffnungslinien (Dreieck) je nach Anschlag; nicht bei fest. */} - {s.opening !== "fest" && - (s.hingeSide === "right" ? ( - - ) : ( - - ))} - , - ); - }); - - return ( - - {/* Rollladenkasten über der Öffnung (nur Fenster mit shading.create). */} - {boxH > 0 && ( - - )} - {/* Blendrahmen (Aussenkontur). */} - - {/* Für Türen: einfaches Türblatt statt Flügelraster. */} - {dt ? ( - <> - - {dt.leafCount === 2 && ( - - )} - - ) : ( - <> - {segEls} - {/* Oberlicht-Kämpfer (waagrechte Linie transomHeight unter der OK). */} - {!dt && wt && (wt.transomHeight ?? 0) > 0 && ( - - )} - {/* Kämpfer-/Sprossen-Zeilen (mullionRows − 1 waagrechte Teiler im - Hauptfeld unterhalb eines etwaigen Oberlichts). */} - {!dt && - wt && - (() => { - const rows = Math.max(1, Math.round(wt.mullionRows ?? 1)); - if (rows <= 1) return null; - const top = originY + px(wt.transomHeight ?? 0); - const fieldH = px(h) - px(wt.transomHeight ?? 0); - return Array.from({ length: rows - 1 }, (_, k) => ( - - )); - })()} - {/* Sprossen-Spalten (mullionCols − 1 vertikale Teiler im - Hauptfeld unterhalb eines etwaigen Oberlichts). */} - {!dt && - wt && - (() => { - const cols = Math.max(1, Math.round(wt.mullionCols ?? 1)); - if (cols <= 1) return null; - const top = originY + px(wt.transomHeight ?? 0); - const fieldH = px(h) - px(wt.transomHeight ?? 0); - const fieldW = px(w); - return Array.from({ length: cols - 1 }, (_, k) => ( - - )); - })()} - - )} - - ); -} diff --git a/src/ui/PenColorField.tsx b/src/ui/PenColorField.tsx index 9be5c75..8da0d7a 100644 --- a/src/ui/PenColorField.tsx +++ b/src/ui/PenColorField.tsx @@ -14,8 +14,9 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import type { MouseEvent } from "react"; import { createPortal } from "react-dom"; -import type { ColorPen, PenStyle } from "../model/types"; -import { FREE_COLOR_PALETTE } from "../model/penSets"; +import type { BuiltinPaletteBanks, ColorPen, CustomPalette, PenStyle } from "../model/types"; +import { Swatch } from "./ColorSwatchCell"; +import { FreeColorPicker } from "./FreeColorPicker"; import { Segmented } from "./resourceManager/fields"; import { t } from "../i18n"; @@ -45,33 +46,11 @@ export interface PenColorFieldProps { * „eigener Wert" editierbar sind (analog `ColorField.disabled`). */ disabled?: boolean; -} - -/** Ein Popover-Swatch (Freie Palette ODER Stift-Raster teilen dieselbe Zelle). */ -function Swatch({ - color, - active, - title, - label, - onClick, -}: { - color: string; - active: boolean; - title: string; - label?: string; - onClick: () => void; -}) { - return ( - - ); + /** Eigene Paletten + Bank-Sichtbarkeit fürs „Frei"-Raster (s. `FreeColorPicker`). */ + customPalettes?: CustomPalette[]; + builtinBanks?: BuiltinPaletteBanks; + /** Legt die aktuelle Farbe in einer eigenen Palette ab („+"-Zelle im Raster). */ + onSaveColor?: (paletteId: string, hex: string) => void; } export function PenColorField({ @@ -83,6 +62,9 @@ export function PenColorField({ onPenChange, showWeight, disabled, + customPalettes, + builtinBanks, + onSaveColor, }: PenColorFieldProps) { const [open, setOpen] = useState(false); const [pos, setPos] = useState({ left: 0, top: 0 }); @@ -136,14 +118,25 @@ export function PenColorField({ if (popRef.current?.contains(tgt) || btnRef.current?.contains(tgt)) return; close(); }; - const onScrollOrResize = () => close(); + // Scrollt der Nutzer INNERHALB des Popovers (langes Paletten-Raster, z. B. + // RAL mit 168 Farben), darf das Popover NICHT schliessen — der Listener + // läuft in der Capture-Phase und sieht sonst auch das Scrollen des eigenen + // Rasters (Nutzer-Report: „bei RAL lässt es sich nicht scrollen"). + // Geschlossen wird nur bei Scrollen AUSSERHALB (Plan/Panel bewegt sich weg + // unter dem Popover) und bei Resize. + const onScroll = (e: Event) => { + const tgt = e.target as Node | null; + if (tgt && popRef.current?.contains(tgt)) return; + close(); + }; + const onResize = () => close(); window.addEventListener("pointerdown", onPointerDown, true); - window.addEventListener("scroll", onScrollOrResize, true); - window.addEventListener("resize", onScrollOrResize); + window.addEventListener("scroll", onScroll, true); + window.addEventListener("resize", onResize); return () => { window.removeEventListener("pointerdown", onPointerDown, true); - window.removeEventListener("scroll", onScrollOrResize, true); - window.removeEventListener("resize", onScrollOrResize); + window.removeEventListener("scroll", onScroll, true); + window.removeEventListener("resize", onResize); }; }, [open]); @@ -262,7 +255,7 @@ export function PenColorField({ )} {isPen ? ( -
+
{pens.map((p) => ( {t("resources.pens.empty")}
}
) : ( - <> -
- {FREE_COLOR_PALETTE.map((hex) => ( - { - pickFree(hex); - close(); - }} - /> - ))} -
- - + )} , document.body, diff --git a/src/ui/PenSwatchPicker.tsx b/src/ui/PenSwatchPicker.tsx new file mode 100644 index 0000000..175faa3 --- /dev/null +++ b/src/ui/PenSwatchPicker.tsx @@ -0,0 +1,114 @@ +// Swatch mit eigenem Popover für die Stift-FARBDEFINITION selbst (Stiftsatz- +// Tab: „welche Farbe HAT Stift Nr. 3"). Anders als `PenColorField` (das einem +// ELEMENT einen Stift zuweist) geht es hier nur um freie Farbwahl — dieselbe +// Popover-Mechanik wie `PenColorField`/`Dropdown.tsx` (eigene Positionierungs- +// /Aussenklick-Logik), aber ohne Frei/Stift-Umschalter. + +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { FreeColorPicker } from "./FreeColorPicker"; +import type { BuiltinPaletteBanks, CustomPalette } from "../model/types"; + +const EDGE_PAD = 4; + +export function PenSwatchPicker({ + color, + onChange, + customPalettes, + builtinBanks, + onSaveColor, +}: { + color: string; + onChange: (hex: string) => void; + customPalettes?: CustomPalette[]; + builtinBanks?: BuiltinPaletteBanks; + onSaveColor?: (paletteId: string, hex: string) => void; +}) { + const [open, setOpen] = useState(false); + const [pos, setPos] = useState({ left: 0, top: 0 }); + const btnRef = useRef(null); + const popRef = useRef(null); + + const openPopover = () => { + const r = btnRef.current?.getBoundingClientRect(); + if (r) setPos({ left: r.left, top: r.bottom + 4 }); + setOpen(true); + }; + const close = () => setOpen(false); + + useLayoutEffect(() => { + if (!open) return; + const el = popRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + const vw = window.innerWidth; + const vh = window.innerHeight; + setPos((p) => { + let left = p.left; + let top = p.top; + if (left + rect.width > vw - EDGE_PAD) left = vw - rect.width - EDGE_PAD; + if (top + rect.height > vh - EDGE_PAD) { + const r = btnRef.current?.getBoundingClientRect(); + top = r ? r.top - rect.height - 4 : vh - rect.height - EDGE_PAD; + } + if (left < EDGE_PAD) left = EDGE_PAD; + if (top < EDGE_PAD) top = EDGE_PAD; + return { left, top }; + }); + }, [open]); + + useEffect(() => { + if (!open) return; + const onPointerDown = (e: PointerEvent) => { + const tgt = e.target as Node; + if (popRef.current?.contains(tgt) || btnRef.current?.contains(tgt)) return; + close(); + }; + // Scrollt der Nutzer INNERHALB des Popovers (langes Paletten-Raster, z. B. + // RAL mit 168 Farben), darf das Popover NICHT schliessen — der Listener + // läuft in der Capture-Phase und sieht sonst auch das Scrollen des eigenen + // Rasters (Nutzer-Report: „bei RAL lässt es sich nicht scrollen"). + // Geschlossen wird nur bei Scrollen AUSSERHALB (Plan/Panel bewegt sich weg + // unter dem Popover) und bei Resize. + const onScroll = (e: Event) => { + const tgt = e.target as Node | null; + if (tgt && popRef.current?.contains(tgt)) return; + close(); + }; + const onResize = () => close(); + window.addEventListener("pointerdown", onPointerDown, true); + window.addEventListener("scroll", onScroll, true); + window.addEventListener("resize", onResize); + return () => { + window.removeEventListener("pointerdown", onPointerDown, true); + window.removeEventListener("scroll", onScroll, true); + window.removeEventListener("resize", onResize); + }; + }, [open]); + + return ( + <> + + ))} + +
+ {tab === "general" && ( + <>
{t("settings.section.workspace")}
@@ -240,7 +305,25 @@ export function SettingsDialog({ />
{t("settings.referenceElevation.hint")}
+ + )} + {tab === "shortcuts" && ( + <> +
+
{t("settings.section.keyboardShortcuts")}
+ +
+ +
+
{t("settings.section.shortcuts")}
+ +
+ + )} + + {tab === "update" && ( + <>
{t("settings.section.update")}
@@ -331,6 +414,8 @@ export function SettingsDialog({ )}
+ + )}
{!windowed && ( @@ -389,3 +474,271 @@ function AccentColorField({ ); } + +/** + * Befehls-Kürzel-Remap (Nutzer-Wunsch: „Befehls-Kürzel sind hart codiert, + * keine Remap-UI"): listet die NUTZER-Übersteuerungen (aus localStorage) mit + * Löschen-Knopf + eine „Neu"-Zeile (Kürzel-Text + Befehls-Dropdown). Verwaltet + * ihren State selbst (lädt/speichert direkt über `commandAliasOverrides.ts`) + * — `onChange` ist nur ein Live-Hook fürs selbe Fenster, s. Prop-Kommentar + * bei `SettingsDialogProps.onAliasOverridesChange`. + */ +function AliasRemapSection({ onChange }: { onChange?: (overrides: Record) => void }) { + const [overrides, setOverrides] = useState>(() => loadAliasOverrides()); + const [newKey, setNewKey] = useState(""); + const [newCommand, setNewCommand] = useState(""); + const commands = allCommandNames(); + + const commit = (next: Record) => { + setOverrides(next); + saveAliasOverrides(next); + onChange?.(next); + }; + + const addOverride = () => { + const key = newKey.trim().toLowerCase(); + if (!isValidAliasKey(key) || !newCommand) return; + commit({ ...overrides, [key]: newCommand }); + setNewKey(""); + setNewCommand(""); + }; + + const removeOverride = (key: string) => { + const next = { ...overrides }; + delete next[key]; + commit(next); + }; + + const entries = Object.entries(overrides).sort(([a], [b]) => a.localeCompare(b)); + + return ( +
+
{t("settings.shortcuts.hint")}
+ {entries.length > 0 && ( +
+ {entries.map(([key, cmd]) => ( +
+ {key} + → + + +
+ ))} +
+ )} +
+ setNewKey(e.target.value)} + placeholder={t("settings.shortcuts.newKey")} + /> + → + + +
+
+ ); +} + +const CATEGORY_ORDER: ShortcutCategory[] = [ + "general", + "selection", + "edit", + "boolean", + "transform", + "group", + "tools", +]; + +/** + * Remap-UI für die ECHTEN Tastenkombinationen (`state/keyboardShortcuts.ts`) — + * Gegenstück zu `AliasRemapSection`, aber für `keydown`-Kürzel statt + * Befehlszeilen-Tipp-Alias. Verwaltet ihren State selbst (lädt/speichert + * direkt), `onChange` ist nur der Live-Hook fürs selbe Fenster (s. + * `SettingsDialogProps.onShortcutOverridesChange`). + * + * Aufnahme läuft über einen `keydown`-Listener in der CAPTURE-Phase + + * `stopPropagation`: die App-weiten Shortcut-Hooks (`useKeyboardShortcuts.ts`) + * hängen alle in der Bubble-Phase am selben `window` — ohne das Abfangen + * hier würde z. B. das Drücken von „m" während der Aufnahme (im INLINE- + * Overlay-Dialog, selbes Fenster) zusätzlich sofort die Bewegen-Transformation + * im Hintergrund auslösen. + */ +function ShortcutRemapSection({ + onChange, +}: { + onChange?: (overrides: ShortcutOverrides) => void; +}) { + const [overrides, setOverrides] = useState(() => loadShortcutOverrides()); + const [recordingId, setRecordingId] = useState(null); + const [error, setError] = useState<{ id: ShortcutId; message: string } | null>(null); + const [pendingConflict, setPendingConflict] = useState<{ + id: ShortcutId; + combo: string; + conflictWith: ShortcutId; + } | null>(null); + + const commit = (next: ShortcutOverrides) => { + setOverrides(next); + saveShortcutOverrides(next); + onChange?.(next); + }; + + useEffect(() => { + if (!recordingId) return; + const id = recordingId; + const def = shortcutDef(id); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.preventDefault(); + setRecordingId(null); + return; + } + const combo = comboFromEvent(e); + if (!combo) return; // reiner Modifikator-Tastendruck — weiter warten + e.preventDefault(); + e.stopPropagation(); + if (isReservedCombo(combo)) { + setError({ id, message: t("settings.keyboardShortcuts.reserved") }); + setRecordingId(null); + return; + } + if (def.bareKeyOnly && combo.includes("+")) { + setError({ id, message: t("settings.keyboardShortcuts.reserved") }); + setRecordingId(null); + return; + } + const conflict = findConflict(combo, id, overrides); + setRecordingId(null); + if (conflict) { + setPendingConflict({ id, combo, conflictWith: conflict }); + return; + } + commit({ ...overrides, [id]: combo }); + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [recordingId, overrides]); + + const hasOverrides = Object.keys(overrides).length > 0; + + return ( +
+
{t("settings.keyboardShortcuts.hint")}
+ {CATEGORY_ORDER.map((cat) => { + const defs = SHORTCUT_DEFS.filter((d) => d.category === cat); + if (defs.length === 0) return null; + return ( +
+
+ {t(`settings.keyboardShortcuts.category.${cat}` as TranslationKey)} +
+ {defs.map((def) => { + const combo = resolveCombo(def.id, overrides); + const isOverridden = def.id in overrides; + const recording = recordingId === def.id; + return ( +
+ + {t(def.labelKey as TranslationKey)} + + + {recording ? t("settings.keyboardShortcuts.recording") : formatCombo(combo)} + + + {isOverridden && ( + + )} + {error?.id === def.id &&
{error.message}
} + {pendingConflict?.id === def.id && ( +
+ {t("settings.keyboardShortcuts.conflict", { + action: t(shortcutDef(pendingConflict.conflictWith).labelKey as TranslationKey), + })} + +
+ )} +
+ ); + })} +
+ ); + })} + {hasOverrides && ( + + )} +
+ ); +} diff --git a/src/ui/SpectrumPicker.tsx b/src/ui/SpectrumPicker.tsx new file mode 100644 index 0000000..8740b6a --- /dev/null +++ b/src/ui/SpectrumPicker.tsx @@ -0,0 +1,73 @@ +// Visueller Farbwähler (klassisches Picker-Muster): eine Fläche für +// Sättigung (X) × Hellwert (Y) plus ein Farbton-Regler darunter. Arbeitet in +// HSV, weil genau das die zwei Achsen der Fläche sind — der Aufrufer +// (`ColorMixer.tsx`) hält den HSV-Puffer, damit der Farbton beim Ziehen in +// die schwarze/weisse Ecke nicht verloren geht (dort ist er mathematisch +// undefiniert, s. `model/color.ts`). +// +// Ohne Canvas: die Fläche ist die übliche Überlagerung aus zwei CSS- +// Verläufen (weiss→transparent horizontal, transparent→schwarz vertikal) +// über der vollgesättigten Farbtonfarbe. + +import { useRef } from "react"; +import type { PointerEvent as ReactPointerEvent } from "react"; +import type { Hsv } from "../model/color"; + +const clamp01 = (v: number) => Math.max(0, Math.min(1, v)); + +export function SpectrumPicker({ hsv, onChange }: { hsv: Hsv; onChange: (next: Hsv) => void }) { + const areaRef = useRef(null); + const hueRef = useRef(null); + + /** Zieh-Geste auf Fläche/Regler: Pointer-Capture, damit sie auch ausserhalb weiterläuft. */ + const drag = ( + ref: typeof areaRef, + e: ReactPointerEvent, + apply: (fx: number, fy: number) => void, + ) => { + const el = ref.current; + if (!el) return; + el.setPointerCapture(e.pointerId); + const move = (clientX: number, clientY: number) => { + const r = el.getBoundingClientRect(); + apply(clamp01((clientX - r.left) / r.width), clamp01((clientY - r.top) / r.height)); + }; + move(e.clientX, e.clientY); + const onMove = (ev: PointerEvent) => move(ev.clientX, ev.clientY); + const onUp = () => { + window.removeEventListener("pointermove", onMove); + window.removeEventListener("pointerup", onUp); + }; + window.addEventListener("pointermove", onMove); + window.addEventListener("pointerup", onUp); + }; + + return ( +
+
+ drag(areaRef, e, (fx, fy) => + onChange({ ...hsv, s: Math.round(fx * 100), v: Math.round((1 - fy) * 100) }), + ) + } + > + + + +
+
drag(hueRef, e, (fx) => onChange({ ...hsv, h: Math.round(fx * 360) }))} + > + +
+
+ ); +} diff --git a/src/ui/StatusBar.tsx b/src/ui/StatusBar.tsx index 85657c6..0faa3ca 100644 --- a/src/ui/StatusBar.tsx +++ b/src/ui/StatusBar.tsx @@ -201,6 +201,33 @@ function SnapControl({ /> {t("snap.onEdge")} + + + + +