diff --git a/src/core/index.ts b/src/core/index.ts index 09b5dc2..daff92d 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -10,6 +10,11 @@ export type { AlignMode } from './layout' export { buildJob, mirrorJobPaths } from './job' export type { JobOptions } from './job' export { buildTestCutJob, testCutPart, TEST_CUT_ORIGIN } from './testcut' +export { + VERDICTS, GRID_MIN_COUNT, GRID_MAX_COUNT, WIZARD_MAX_MARKS, slotCount, slotsPerRow, slotRows, slotPosition, + buildWizardJob, buildGridJobs, gridVariants, gridDefaults, suggestAdjustment +} from './materialWizard' +export type { Verdict, GridParam, GridPlan, Adjustment } from './materialWizard' export { uid } from './uid' export { importDxf } from './dxf' export { importPdf, setPdfWorkerSrc } from './pdf' @@ -23,7 +28,7 @@ export { textToParts, capHeightUnits, MAX_TEXT_CHARS } from './text' export type { ActiveProfileRef } from './materials' export type { TextFont, TextGlyph, TextOptions, TextResult } from './text' export { - BUILTIN_MATERIALS, MAX_PROFILE_NAME, cleanProfileName, sanitizeProfiles, upsertProfile, renameProfile, deleteProfile, + BUILTIN_MATERIALS, MAX_PROFILE_NAME, MAX_PROFILE_NOTE, RANGES as CUT_RANGES, cleanProfileName, cleanProfileNote, sanitizeProfiles, upsertProfile, renameProfile, deleteProfile, findMatchingProfile, isBuiltinName, isModified, updateProfile, resolveActiveProfile, sameName, materialLabel, findBuiltin } from './materials' export { MAX_IMPORT_BYTES, MAX_PART_POINTS, SIMPLIFY_TOLERANCE_MM, assertImportSize, dropInvalidPaths, douglasPeucker, simplifyPolyline, limitPoints } from './sanitize' diff --git a/src/core/materialWizard.test.ts b/src/core/materialWizard.test.ts new file mode 100644 index 0000000..ca6fb96 --- /dev/null +++ b/src/core/materialWizard.test.ts @@ -0,0 +1,249 @@ +import { describe, expect, it } from 'vitest' +import type { CutSettings, WorkArea } from '@shared/types' +import { DEFAULT_CUT } from '@shared/types' +import { + GRID_MAX_COUNT, GRID_MIN_COUNT, VERDICTS, WIZARD_CELL_H_MM, WIZARD_CELL_W_MM, WIZARD_MARGIN_MM, buildGridJobs, buildWizardJob, + gridDefaults, gridVariants, slotCount, slotPosition, slotRows, slotsPerRow, suggestAdjustment +} from './materialWizard' +import { RANGES, MAX_PROFILE_NOTE, sanitizeProfiles, updateProfile, upsertProfile, renameProfile } from './materials' +import { pointsBox } from './geom' +import { testCutPart } from './testcut' + +const wa: WorkArea = { name: 'x', width: 305, height: 305 } +const KEYS: (keyof CutSettings)[] = ['blade', 'force', 'speed', 'passes', 'overcut'] +const inRange = (c: CutSettings): boolean => KEYS.every((k) => c[k] >= RANGES[k][0] && c[k] <= RANGES[k][1]) + +describe('Testplatz-Raster', () => { + it('12x12-Matte: 4 Spalten, 7 Zeilen, Plätze zeilenweise von links nach rechts', () => { + expect(slotsPerRow(wa)).toBe(4) + expect(slotRows(wa)).toBe(7) + expect(slotCount(wa)).toBe(28) + expect(slotPosition(wa, 0)).toEqual({ x: WIZARD_MARGIN_MM, y: WIZARD_MARGIN_MM }) + expect(slotPosition(wa, 1)).toEqual({ x: WIZARD_MARGIN_MM + WIZARD_CELL_W_MM, y: WIZARD_MARGIN_MM }) + expect(slotPosition(wa, 4)).toEqual({ x: WIZARD_MARGIN_MM, y: WIZARD_MARGIN_MM + WIZARD_CELL_H_MM }) + }) + + it('kein Platz mehr: null; ungültige Plätze und zu kleine Flächen ebenfalls', () => { + expect(slotPosition(wa, 28)).toBeNull() + expect(slotPosition(wa, -1)).toBeNull() + expect(slotPosition(wa, 1.5)).toBeNull() + const tiny = { name: 't', width: 50, height: 305 } + expect(slotCount(tiny)).toBe(0) + expect(slotPosition(tiny, 0)).toBeNull() + expect(buildWizardJob(tiny, DEFAULT_CUT, 0, 1)).toBeNull() + }) + + it('alle Plätze liegen vollständig auf der Arbeitsfläche, ohne einander zu überlappen', () => { + const boxes = Array.from({ length: slotCount(wa) }, (_, s) => { + const job = buildWizardJob(wa, DEFAULT_CUT, s, (s % 9) + 1)! + const b = pointsBox(job.paths.flatMap((p) => p.points))! + expect(b.x).toBeGreaterThanOrEqual(WIZARD_MARGIN_MM - 1e-6) + expect(b.y).toBeGreaterThanOrEqual(WIZARD_MARGIN_MM - 1e-6) + expect(b.x + b.width).toBeLessThanOrEqual(wa.width - WIZARD_MARGIN_MM + 1e-6) + expect(b.y + b.height).toBeLessThanOrEqual(wa.height - WIZARD_MARGIN_MM + 1e-6) + return b + }) + for (let i = 0; i < boxes.length; i++) for (let j = i + 1; j < boxes.length; j++) { + const a = boxes[i], b = boxes[j] + const overlap = a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height + expect(overlap, `${i}/${j}`).toBe(false) + } + }) +}) + +describe('buildWizardJob', () => { + it('Testmuster (3 geschlossene Pfade) plus n Strichmarken (offene Zweipunkt-Linien) darüber', () => { + for (const n of [1, 3, 9]) { + const job = buildWizardJob(wa, DEFAULT_CUT, 5, n)! + const closed = job.paths.filter((p) => p.closed) + const marks = job.paths.filter((p) => !p.closed) + expect(closed).toHaveLength(3) + expect(marks).toHaveLength(n) + expect(marks.every((m) => m.points.length === 2)).toBe(true) + const patternTop = Math.min(...closed.flatMap((p) => p.points.map((q) => q.y))) + const marksBottom = Math.max(...marks.flatMap((p) => p.points.map((q) => q.y))) + expect(marksBottom).toBeLessThan(patternTop) + } + }) + + it('mehr als 9 Striche werden auf 9 begrenzt; Einstellungen und Ausfahren werden übernommen', () => { + const cut = { ...DEFAULT_CUT, force: 22 } + const job = buildWizardJob(wa, cut, 0, 15, 40)! + expect(job.paths.filter((p) => !p.closed)).toHaveLength(9) + expect(job.settings).toEqual(cut) + expect(job.ejectExtraMm).toBe(40) + expect(buildWizardJob(wa, cut, 0, 1)!.ejectExtraMm).toBeUndefined() + }) + + it('Muster hat die Größe des Testschnitts (55 x 25) an der Platzposition', () => { + const job = buildWizardJob(wa, DEFAULT_CUT, 1, 2)! + const pos = slotPosition(wa, 1)! + const b = pointsBox(job.paths.filter((p) => p.closed).flatMap((p) => p.points))! + expect(b.width).toBeCloseTo(55, 1) + expect(b.height).toBeCloseTo(25, 1) + expect(b.x).toBeCloseTo(pos.x, 6) + }) + + it('testCutPart() ohne Argument bleibt an der alten Position (10/10)', () => { + const p = testCutPart() + expect([p.x, p.y]).toEqual([10, 10]) + expect(testCutPart({ x: 3, y: 4 }).x).toBe(3) + }) +}) + +describe('gridVariants', () => { + it('Schrittfolge für Druck; übrige Werte bleiben', () => { + const v = gridVariants(DEFAULT_CUT, 'force', 8, 2, 5) + expect(v.map((c) => c.force)).toEqual([8, 10, 12, 14, 16]) + expect(v.every((c) => c.speed === DEFAULT_CUT.speed && c.blade === DEFAULT_CUT.blade)).toBe(true) + }) + + it('Anzahl 3..7, Klemmen auf den Bereich, Duplikate entfallen', () => { + expect(gridVariants(DEFAULT_CUT, 'force', 1, 1, 1)).toHaveLength(GRID_MIN_COUNT) + expect(gridVariants(DEFAULT_CUT, 'force', 1, 1, 99)).toHaveLength(GRID_MAX_COUNT) + const hi = gridVariants(DEFAULT_CUT, 'force', 30, 2, 5) + expect(hi.map((c) => c.force)).toEqual([30, 32, 33]) + const speed = gridVariants(DEFAULT_CUT, 'speed', 9, 1, 5) + expect(speed.map((c) => c.speed)).toEqual([9, 10]) + expect(gridVariants(DEFAULT_CUT, 'blade', 4, 0, 4)).toHaveLength(1) + expect(gridVariants(DEFAULT_CUT, 'blade', 2, 1.4, 3).every(inRange)).toBe(true) + }) +}) + +describe('gridDefaults', () => { + it('aktueller Wert liegt in der Mitte, Start bleibt im Bereich', () => { + expect(gridDefaults(DEFAULT_CUT, 'force', 5)).toEqual({ start: 6, step: 2 }) + expect(gridDefaults({ ...DEFAULT_CUT, force: 2 }, 'force', 7)).toEqual({ start: 1, step: 2 }) + expect(gridDefaults(DEFAULT_CUT, 'speed', 5)).toEqual({ start: 3, step: 1 }) + }) +}) + +describe('buildGridJobs', () => { + const cuts = gridVariants(DEFAULT_CUT, 'force', 6, 2, 5) + + it('ein Auftrag je Variante mit der jeweiligen Einstellung und 1..N Strichmarken', () => { + const plan = buildGridJobs(wa, cuts, 0)! + expect(plan.jobs).toHaveLength(5) + plan.jobs.forEach((job, i) => { + expect(job.settings).toEqual(cuts[i]) + expect(job.paths.filter((p) => p.closed)).toHaveLength(1) + expect(job.paths.filter((p) => !p.closed)).toHaveLength(i + 1) + }) + }) + + it('belegt eine ganze Zeile; mitten in einer Zeile beginnt das Raster in der nächsten', () => { + const cols = slotsPerRow(wa) + const a = buildGridJobs(wa, cuts, 0)! + expect(a.firstSlot).toBe(0) + expect(a.nextSlot).toBe(cols) + expect(a.slotsUsed).toBe(cols) + const b = buildGridJobs(wa, cuts, 2)! + expect(b.firstSlot).toBe(cols) + expect(b.nextSlot).toBe(2 * cols) + expect(b.slotsUsed).toBe(2 * cols - 2) + const rowY = (plan: NonNullable): number => Math.min(...plan.jobs.flatMap((j) => j.paths.flatMap((p) => p.points.map((q) => q.y)))) + expect(rowY(b)).toBeCloseTo(rowY(a) + WIZARD_CELL_H_MM, 6) + }) + + it('Quadrate 15 mm im Abstand 22 mm, nur der letzte Auftrag fährt aus', () => { + const plan = buildGridJobs(wa, cuts, 0, 25)! + const xs = plan.jobs.map((j) => pointsBox(j.paths.find((p) => p.closed)!.points)!) + xs.forEach((b, i) => { + expect(b.width).toBeCloseTo(15, 6) + expect(b.x).toBeCloseTo(WIZARD_MARGIN_MM + i * 22, 6) + }) + expect(plan.jobs.map((j) => j.ejectExtraMm)).toEqual([undefined, undefined, undefined, undefined, 25]) + }) + + it('null bei voller Matte, zu schmaler Fläche oder leerer Variantenliste', () => { + const last = slotCount(wa) - slotsPerRow(wa) + 1 + expect(buildGridJobs(wa, cuts, last)).toBeNull() + expect(buildGridJobs({ name: 'n', width: 100, height: 305 }, cuts, 0)).toBeNull() + expect(buildGridJobs(wa, [], 0)).toBeNull() + }) +}) + +describe('suggestAdjustment', () => { + const base: CutSettings = { blade: 3, force: 10, speed: 5, passes: 1, overcut: 0.5 } + + it('good: unverändert', () => { + const r = suggestAdjustment(base, 'good') + expect(r.cut).toEqual(base) + expect(r.changed).toEqual([]) + }) + + it('notThrough: Druck +2, ab Druck 30 ein Durchgang mehr', () => { + expect(suggestAdjustment(base, 'notThrough')).toMatchObject({ cut: { ...base, force: 12 }, changed: ['force'], reasonKey: 'wizard.reason.notThrough' }) + const r = suggestAdjustment({ ...base, force: 30 }, 'notThrough') + expect(r.cut).toEqual({ ...base, force: 30, passes: 2 }) + expect(r.changed).toEqual(['passes']) + expect(r.reasonKey).toBe('wizard.reason.notThroughPasses') + }) + + it('tooDeep: Druck -2 und Klinge -1 (nur wenn > 1); Hinweistext je nach Klingenart', () => { + const r = suggestAdjustment(base, 'tooDeep') + expect(r.cut).toEqual({ ...base, force: 8, blade: 2 }) + expect(r.changed.sort()).toEqual(['blade', 'force']) + expect(r.reasonKey).toBe('wizard.reason.tooDeepBlade') + expect(suggestAdjustment(base, 'tooDeep', false).reasonKey).toBe('wizard.reason.tooDeepBladeManual') + const one = suggestAdjustment({ ...base, blade: 1 }, 'tooDeep') + expect(one.cut).toEqual({ ...base, blade: 1, force: 8 }) + expect(one.reasonKey).toBe('wizard.reason.tooDeep') + }) + + it('cornersTorn: Tempo -1 und Druck -1; liftsOff: nur Tempo -1, Überschnitt bleibt', () => { + expect(suggestAdjustment(base, 'cornersTorn').cut).toEqual({ ...base, speed: 4, force: 9 }) + const r = suggestAdjustment(base, 'liftsOff') + expect(r.cut).toEqual({ ...base, speed: 4 }) + expect(r.cut.overcut).toBe(0.5) + expect(r.changed).toEqual(['speed']) + }) + + it('klemmt an den Grenzen; ohne mögliche Änderung kommt der Grenz-Hinweis', () => { + expect(suggestAdjustment({ ...base, force: 29 }, 'notThrough').cut.force).toBe(31) + expect(suggestAdjustment({ ...base, force: 1, blade: 1, speed: 1 }, 'tooDeep').changed).toEqual([]) + expect(suggestAdjustment({ ...base, force: 1, blade: 1 }, 'tooDeep').reasonKey).toBe('wizard.reason.limit') + expect(suggestAdjustment({ ...base, force: 33, passes: 5 }, 'notThrough').reasonKey).toBe('wizard.reason.limit') + expect(suggestAdjustment({ ...base, speed: 1 }, 'liftsOff').reasonKey).toBe('wizard.reason.limit') + }) + + it('liefert für alle Urteile und Randwerte gültige Werte, ohne die Eingabe zu verändern', () => { + for (const verdict of VERDICTS) for (const force of [1, 29, 30, 33]) for (const blade of [1, 10]) for (const speed of [1, 10]) for (const passes of [1, 5]) { + const cut = { blade, force, speed, passes, overcut: 0 } + const copy = { ...cut } + const r = suggestAdjustment(cut, verdict) + expect(inRange(r.cut)).toBe(true) + expect(cut).toEqual(copy) + } + }) +}) + +describe('Profilnotiz', () => { + it('upsertProfile speichert die bereinigte, gekürzte Notiz; ohne Angabe bleibt eine vorhandene beim Überschreiben', () => { + let r = upsertProfile([], 'Folie', DEFAULT_CUT, ' Klinge rot\nMatte neu ') + expect(r.list[0].note).toBe('Klinge rot Matte neu') + r = upsertProfile(r.list, 'folie', { ...DEFAULT_CUT, force: 20 }) + expect(r.list[0].note).toBe('Klinge rot Matte neu') + expect(r.list[0].cut.force).toBe(20) + r = upsertProfile(r.list, 'Folie', DEFAULT_CUT, 'neu') + expect(r.list[0].note).toBe('neu') + r = upsertProfile(r.list, 'Folie', DEFAULT_CUT, ' ') + expect(r.list[0]).not.toHaveProperty('note') + expect(upsertProfile([], 'A', DEFAULT_CUT, 'x'.repeat(500)).list[0].note).toHaveLength(MAX_PROFILE_NOTE) + expect(upsertProfile([], 'B', DEFAULT_CUT).list[0]).not.toHaveProperty('note') + }) + + it('sanitizeProfiles bereinigt Notizen; update/rename erhalten sie', () => { + const out = sanitizeProfiles([ + { name: 'A', cut: DEFAULT_CUT, note: ' hallo welt ' }, + { name: 'B', cut: DEFAULT_CUT, note: 42 }, + { name: 'C', cut: DEFAULT_CUT, note: 'y'.repeat(300) } + ]) + expect(out[0].note).toBe('hallo welt') + expect(out[1]).not.toHaveProperty('note') + expect(out[2].note).toHaveLength(MAX_PROFILE_NOTE) + const u = updateProfile(out, 'A', { ...DEFAULT_CUT, force: 15 }) + expect(u.list[0].note).toBe('hallo welt') + expect(renameProfile(u.list, 'A', 'Neu').list[0].note).toBe('hallo welt') + }) +}) diff --git a/src/core/materialWizard.ts b/src/core/materialWizard.ts new file mode 100644 index 0000000..2b7385f --- /dev/null +++ b/src/core/materialWizard.ts @@ -0,0 +1,228 @@ +import type { CutJob, CutSettings, Part, Point, Polyline, WorkArea } from '@shared/types' +import type { MessageKey } from '@shared/i18n' +import { t } from '@shared/i18n' +import { buildJob } from './job' +import { RANGES } from './materials' +import { TEST_CUT_HEIGHT_MM, TEST_CUT_WIDTH_MM, testCutPart } from './testcut' +import { uid } from './uid' + +/** + * Material-Einmessen-Assistent (reiner Kern ohne UI): Raster der Testplätze, Aufträge für Einzel- und Rastertests + * und Vorschläge zur Anpassung der Schnittwerte. + */ + +/** Urteil des Nutzers über einen Testschnitt. */ +export type Verdict = 'good' | 'notThrough' | 'tooDeep' | 'cornersTorn' | 'liftsOff' +export const VERDICTS: Verdict[] = ['good', 'notThrough', 'tooDeep', 'cornersTorn', 'liftsOff'] + +/** Rastermaße (mm): Rand der Arbeitsfläche und Zellengröße eines Testplatzes (Muster 55 x 25 plus Strichmarken darüber). */ +export const WIZARD_MARGIN_MM = 6 +export const WIZARD_CELL_W_MM = 62 +export const WIZARD_CELL_H_MM = 38 +/** Höhe des Streifens mit den Strichmarken über dem Muster; die Marken selbst sind MARK_H hoch. */ +const MARK_BAND_MM = 10 +const MARK_H_MM = 5 +const MARK_PITCH_MM = 2 +export const WIZARD_MAX_MARKS = 9 + +/** Rastertest: Quadrate (Kantenlänge, Abstand von Mitte zu Mitte) und erlaubte Anzahl Varianten. */ +export const GRID_SQUARE_MM = 15 +export const GRID_PITCH_MM = 22 +export const GRID_MIN_COUNT = 3 +export const GRID_MAX_COUNT = 7 + +/** Höhe, die ein Testplatz tatsächlich belegt (Marken-Streifen + Muster). */ +const SLOT_USED_H_MM = MARK_BAND_MM + TEST_CUT_HEIGHT_MM + +/** Anzahl Testplätze je Zeile. */ +export function slotsPerRow(workArea: WorkArea): number { + const usable = workArea.width - 2 * WIZARD_MARGIN_MM - TEST_CUT_WIDTH_MM + if (usable < -1e-9) return 0 + return Math.floor(usable / WIZARD_CELL_W_MM + 1e-9) + 1 +} + +/** Anzahl Zeilen auf der Arbeitsfläche. */ +export function slotRows(workArea: WorkArea): number { + const usable = workArea.height - 2 * WIZARD_MARGIN_MM - SLOT_USED_H_MM + if (usable < -1e-9) return 0 + return Math.floor(usable / WIZARD_CELL_H_MM + 1e-9) + 1 +} + +/** Wie viele Testplätze passen auf die Arbeitsfläche (zeilenweise von links nach rechts)? */ +export function slotCount(workArea: WorkArea): number { + return slotsPerRow(workArea) * slotRows(workArea) +} + +/** Linke obere Ecke (inkl. Marken-Streifen) des Testplatzes `slot` (ab 0); null = passt nicht (mehr). */ +export function slotPosition(workArea: WorkArea, slot: number): Point | null { + const cols = slotsPerRow(workArea) + if (!Number.isInteger(slot) || slot < 0 || cols === 0 || slot >= slotCount(workArea)) return null + return { x: WIZARD_MARGIN_MM + (slot % cols) * WIZARD_CELL_W_MM, y: WIZARD_MARGIN_MM + Math.floor(slot / cols) * WIZARD_CELL_H_MM } +} + +/** Strichmarken als Bauteil: `n` senkrechte Striche (1..9) nebeneinander, linke obere Ecke bei (x, y). */ +function marksPart(n: number, x: number, y: number): Part { + const count = Math.max(1, Math.min(WIZARD_MAX_MARKS, Math.round(n))) + const paths: Polyline[] = [] + for (let i = 0; i < count; i++) paths.push({ closed: false, points: [{ x: i * MARK_PITCH_MM, y: 0 }, { x: i * MARK_PITCH_MM, y: MARK_H_MM }] }) + return { + id: uid(), name: t('part.testCutName'), sourcePath: '', paths, + width: (count - 1) * MARK_PITCH_MM, height: MARK_H_MM, x, y, rotation: 0, scale: 1 + } +} + +/** Breite der Strichmarken für `n` Striche (mm). */ +const marksWidth = (n: number): number => (Math.max(1, Math.min(WIZARD_MAX_MARKS, Math.round(n))) - 1) * MARK_PITCH_MM + +/** + * Auftrag für Versuch Nummer `n` auf Testplatz `slot`: das Testmuster (Quadrat, Dreieck, Kreis) mit `n` Strichmarken darüber. + * null = Platz passt nicht mehr auf die Arbeitsfläche. `ejectExtraMm` setzt das Ausfahren nach dem Schnitt. + */ +export function buildWizardJob(workArea: WorkArea, cut: CutSettings, slot: number, n: number, ejectExtraMm?: number): CutJob | null { + const pos = slotPosition(workArea, slot) + if (!pos) return null + const pattern = testCutPart({ x: pos.x, y: pos.y + MARK_BAND_MM }) + // Marken mittig über dem Quadrat des Musters (die Strichmarken sind schmal) + const marks = marksPart(n, pos.x + 10 - marksWidth(n) / 2, pos.y) + const job = buildJob([marks, pattern], workArea, cut) + return ejectExtraMm !== undefined ? { ...job, ejectExtraMm } : job +} + +/** Welche Werte der Rastertest variiert. */ +export type GridParam = 'force' | 'speed' | 'blade' + +/** Auf den erlaubten Bereich begrenzter, ganzzahliger Wert eines Schnittparameters. */ +function clampCut(key: keyof CutSettings, v: number): number { + const [lo, hi] = RANGES[key] + const x = Math.min(hi, Math.max(lo, v)) + return key === 'overcut' ? Math.round(x * 10) / 10 : Math.round(x) +} + +/** + * Varianten für den Rastertest: `count` (3..7) Werte ab `start` in Schritten von `step` für `param`, sonst die Werte von `base`. + * Werte werden in den erlaubten Bereich geklemmt, doppelte Varianten entfallen (Reihenfolge bleibt). + */ +export function gridVariants(base: CutSettings, param: GridParam, start: number, step: number, count: number): CutSettings[] { + const n = Math.max(GRID_MIN_COUNT, Math.min(GRID_MAX_COUNT, Math.round(count))) + const out: CutSettings[] = [] + const seen = new Set() + for (let i = 0; i < n; i++) { + const v = clampCut(param, start + i * step) + if (seen.has(v)) continue + seen.add(v) + out.push({ ...base, [param]: v }) + } + return out +} + +/** Sinnvolle Standard-Schrittweite je variiertem Wert. */ +export const GRID_DEFAULT_STEP: Record = { force: 2, speed: 1, blade: 1 } + +/** Startwert und Schrittweite für ein Raster, das den aktuellen Wert von `param` in der Mitte der `count` Varianten hat. */ +export function gridDefaults(cut: CutSettings, param: GridParam, count: number): { start: number; step: number } { + const step = GRID_DEFAULT_STEP[param] + const n = Math.max(GRID_MIN_COUNT, Math.min(GRID_MAX_COUNT, Math.round(count))) + return { start: clampCut(param, cut[param] - step * Math.floor((n - 1) / 2)), step } +} + +/** Zeile, in der ein Rastertest ab `startSlot` liegt: die laufende Zeile, wenn `startSlot` ihr Anfang ist, sonst die nächste. */ +function gridRow(workArea: WorkArea, startSlot: number): number { + const cols = slotsPerRow(workArea) + return cols === 0 ? -1 : Math.ceil(Math.max(0, startSlot) / cols) +} + +export interface GridPlan { + /** Ein Auftrag je Variante (nacheinander zu senden); nur der letzte trägt ggf. `ejectExtraMm`. */ + jobs: CutJob[] + /** Erster Testplatz der belegten Zeile. */ + firstSlot: number + /** Nächster freier Testplatz (Anfang der nächsten Zeile). */ + nextSlot: number + /** `nextSlot - startSlot`: so viele Plätze sind belegt bzw. übersprungen. */ + slotsUsed: number +} + +/** + * Rastertest: eine Reihe kleiner Quadrate (15 mm, Abstand 22 mm), je Variante eines mit 1..N Strichmarken als Nummer. + * Belegt eine ganze Testplatz-Zeile; null = die Zeile oder die Varianten passen nicht auf die Arbeitsfläche. + * Weil ein Auftrag nur EINE Schnitteinstellung hat, wird je Variante ein eigener Auftrag erzeugt. + */ +export function buildGridJobs(workArea: WorkArea, cuts: CutSettings[], startSlot: number, ejectExtraMm?: number): GridPlan | null { + const n = cuts.length + if (n < 1 || n > WIZARD_MAX_MARKS) return null + const cols = slotsPerRow(workArea) + const rows = slotRows(workArea) + const row = gridRow(workArea, startSlot) + if (cols === 0 || row < 0 || row >= rows) return null + const rowWidth = (n - 1) * GRID_PITCH_MM + GRID_SQUARE_MM + if (WIZARD_MARGIN_MM * 2 + rowWidth > workArea.width + 1e-9) return null + const y0 = WIZARD_MARGIN_MM + row * WIZARD_CELL_H_MM + const jobs = cuts.map((cut, i) => { + const x = WIZARD_MARGIN_MM + i * GRID_PITCH_MM + const sq = GRID_SQUARE_MM + const square: Part = { + id: uid(), name: t('part.testCutName'), sourcePath: '', + paths: [{ closed: true, points: [{ x: 0, y: 0 }, { x: sq, y: 0 }, { x: sq, y: sq }, { x: 0, y: sq }] }], + width: sq, height: sq, x, y: y0 + MARK_BAND_MM, rotation: 0, scale: 1 + } + const marks = marksPart(i + 1, x + sq / 2 - marksWidth(i + 1) / 2, y0) + const job = buildJob([marks, square], workArea, cut) + return i === n - 1 && ejectExtraMm !== undefined ? { ...job, ejectExtraMm } : job + }) + const firstSlot = row * cols + const nextSlot = (row + 1) * cols + return { jobs, firstSlot, nextSlot, slotsUsed: Math.max(0, nextSlot - Math.max(0, startSlot)) } +} + +export interface Adjustment { + cut: CutSettings + /** Die Werte, die sich gegenüber `cut` der Eingabe geändert haben. */ + changed: (keyof CutSettings)[] + /** Erklärtext (i18n-Schlüssel), warum so angepasst wird. */ + reasonKey: MessageKey +} + +/** + * Vorschlag für die nächsten Werte nach einem Urteil: + * nicht durchgeschnitten -> mehr Druck (ab Druck 30 stattdessen ein Durchgang mehr); zu tief -> weniger Druck (und flachere Klinge); + * Ecken ausgerissen -> langsamer und weniger Druck; Folie hebt sich ab -> langsamer. Immer innerhalb der erlaubten Bereiche. + * `autoBlade === false` (Klinge von Hand): Der Text sagt dann, die Klinge am Messer zu verstellen. + */ +export function suggestAdjustment(cut: CutSettings, verdict: Verdict, autoBlade?: boolean): Adjustment { + const next: CutSettings = { ...cut } + const clamp = (key: keyof CutSettings, v: number): number => clampCut(key, v) + let reasonKey: MessageKey = 'wizard.reason.good' + switch (verdict) { + case 'good': + break + case 'notThrough': + if (cut.force >= 30) { + next.passes = clamp('passes', cut.passes + 1) + reasonKey = 'wizard.reason.notThroughPasses' + } else { + next.force = clamp('force', cut.force + 2) + reasonKey = 'wizard.reason.notThrough' + } + break + case 'tooDeep': + next.force = clamp('force', cut.force - 2) + if (cut.blade > 1) { + next.blade = clamp('blade', cut.blade - 1) + reasonKey = autoBlade === false ? 'wizard.reason.tooDeepBladeManual' : 'wizard.reason.tooDeepBlade' + } else reasonKey = 'wizard.reason.tooDeep' + break + case 'cornersTorn': + next.speed = clamp('speed', cut.speed - 1) + next.force = clamp('force', cut.force - 1) + reasonKey = 'wizard.reason.cornersTorn' + break + case 'liftsOff': + next.speed = clamp('speed', cut.speed - 1) + reasonKey = 'wizard.reason.liftsOff' + break + } + const changed = (Object.keys(next) as (keyof CutSettings)[]).filter((k) => Math.abs(next[k] - cut[k]) > 1e-9) + // Nichts mehr zu ändern (Grenze erreicht): eigener Hinweis statt einer Erklärung, die nicht mehr zutrifft + if (verdict !== 'good' && changed.length === 0) reasonKey = 'wizard.reason.limit' + return { cut: next, changed, reasonKey } +} diff --git a/src/core/materials.ts b/src/core/materials.ts index 6ad09ec..391e67b 100644 --- a/src/core/materials.ts +++ b/src/core/materials.ts @@ -36,9 +36,11 @@ export const findBuiltin = (name: string): MaterialProfile | undefined => BUILTI export const MAX_PROFILE_NAME = 40 export const MAX_PROFILES = 100 +export const MAX_PROFILE_NOTE = 200 const KEYS: (keyof CutSettings)[] = ['blade', 'force', 'speed', 'passes', 'overcut'] -const RANGES: Record = { +/** Zulässige Bereiche der Schnittwerte (Klinge, Druck, Tempo, Durchgänge, Überschnitt). */ +export const RANGES: Record = { blade: [1, 10], force: [1, 33], speed: [1, 10], passes: [1, 5], overcut: [0, 5] } @@ -53,6 +55,13 @@ export function cleanProfileName(name: string): string | null { return n || null } +/** Bereinigt eine Profilnotiz (Leerraum, Länge). Leer oder kein Text = undefined. */ +export function cleanProfileNote(raw: unknown): string | undefined { + if (typeof raw !== 'string') return undefined + const n = raw.replace(/\s+/g, ' ').trim().slice(0, MAX_PROFILE_NOTE).trim() + return n || undefined +} + function cleanCut(raw: unknown): CutSettings | null { if (!isObj(raw)) return null const out = { ...DEFAULT_CUT } @@ -75,7 +84,8 @@ export function sanitizeProfiles(raw: unknown): MaterialProfile[] { const cut = cleanCut(r.cut) if (!name || !cut) continue if (out.some((p) => sameName(p.name, name)) || isBuiltinName(name)) continue - out.push({ name, cut }) + const note = cleanProfileNote(r.note) + out.push(note ? { name, cut, note } : { name, cut }) if (out.length >= MAX_PROFILES) break } return out @@ -84,15 +94,22 @@ export function sanitizeProfiles(raw: unknown): MaterialProfile[] { /** Name belegt durch ein eingebautes Material? */ export const isBuiltinName = (name: string): boolean => findBuiltin(name) !== undefined -/** Legt ein Profil an oder überschreibt das gleichnamige. Fehler: leerer Name oder Name eines eingebauten Materials. */ -export function upsertProfile(list: MaterialProfile[], name: string, cut: CutSettings): { list: MaterialProfile[]; error?: string; replaced?: boolean } { +/** + * Legt ein Profil an oder überschreibt das gleichnamige. Fehler: leerer Name oder Name eines eingebauten Materials. + * `note`: optionale Notiz (bereinigt, max. MAX_PROFILE_NOTE Zeichen); ohne Angabe bleibt beim Überschreiben die vorhandene Notiz. + */ +export function upsertProfile(list: MaterialProfile[], name: string, cut: CutSettings, note?: string): { list: MaterialProfile[]; error?: string; replaced?: boolean } { const n = cleanProfileName(name) if (!n) return { list, error: t('materials.nameRequired') } if (isBuiltinName(n)) return { list, error: t('materials.nameBuiltin', { name: n }) } const i = list.findIndex((p) => sameName(p.name, n)) // Beim Überschreiben bleibt die vorhandene Schreibweise des Namens - if (i >= 0) return { list: list.map((p, k) => (k === i ? { name: p.name, cut: { ...cut } } : p)), replaced: true } - return { list: [...list, { name: n, cut: { ...cut } }] } + const cn = note === undefined ? undefined : cleanProfileNote(note) + if (i >= 0) { + const keep = note === undefined ? cleanProfileNote(list[i].note) : cn + return { list: list.map((p, k) => (k === i ? { name: p.name, cut: { ...cut }, ...(keep ? { note: keep } : {}) } : p)), replaced: true } + } + return { list: [...list, { name: n, cut: { ...cut }, ...(cn ? { note: cn } : {}) }] } } /** Benennt ein Profil um (Werte bleiben). Fehler bei leerem/doppeltem Namen. */ diff --git a/src/core/testcut.ts b/src/core/testcut.ts index 3b33925..4b553f3 100644 --- a/src/core/testcut.ts +++ b/src/core/testcut.ts @@ -17,8 +17,12 @@ function circle(cx: number, cy: number, r: number, n = 72): Point[] { return pts } -/** Das Testmuster als Bauteil (lokale Koordinaten, bbox.min = 0,0): Quadrat 20x20 mit Dreieck innen, daneben ein Kreis (25 mm). */ -export function testCutPart(): Part { +/** Größe des Testmusters (Breite x Höhe in mm). */ +export const TEST_CUT_WIDTH_MM = TEST_CUT_SQUARE_MM + 10 + TEST_CUT_CIRCLE_DIAMETER_MM +export const TEST_CUT_HEIGHT_MM = TEST_CUT_CIRCLE_DIAMETER_MM + +/** Das Testmuster als Bauteil (lokale Koordinaten, bbox.min = 0,0): Quadrat 20x20 mit Dreieck innen, daneben ein Kreis (25 mm). `origin` = linke obere Ecke auf der Matte. */ +export function testCutPart(origin: Point = TEST_CUT_ORIGIN): Part { const sq = TEST_CUT_SQUARE_MM const d = TEST_CUT_CIRCLE_DIAMETER_MM const gap = 10 @@ -29,7 +33,7 @@ export function testCutPart(): Part { ] return { id: uid(), name: t('part.testCutName'), sourcePath: '', paths, - width: sq + gap + d, height: d, x: TEST_CUT_ORIGIN.x, y: TEST_CUT_ORIGIN.y, rotation: 0, scale: 1 + width: sq + gap + d, height: d, x: origin.x, y: origin.y, rotation: 0, scale: 1 } } diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index b734a3a..640cd9e 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -7,6 +7,7 @@ import { FileTree } from './components/FileTree' import { Workspace } from './components/Workspace' import { RightColumn } from './components/RightPanels' import { CutDialog } from './components/CutDialog' +import { MaterialWizard } from './components/MaterialWizard' import { TextDialog } from './components/TextDialog' import { NestDialog } from './components/NestDialog' import { TraceDialog } from './components/TraceDialog' @@ -127,6 +128,8 @@ export function App(): JSX.Element { + {/* Vor dem DialogHost: Namens-/Bestätigungsdialoge des Assistenten müssen darüber liegen */} + diff --git a/src/renderer/components/MaterialWizard.tsx b/src/renderer/components/MaterialWizard.tsx new file mode 100644 index 0000000..c1ef9b3 --- /dev/null +++ b/src/renderer/components/MaterialWizard.tsx @@ -0,0 +1,629 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { AlertTriangle, CheckCircle2, Info, Loader2, PauseCircle, Plus, RotateCcw, Save, Scissors, Undo2, Wand2, X } from 'lucide-react' +import type { CutJob, CutSettings, PlotEvent } from '@shared/types' +import { MAX_EJECT_MM } from '@shared/types' +import type { MessageKey } from '@shared/i18n' +import { formatNumber } from '@shared/i18n' +import { + BUILTIN_MATERIALS, GRID_MAX_COUNT, GRID_MIN_COUNT, VERDICTS, buildGridJobs, buildWizardJob, gridDefaults, gridVariants, materialLabel, + slotCount, slotPosition, suggestAdjustment +} from '../core' +import type { GridParam, Verdict } from '../core' +import { useStore, wizardTestCount, type WizardAttempt, type WizardStage } from '../store' +import { useT } from '../lib/useT' +import { pathD } from '../lib/transform' +import { NumberField } from './NumberField' +import { SliderField, useTestCutBlocker } from './RightPanels' + +const fmt = (n: number, digits = 1): string => formatNumber(n, { minimumFractionDigits: 0, maximumFractionDigits: digits }) +const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)) + +type Phase = 'idle' | 'running' | 'paused' | 'cancelled' | 'error' + +interface Live { totalLength: number; cutLength: number; pathIndex: number; pathDone: boolean; x: number; y: number } +const freshLive = (): Live => ({ totalLength: 0, cutLength: 0, pathIndex: -1, pathDone: false, x: 0, y: 0 }) + +/** Laufender Auftragsblock: bei einem Raster mehrere Aufträge nacheinander. */ +interface Run { + jobs: CutJob[] + index: number + /** Anzahl der für diesen Lauf neu angelegten Versuche (die letzten der Liste). */ + added: number + before: { attempts: WizardAttempt[]; nextSlot: number; stage: WizardStage } + /** Wartet zwischen zwei Aufträgen auf den Plotter. */ + between: boolean + stopped: boolean +} + +const PARAM_KEY: Record = { force: 'cut.setting.force', speed: 'cut.setting.speed', blade: 'rightPanel.cut.blade' } +const VERDICT_KEY: Record = { + good: 'wizard.verdict.good', notThrough: 'wizard.verdict.notThrough', tooDeep: 'wizard.verdict.tooDeep', + cornersTorn: 'wizard.verdict.cornersTorn', liftsOff: 'wizard.verdict.liftsOff' +} +const VERDICT_TIP: Record, MessageKey> = { + notThrough: 'wizard.verdict.tip.notThrough', tooDeep: 'wizard.verdict.tip.tooDeep', + cornersTorn: 'wizard.verdict.tip.cornersTorn', liftsOff: 'wizard.verdict.tip.liftsOff' +} +const TITLE_KEY: Record = { + setup: 'wizard.title.setup', rate: 'wizard.title.rate', adjust: 'wizard.title.adjust', save: 'wizard.title.save' +} + +export function MaterialWizard(): JSX.Element | null { + const open = useStore((s) => s.wizardOpen) + if (!open) return null + return +} + +/** Mattenansicht mit den bisherigen Versuchen (und optional dem nächsten Platz); `children` liegt oben drauf (Live-Schnitt). */ +function MatView({ wa, items, next, children }: { + wa: { width: number; height: number } + items: { d: string; cls: string }[] + next: { x: number; y: number; w: number; h: number } | null + children?: React.ReactNode +}): JSX.Element { + const t = useT() + const m = 8 + return ( + + + + {next && } + {items.map((it, i) => )} + {children} + + + ) +} + +/** Die fünf Schnittwerte als Regler (wie im Panel „Schnitteinstellungen“). */ +function CutSliders({ cut, onChange, autoBlade, prev }: { cut: CutSettings; onChange: (c: CutSettings) => void; autoBlade: boolean | undefined; prev?: CutSettings }): JSX.Element { + const t = useT() + const set = (patch: Partial): void => onChange({ ...cut, ...patch }) + // Mit `prev` (Werte des letzten Tests) werden geänderte Regler orange markiert und zeigen "alt → neu". + const wrap = (key: keyof CutSettings, unit: string, field: JSX.Element): JSX.Element => { + const changed = !!prev && Math.abs(prev[key] - cut[key]) > 1e-9 + return ( +
+ {field} + {changed && prev && {prev[key]}{unit} → {cut[key]}{unit}} +
+ ) + } + return ( +
+ {wrap('blade', '', set({ blade: v })} + title={autoBlade === true ? t('rightPanel.cut.bladeTooltipAuto') : autoBlade === false ? t('rightPanel.cut.bladeTooltipManual') : t('rightPanel.cut.bladeTooltip')} + />)} + {autoBlade === true &&

{t('rightPanel.cut.bladeNoteAuto')}

} + {autoBlade === false &&

{t('rightPanel.cut.bladeNoteManual', { level: cut.blade })}

} + {wrap('force', '', set({ force: v })} title={t('rightPanel.cut.forceTooltip')} />)} + {wrap('speed', '', set({ speed: v })} title={t('rightPanel.cut.speedTooltip')} />)} + {wrap('passes', '', set({ passes: v })} title={t('rightPanel.cut.passesTooltip')} />)} + {wrap('overcut', ' mm', set({ overcut: Math.round(v * 10) / 10 })} title={t('rightPanel.cut.overcutTooltip')} />)} +
+ ) +} + +/** Kurzfassung der Werte als Chips (wie im Schneiden-Dialog). */ +function CutChips({ cut, autoBlade }: { cut: CutSettings; autoBlade: boolean | undefined }): JSX.Element { + const t = useT() + return ( +
+ {autoBlade === true + ? {t('cut.blade.auto')} {cut.blade} {t('cut.blade.autoSuffix')} + : {t('cut.blade.manual')} {cut.blade}} + {t('cut.setting.force')} {cut.force}{t('cut.setting.speed')} {cut.speed} + {t('cut.setting.passes')} {cut.passes}{t('cut.setting.overcut')} {fmt(cut.overcut)} mm +
+ ) +} + +function WizardInner(): JSX.Element { + const t = useT() + const wizard = useStore((s) => s.wizard) + const patch = useStore((s) => s.patchWizard) + const close = useStore((s) => s.closeWizard) + const reset = useStore((s) => s.resetWizard) + const save = useStore((s) => s.saveWizardProfile) + const setCut = useStore((s) => s.setCut) + const toast = useStore((s) => s.toast) + const askConfirm = useStore((s) => s.askConfirm) + const settings = useStore((s) => s.settings) + const device = useStore((s) => s.devices.find((d) => d.id === s.connectedId)) + const blocker = useTestCutBlocker() + const wa = settings.activeWorkArea + const autoBlade = device?.autoBlade + const profiles = settings.materialProfiles ?? [] + const { attempts, cut, stage } = wizard + + // ---- Lauf (Schneiden) ---- + const [phase, setPhase] = useState('idle') + const [run, setRun] = useState<{ jobs: CutJob[]; index: number; added: number } | null>(null) + const [live, setLive] = useState(freshLive()) + const [error, setError] = useState('') + const [lost, setLost] = useState(false) + const [pauseMsg, setPauseMsg] = useState('') + const [cancelling, setCancelling] = useState(false) + const [ejecting, setEjecting] = useState(false) + const [startFrom, setStartFrom] = useState('cur') + const unsub = useRef<(() => void) | null>(null) + const runRef = useRef(null) + const liveRef = useRef(live) + const phaseRef = useRef('idle') + phaseRef.current = phase + const onEventRef = useRef<(e: PlotEvent) => void>(() => undefined) + + const setLiveBoth = (l: Live): void => { liveRef.current = l; setLive(l) } + const active = phase === 'running' || phase === 'paused' + + useEffect(() => () => { unsub.current?.() }, []) + useEffect(() => { + const onKey = (e: KeyboardEvent): void => { + // Escape gehört einem offenen Namens-/Bestätigungsdialog; beim Schneiden gesperrt + if (e.key === 'Escape' && !useStore.getState().dialog && phaseRef.current !== 'running' && phaseRef.current !== 'paused') close() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [close]) + + const stopRun = (kind: 'cancelled' | 'error', message = '', deviceLost = false): void => { + const r = runRef.current + unsub.current?.(); unsub.current = null + runRef.current = null + if (r) { + // Behalten: fertig geschnittene Aufträge plus der angeschnittene; nichts geschnitten = alles zurückrollen (Platz bleibt frei) + const kept = Math.min(r.added, r.index + (liveRef.current.cutLength > 0 ? 1 : 0)) + const cur = useStore.getState().wizard + const mine = cur.attempts.slice(r.before.attempts.length, r.before.attempts.length + r.added) + patch({ + attempts: [...r.before.attempts, ...mine.slice(0, kept)], + nextSlot: kept === 0 ? r.before.nextSlot : cur.nextSlot, + stage: kept > 0 ? 'rate' : r.before.stage + }) + } + setRun(null) + setCancelling(false) + setError(message) + setLost(deviceLost) + setPhase(kind) + } + + const sendJob = async (i: number): Promise => { + const r = runRef.current + if (!r) return + setEjecting(false) + try { + await window.api.startPlot(r.jobs[i]) + } catch (e) { + stopRun('error', (e as Error).message || t('cut.error.startFailed')) + } + } + + /** Nächster Auftrag des Rasters: erst warten, bis der Plotter wieder frei ist. */ + const advance = async (): Promise => { + const r = runRef.current + if (!r) return + r.index += 1 + r.between = true + setRun({ jobs: r.jobs, index: r.index, added: r.added }) + setLiveBoth(freshLive()) + await sleep(150) + for (let i = 0; i < 50 && useStore.getState().deviceStatus === 'busy'; i++) await sleep(100) + if (runRef.current !== r || r.stopped) return + r.between = false + await sendJob(r.index) + } + + const onEvent = (e: PlotEvent): void => { + switch (e.type) { + case 'started': setLiveBoth({ ...liveRef.current, totalLength: e.totalLength || liveRef.current.totalLength }); break + case 'progress': setLiveBoth({ ...liveRef.current, cutLength: e.cutLength, pathIndex: e.pathIndex, pathDone: e.done, x: e.x, y: e.y }); break + case 'finished': { + const r = runRef.current + if (!r) break + if (r.index + 1 < r.jobs.length) { void advance(); break } + unsub.current?.(); unsub.current = null + runRef.current = null + setRun(null) + patch({ stage: 'rate' }) + setPhase('idle') + break + } + case 'cancelled': stopRun('cancelled'); break + case 'paused': setPauseMsg(e.message); setPhase('paused'); break + case 'resumed': setPhase('running'); break + case 'ejecting': setEjecting(true); break + case 'error': stopRun('error', e.message, !!e.deviceLost); break + } + } + onEventRef.current = onEvent + + const startRun = (jobs: CutJob[], added: WizardAttempt[], nextSlot: number): void => { + setError(''); setLost(false); setCancelling(false); setEjecting(false) + runRef.current = { jobs, index: 0, added: added.length, before: { attempts, nextSlot: wizard.nextSlot, stage }, between: false, stopped: false } + setRun({ jobs, index: 0, added: added.length }) + setLiveBoth(freshLive()) + patch({ attempts: [...attempts, ...added], nextSlot }) + setPhase('running') + unsub.current?.() + unsub.current = window.api.onPlotEvent((e) => onEventRef.current(e)) + void sendJob(0) + } + + const cancel = async (): Promise => { + setCancelling(true) + const r = runRef.current + if (r?.between) { r.stopped = true; stopRun('cancelled'); return } + try { await window.api.cancelPlot() } catch (e) { toast('error', t('cut.error.cancelFailed', { message: (e as Error).message })) } + } + const resume = async (): Promise => { + try { await window.api.resumePlot() } catch (e) { toast('error', t('cut.error.resumeFailed', { message: (e as Error).message })) } + } + + // ---- Tests starten ---- + const ejectMm = wizard.ejectOn ? wizard.ejectMm : undefined + const variants = useMemo( + () => gridVariants(cut, wizard.gridParam, wizard.gridStart, wizard.gridStep, wizard.gridCount), + [cut, wizard.gridParam, wizard.gridStart, wizard.gridStep, wizard.gridCount] + ) + const gridPlan = useMemo(() => buildGridJobs(wa, variants, wizard.nextSlot, ejectMm), [wa, variants, wizard.nextSlot, ejectMm]) + const singleSlot = slotPosition(wa, wizard.nextSlot) + const total = slotCount(wa) + + const runSingle = (c: CutSettings): void => { + const n = attempts.filter((a) => a.kind === 'single').length + 1 + const job = buildWizardJob(wa, c, wizard.nextSlot, n, ejectMm) + if (!job) return + startRun([job], [{ n, cut: { ...c }, slot: wizard.nextSlot, kind: 'single', piece: wizard.piece }], wizard.nextSlot + 1) + } + const runGrid = (): void => { + if (!gridPlan) return + startRun( + gridPlan.jobs, + variants.map((c, i) => ({ n: i + 1, cut: c, slot: gridPlan.firstSlot, kind: 'grid' as const, piece: wizard.piece })), + gridPlan.nextSlot + ) + } + + // ---- Bewertung ---- + const last = attempts[attempts.length - 1] + const group = useMemo( + () => (!last ? [] : last.kind === 'grid' ? attempts.filter((a) => a.kind === 'grid' && a.slot === last.slot && a.piece === last.piece) : [last]), + [attempts, last] + ) + const setVerdict = (target: WizardAttempt, verdict: Verdict | undefined): WizardAttempt[] => + attempts.map((a) => (a === target ? { ...a, verdict } : a)) + const rate = (v: Verdict): void => { + if (!last) return + const list = setVerdict(last, v) + if (v === 'good') patch({ attempts: list, cut: { ...last.cut }, stage: 'save' }) + else patch({ attempts: list, cut: suggestAdjustment(last.cut, v, autoBlade).cut, stage: 'adjust' }) + } + const pick = (a: WizardAttempt): void => patch({ attempts: setVerdict(a, 'good'), cut: { ...a.cut }, stage: 'save' }) + /** Zurück zur Bewertung des letzten Tests (Urteil wird gelöscht). */ + const rerate = (): void => { + const picked = group.find((a) => a.verdict !== undefined) + patch({ attempts: picked ? setVerdict(picked, undefined) : attempts, stage: 'rate' }) + } + const toGrid = (param: GridParam = wizard.gridParam): void => { + const g = gridDefaults(cut, param, wizard.gridCount) + patch({ stage: 'setup', mode: 'grid', gridParam: param, gridStart: g.start, gridStep: g.step }) + } + const backFromSetup = (): void => { + patch({ stage: last?.verdict && last.verdict !== 'good' ? 'adjust' : 'rate' }) + } + const newPiece = (): void => patch({ nextSlot: 0, piece: wizard.piece + 1 }) + const doReset = async (): Promise => { + if (await askConfirm(t('wizard.reset.title'), t('wizard.reset.message'), t('wizard.reset.confirm'), true)) { reset(); setStartFrom('cur') } + } + const applyOnly = (): void => { + setCut(cut) + toast('success', t('wizard.save.applied')) + reset() + close() + } + + const full = wizard.mode === 'grid' && stage === 'setup' ? gridPlan === null : singleSlot === null + const startBlock = blocker ?? (full ? t('wizard.slots.full') : undefined) + const used = Math.min(wizard.nextSlot, total) + + // ---- Vorschau ---- + const piece = wizard.piece + const preview = useMemo(() => { + const shown = run ? attempts.slice(0, attempts.length - run.added) : attempts + const items: { d: string; cls: string }[] = [] + const cls = (a: WizardAttempt): string => 'wiz-p ' + (group.includes(a) ? 'cur' : 'old') + (a.verdict === 'good' ? ' ok' : a.verdict ? ' bad' : '') + const add = (job: CutJob | null, a: WizardAttempt): void => { if (job) items.push({ d: job.paths.map((p) => pathD(p.points, p.closed)).join(''), cls: cls(a) }) } + const grids = new Map() + for (const a of shown) { + if (a.piece !== piece) continue + if (a.kind === 'single') add(buildWizardJob(wa, a.cut, a.slot, a.n), a) + else grids.set(a.slot, [...(grids.get(a.slot) ?? []), a]) + } + for (const [slot, list] of grids) { + const sorted = [...list].sort((x, y) => x.n - y.n) + buildGridJobs(wa, sorted.map((a) => a.cut), slot)?.jobs.forEach((job, i) => add(job, sorted[i])) + } + return items + }, [attempts, run, piece, wa, group]) + + const nextRect = useMemo(() => { + if (stage !== 'setup' && stage !== 'adjust') return null + if (wizard.mode === 'grid' && stage === 'setup') { + const pos = gridPlan ? slotPosition(wa, gridPlan.firstSlot) : null + return pos ? { x: pos.x, y: pos.y, w: (variants.length - 1) * 22 + 15, h: 35 } : null + } + const pos = slotPosition(wa, wizard.nextSlot) + return pos ? { x: pos.x, y: pos.y, w: 55, h: 35 } : null + }, [stage, wizard.mode, wizard.nextSlot, gridPlan, variants.length, wa]) + + // ---- Live-Ansicht ---- + const liveD = useMemo(() => (run ? run.jobs.map((j) => j.paths.map((p) => pathD(p.points, p.closed))) : []), [run]) + const idx = run?.index ?? 0 + const doneCount = Math.max(0, live.pathIndex + (live.pathDone ? 1 : 0)) + const dDone = run ? liveD.slice(0, idx).flat().join('') + (liveD[idx] ?? []).slice(0, doneCount).join('') : '' + const dRest = run ? (liveD[idx] ?? []).slice(doneCount).join('') + liveD.slice(idx + 1).flat().join('') : '' + const dCur = run && phase === 'running' && !live.pathDone && live.pathIndex >= 0 ? (liveD[idx] ?? [])[live.pathIndex] ?? '' : '' + const frac = live.totalLength > 0 ? Math.min(1, live.cutLength / live.totalLength) : 0 + const pct = run ? Math.min(100, ((idx + frac) / run.jobs.length) * 100) : 0 + + // ---- Teilbereiche der Oberfläche ---- + const slotStatus = ( + <> +

{t('wizard.slots.status', { used, total })}

+ {full &&

{wizard.mode === 'grid' && stage === 'setup' && singleSlot !== null ? t('wizard.slots.fullGrid') : t('wizard.slots.full')}

} + + + ) + const ejectBlock = ( +
+ + {wizard.ejectOn && ( + <> + patch({ ejectMm: v })} title={t('wizard.eject.tooltip')} /> +

{t('wizard.eject.hint')}

+ + )} +
+ ) + const noteField = ( + + ) + + const startFromChange = (v: string): void => { + setStartFrom(v) + const p = v === 'cur' ? { cut: settings.cut } : v.startsWith('b:') ? BUILTIN_MATERIALS.find((m) => m.name === v.slice(2)) : profiles.find((m) => m.name === v.slice(2)) + if (p) patch({ cut: { ...p.cut } }) + } + + const lastCut = last?.cut + const adj = last?.verdict && last.verdict !== 'good' ? suggestAdjustment(last.cut, last.verdict, autoBlade) : null + const titleKey: MessageKey = phase === 'paused' ? 'wizard.title.paused' : phase === 'running' ? 'wizard.title.running' : phase === 'cancelled' ? 'wizard.title.cancelled' : phase === 'error' ? 'wizard.title.error' : TITLE_KEY[stage] + + return ( +
!active && close()}> +
e.stopPropagation()}> +
+

{t(titleKey)}

+ +
+
+
+
+ + {run && ( + <> + + + {dCur && } + {phase === 'running' && live.pathIndex >= 0 && ( + + + + + )} + + )} + +
+ +
+ {phase === 'idle' && stage === 'setup' && ( + <> +

{t('wizard.setup.intro')}

+ + patch({ cut: c })} autoBlade={autoBlade} /> +
+ + +
+ {wizard.mode === 'single' + ?

{t('wizard.mode.singleHint')}

+ : ( +
+
+ {(['force', 'speed', 'blade'] as GridParam[]).map((p) => ( + + ))} +
+
+ patch({ gridStart: v })} /> + patch({ gridStep: v })} /> + patch({ gridCount: v })} /> +
+

{t('wizard.grid.variants', { param: t(PARAM_KEY[wizard.gridParam]), list: variants.map((c) => c[wizard.gridParam]).join(', ') })}

+

{t('wizard.grid.hint')}

+
+ )} + {noteField} + {ejectBlock} + {slotStatus} + {blocker &&

{blocker}

} + + )} + + {phase === 'idle' && stage === 'rate' && last && ( + <> + {group.length > 1 || last.kind === 'grid' ? ( + <> +

{t('wizard.rate.gridIntro')}

+
+ {[...group].sort((a, b) => a.n - b.n).map((a) => ( + + ))} + +
+ + ) : ( + <> +

{t('wizard.rate.intro', { n: last.n })}

+ +
{t('wizard.rate.question')}
+
+ + {VERDICTS.filter((v): v is Exclude => v !== 'good').map((v) => ( + + ))} +
+ + )} + + )} + + {phase === 'idle' && stage === 'adjust' && last && ( + <> +

{t('wizard.adjust.verdict', { verdict: last.verdict ? t(VERDICT_KEY[last.verdict]) : '' })}
{adj && t(adj.reasonKey)}

+ patch({ cut: c })} autoBlade={autoBlade} prev={last.cut} /> +

{(['blade', 'force', 'speed', 'passes', 'overcut'] as const).some((k) => Math.abs(last.cut[k] - cut[k]) > 1e-9) ? t('wizard.adjust.changedLegend') : t('wizard.adjust.noChange')}

+
+ + +
+ + {ejectBlock} + {slotStatus} + {blocker &&

{blocker}

} + + )} + + {phase === 'idle' && stage === 'save' && ( + <> +

{t('wizard.save.intro', { n: wizardTestCount(attempts) })}

+ + {noteField} +

{t('wizard.save.historyNote', { history: t('wizard.save.history', { n: wizardTestCount(attempts), force: cut.force, speed: cut.speed }) })}

+ + {ejectBlock} + {slotStatus} + {blocker &&

{blocker}

} + + )} + + {run && (phase === 'running' || phase === 'paused') && ( + <> + {phase === 'paused' + ?

{t('cut.title.paused')}
{pauseMsg}
{t('cut.paused.next')}

+ : ( + <> +
{Math.round(pct)}%
+
+ + )} + {run.jobs.length > 1 &&

{t('wizard.running.gridStep', { n: Math.min(idx + 1, run.jobs.length), total: run.jobs.length })}

} +

{cancelling ? t('cut.running.cancelling') : ejecting ? t('cut.running.ejecting') : t('cut.running.warn')}

+ + )} + {phase === 'cancelled' &&

{t('cut.cancelled')}

} + {phase === 'error' && ( +

{lost ? t('cut.error.lost') : t('cut.error.failedTest')}
{error}{lost && <>
{t('cut.error.lostHint')}}

+ )} +
+
+ + {attempts.length > 0 && ( +
+
{t('wizard.table.title')}
+ + + + + + + + + {attempts.map((a, i) => ( + + + + + ))} + +
{t('wizard.table.no')}{autoBlade === true ? t('rightPanel.cut.bladeDepth') : t('rightPanel.cut.blade')}{t('cut.setting.force')}{t('cut.setting.speed')}{t('cut.setting.passes')}{t('cut.setting.overcut')}{t('wizard.table.verdict')}
{a.kind === 'grid' ? t('wizard.table.grid', { n: a.n }) : a.n}{a.cut.blade}{a.cut.force}{a.cut.speed}{a.cut.passes}{fmt(a.cut.overcut)}{a.verdict ? t(VERDICT_KEY[a.verdict]) : t('wizard.table.open')}
+
+ )} +
+ +
+ {active && ( + <> + {phase === 'paused' && } + + + )} + {(phase === 'cancelled' || phase === 'error') && ( + <> + + + + )} + {phase === 'idle' && ( + <> + + {attempts.length > 0 && } + {stage === 'setup' && attempts.length > 0 && } + {stage === 'setup' && ( + + )} + {stage === 'adjust' && ( + <> + + + + )} + {stage === 'save' && ( + <> + + + + + )} + + )} +
+
+
+ ) +} diff --git a/src/renderer/components/RightPanels.tsx b/src/renderer/components/RightPanels.tsx index 4eb0f99..15e7961 100644 --- a/src/renderer/components/RightPanels.tsx +++ b/src/renderer/components/RightPanels.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react' import { Copy, CopyPlus, Cpu, FlipHorizontal2, FlipVertical2, Group, Lock, LockOpen, Pencil, Plus, Split, Move, Plug, PlugZap, - Merge, RefreshCw, SquareDashed, ArrowDownToLine, Ruler, Save, Scissors, Trash2, Ungroup, Info, Usb, FlaskConical, Undo2 + Merge, RefreshCw, SquareDashed, ArrowDownToLine, Ruler, Save, Scissors, Trash2, Ungroup, Info, Usb, FlaskConical, Undo2, Wand2 } from 'lucide-react' import type { DeviceStatus } from '@shared/types' import { BORDER_MAX_MM, BORDER_MIN_MM, DEFAULT_AFTER_CUT, MAX_EJECT_MM } from '@shared/types' @@ -290,6 +290,7 @@ export function CutPanel(): JSX.Element { const setCut = useStore((s) => s.setCut) const device = useStore((s) => s.devices.find((d) => d.id === s.connectedId)) const openTestCut = useStore((s) => s.openTestCut) + const openWizard = useStore((s) => s.openWizard) const testBlocker = useTestCutBlocker() const autoBlade = device?.autoBlade const profiles = useStore((s) => s.settings.materialProfiles) ?? [] @@ -311,7 +312,7 @@ export function CutPanel(): JSX.Element { ))} {profiles.map((m) => ( - + ))} {!active && {t('rightPanel.cut.ownValues')}}
@@ -348,9 +349,14 @@ export function CutPanel(): JSX.Element { setCut({ speed: v })} title={t('rightPanel.cut.speedTooltip')} /> setCut({ passes: v })} title={t('rightPanel.cut.passesTooltip')} /> setCut({ overcut: Math.round(v * 10) / 10 })} title={t('rightPanel.cut.overcutTooltip')} /> - +
+ + +
) } diff --git a/src/renderer/store.ts b/src/renderer/store.ts index 9aee565..0b90c77 100644 --- a/src/renderer/store.ts +++ b/src/renderer/store.ts @@ -1,8 +1,9 @@ import { create } from 'zustand' import type { AfterCutSettings, BorderSettings, CutSettings, NestSettings, DeviceInfo, DeviceStatus, Part, PersistedSettings, Point, WorkArea } from '@shared/types' import { DEFAULT_AFTER_CUT, DEFAULT_BORDER, DEFAULT_CUT, DEFAULT_NEST, MAX_EJECT_MM, DEFAULT_WORK_AREAS } from '@shared/types' +import type { GridParam, Verdict } from './core' import { - addBorderToParts, findBuiltin, borderOptionsFrom, cleanProfileName, deleteProfile, isModified, updateProfile, resolveActiveProfile, type ActiveProfileRef, duplicateParts, expandToGroups, flipParts, groupParts, normalizeGroups, partScale, partSize, + MAX_PROFILE_NOTE, gridDefaults, addBorderToParts, findBuiltin, borderOptionsFrom, cleanProfileName, deleteProfile, isModified, updateProfile, resolveActiveProfile, type ActiveProfileRef, duplicateParts, expandToGroups, flipParts, groupParts, normalizeGroups, partScale, partSize, removeBorderFromParts, renameProfile, sanitizeBorder, sanitizeNest, scalePartBy, splitPart, ungroupParts, upsertProfile, weldPart, withScale } from './core' import { LANGUAGES, onLanguageChange, t, tIn, type LanguagePref } from '@shared/i18n' @@ -18,6 +19,52 @@ export type DialogState = | { type: 'prompt'; title: string; label: string; initial: string; confirmLabel: string; resolve: (v: string | null) => void } | { type: 'unsaved'; title: string; message: string; resolve: (choice: 'save' | 'discard' | 'cancel') => void } +/** Ein Versuch des Einmess-Assistenten. Raster-Varianten teilen sich `slot` (erster Platz der Zeile); `n` ist dort die Variantennummer. */ +export interface WizardAttempt { + n: number + cut: CutSettings + slot: number + verdict?: Verdict + kind: 'single' | 'grid' + /** Materialstück, auf dem der Versuch liegt (zählt hoch bei „Neues Materialstück eingelegt“). */ + piece: number +} +export type WizardStage = 'setup' | 'rate' | 'adjust' | 'save' +/** Entwurf des Einmess-Assistenten (nur im Speicher; überlebt das Schließen des Dialogs, nicht den Neustart). */ +export interface WizardState { + stage: WizardStage + attempts: WizardAttempt[] + /** Nächster freier Testplatz auf dem aktuellen Materialstück. */ + nextSlot: number + piece: number + /** Aktuelle Werte des Assistenten (unabhängig von settings.cut). */ + cut: CutSettings + note: string + mode: 'single' | 'grid' + gridParam: GridParam + gridStart: number + gridStep: number + gridCount: number + /** Ausfahren nach dem Test (nur Assistent; settings.afterCut bleibt unberührt). */ + ejectOn: boolean + ejectMm: number +} + +const freshWizard = (settings: PersistedSettings): WizardState => { + const cut = { ...settings.cut } + const g = gridDefaults(cut, 'force', 5) + return { + stage: 'setup', attempts: [], nextSlot: 0, piece: 1, cut, note: '', mode: 'single', gridParam: 'force', + gridStart: g.start, gridStep: g.step, gridCount: 5, ejectOn: false, ejectMm: (settings.afterCut ?? DEFAULT_AFTER_CUT).ejectExtraMm + } +} + +/** Anzahl Tests des Assistenten: ein Einzelschnitt zählt eins, ein ganzes Raster ebenfalls eins. */ +export function wizardTestCount(attempts: WizardAttempt[]): number { + const grids = new Set(attempts.filter((a) => a.kind === 'grid').map((a) => `${a.piece}:${a.slot}`)) + return attempts.filter((a) => a.kind === 'single').length + grids.size +} + /** Aktuelles Projekt: Pfad (null = noch nie gespeichert), Anzeigename und ungespeicherte Änderungen. */ export interface ProjectInfo { path: string | null; name: string; dirty: boolean } @@ -71,6 +118,9 @@ interface State { lockAspect: boolean /** 'test' = Testschnitt (kleines Muster statt Projekt) im Schneiden-Dialog */ cutMode: 'project' | 'test' + /** Einmess-Assistent: Dialog offen? und Entwurf (bleibt beim Schließen erhalten). */ + wizardOpen: boolean + wizard: WizardState init(): () => void toast(kind: Toast['kind'], text: string, action?: Toast['action']): void @@ -147,7 +197,11 @@ interface State { saveWorkAreaPreset(name: string): void deleteWorkAreaPreset(name: string): void /** Eigene Materialprofile: speichern (Name per Dialog), umbenennen, löschen. */ - saveMaterialProfile(): Promise + /** + * Fragt den Namen ab und speichert die aktuellen Werte (oder `cut`) als Profil, optional mit Notiz. `quiet` unterdrückt die Erfolgsmeldung. + * Liefert den gespeicherten Namen, bei Abbruch oder Fehler null. + */ + saveMaterialProfile(opts?: { cut?: CutSettings; note?: string; quiet?: boolean }): Promise renameMaterialProfile(name: string): Promise /** Zuletzt gewähltes Material-/Profil-Chip (nicht gespeichert; ohne Wahl gilt das zu den Werten passende Profil). */ activeProfile: ActiveProfileRef | null @@ -168,6 +222,14 @@ interface State { disconnect(): Promise setCutOpen(open: boolean): void openTestCut(): void + openWizard(): void + /** Schließt den Dialog; der Entwurf bleibt erhalten. */ + closeWizard(): void + /** Verwirft den Entwurf (Versuche, Platzzählung, Werte). */ + resetWizard(): void + patchWizard(patch: Partial): void + /** Speichert die Endwerte des Assistenten als Profil (Name per Dialog) und übernimmt sie; true = gespeichert. */ + saveWizardProfile(): Promise } let toastSeq = 1 @@ -253,6 +315,8 @@ export const useStore = create((set, get) => { textOpen: false, lockAspect: true, cutMode: 'project', + wizardOpen: false, + wizard: freshWizard(defaultSettings()), init() { const unsub = window.api.onDeviceStatus((st) => { @@ -578,22 +642,23 @@ export const useStore = create((set, get) => { get().patchSettings({ workAreas: settings.workAreas.filter((w) => w.name !== name) }) get().toast('info', t('toast.preset.deleted', { name })) }, - async saveMaterialProfile() { + async saveMaterialProfile(opts = {}) { const st = get() const name = await st.askText(t('profile.save.title'), t('profile.save.label'), '', t('common.save')) - if (name === null) return + if (name === null) return null const list = get().settings.materialProfiles ?? [] const clean = cleanProfileName(name) if (clean && list.some((p) => p.name.toLowerCase() === clean.toLowerCase())) { const ok = await get().askConfirm(t('profile.overwrite.title'), t('profile.overwrite.exists', { name: clean }), t('profile.overwrite.confirm')) - if (!ok) return + if (!ok) return null } - const r = upsertProfile(list, name, get().settings.cut) - if (r.error) { get().toast('error', r.error); return } + const r = upsertProfile(list, name, opts.cut ?? get().settings.cut, opts.note) + if (r.error) { get().toast('error', r.error); return null } get().patchSettings({ materialProfiles: r.list }) const saved = r.list.find((p) => cleanProfileName(name) && p.name.toLowerCase() === cleanProfileName(name)!.toLowerCase()) if (saved) set({ activeProfile: { name: saved.name, builtin: false } }) - get().toast('success', t(r.replaced ? 'toast.profile.updated' : 'toast.profile.saved', { name: cleanProfileName(name) ?? name })) + if (!opts.quiet) get().toast('success', t(r.replaced ? 'toast.profile.updated' : 'toast.profile.saved', { name: cleanProfileName(name) ?? name })) + return saved?.name ?? cleanProfileName(name) ?? name }, selectProfile(ref) { const p = ref.builtin ? findBuiltin(ref.name) : (get().settings.materialProfiles ?? []).find((m) => m.name === ref.name) @@ -687,7 +752,31 @@ export const useStore = create((set, get) => { set({ connectedId: null, deviceStatus: 'disconnected' }) }, setCutOpen(open) { set({ cutOpen: open, cutMode: 'project' }) }, - openTestCut() { set({ cutOpen: true, cutMode: 'test' }) } + openTestCut() { set({ cutOpen: true, cutMode: 'test' }) }, + + openWizard() { + // Ohne Versuche zählt der Entwurf nicht: frisch mit den aktuellen Einstellungen beginnen + if (get().wizard.attempts.length === 0) set({ wizard: freshWizard(get().settings) }) + set({ wizardOpen: true }) + }, + closeWizard() { set({ wizardOpen: false }) }, + resetWizard() { set({ wizard: freshWizard(get().settings) }) }, + patchWizard(patch) { set((s) => ({ wizard: { ...s.wizard, ...patch } })) }, + async saveWizardProfile() { + const w = get().wizard + // Kurzverlauf zuerst, damit er bei langer Nutzernotiz nicht abgeschnitten wird + const history = t('wizard.save.history', { n: wizardTestCount(w.attempts), force: w.cut.force, speed: w.cut.speed }) + const room = MAX_PROFILE_NOTE - history.length - 3 + const user = w.note.replace(/\s+/g, ' ').trim().slice(0, Math.max(0, room)).trim() + const name = await get().saveMaterialProfile({ cut: w.cut, note: user ? `${user} · ${history}` : history, quiet: true }) + if (name === null) return false + get().setCut(w.cut) + set({ activeProfile: { name, builtin: false } }) + get().toast('success', t('wizard.save.done', { name })) + get().resetWizard() + get().closeWizard() + return true + } } }) diff --git a/src/renderer/styles.css b/src/renderer/styles.css index f866526..17f8f2b 100644 --- a/src/renderer/styles.css +++ b/src/renderer/styles.css @@ -338,6 +338,8 @@ input[type='range']:hover::-webkit-slider-thumb { background: #35e0c2; } .blade-note { margin-top: -4px; } .blade-note svg { margin-top: 1px; } .test-cut { align-self: flex-start; margin-top: 2px; } +.test-cut-row { margin-top: 2px; } +.test-cut-row .test-cut { align-self: auto; margin-top: 0; } /* ----- Datei-Menü / Projekt ----- */ .file-menu { position: relative; display: flex; align-items: center; gap: 8px; } @@ -504,3 +506,27 @@ input[type='range']:hover::-webkit-slider-thumb { background: #35e0c2; } .lang-chip.open { background: var(--card-2); color: var(--text); } .menu.menu-right { left: auto; right: 0; min-width: 190px; } .menu-title { padding: 6px 10px 4px; color: var(--text-3); font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; } + +/* ----- Material einmessen (Assistent) ----- */ +.modal.wizard { width: min(1020px, 100%); } +.wizard-body { display: flex; flex-direction: column; gap: 14px; } +.wiz-side { gap: 10px; } +.wiz-sliders { display: flex; flex-direction: column; gap: 8px; } +.wiz-slider { display: flex; flex-direction: column; gap: 2px; padding: 4px 8px; margin: 0 -8px; border-radius: 9px; border: 1px solid transparent; } +.wiz-slider.changed { background: rgba(240, 145, 45, 0.14); border-color: rgba(240, 145, 45, 0.55); } +.wiz-delta { align-self: flex-end; font-size: 12px; font-variant-numeric: tabular-nums; color: #f0912d; } +.wiz-delta b { font-weight: 700; } +.wiz-eject { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 9px; } +.wiz-grid { display: flex; flex-direction: column; gap: 8px; } +.wiz-next { fill: rgba(25, 195, 166, 0.12); stroke: #19c3a6; stroke-width: 1.2; stroke-dasharray: 4 3; vector-effect: non-scaling-stroke; } +.wiz-p { fill: none; stroke-width: 1.6; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; } +.wiz-p.old { stroke: #8a93a0; } +.wiz-p.cur { stroke: #0fae94; } +.wiz-p.bad { stroke: #f0912d; } +.wiz-p.ok { stroke: #2fa84f; } +.wiz-table-wrap { display: flex; flex-direction: column; gap: 6px; } +.wiz-table { width: 100%; border-collapse: collapse; font-size: 12.5px; font-variant-numeric: tabular-nums; } +.wiz-table th, .wiz-table td { padding: 5px 8px; text-align: left; border-bottom: 1px solid var(--line); } +.wiz-table th { color: var(--text-2); font-weight: 600; } +.wiz-table tr.cur td { background: var(--accent-soft); } +.wizard .sub-head { font-weight: 600; font-size: 12.5px; color: var(--text); } diff --git a/src/shared/i18n/de.ts b/src/shared/i18n/de.ts index 3bedd1b..d7a7cb3 100644 --- a/src/shared/i18n/de.ts +++ b/src/shared/i18n/de.ts @@ -1,5 +1,6 @@ import { deTrace } from './de.trace' import { deCut } from './de.cut' +import { deWizard } from './de.wizard' import { deShell } from './de.shell' /** @@ -282,7 +283,8 @@ export const de = { 'mock.error.notReady': 'Kein Gerät bereit', 'mock.error.fileNotFound': 'Datei nicht gefunden: {path}', - ...deCut + ...deCut, + ...deWizard } export type MessageKey = keyof typeof de diff --git a/src/shared/i18n/de.wizard.ts b/src/shared/i18n/de.wizard.ts new file mode 100644 index 0000000..4ccd788 --- /dev/null +++ b/src/shared/i18n/de.wizard.ts @@ -0,0 +1,124 @@ +/** Deutsche Texte des Einmess-Assistenten „Material einmessen“ (wizard.*); in de.ts eingebunden. */ +export const deWizard = { + // ---- Auslöser im Panel „Schnitteinstellungen“ + 'wizard.open': 'Material einmessen', + 'wizard.open.tooltip': 'Schneidet kleine Testformen, bewertet sie mit dir und findet Schritt für Schritt passende Werte – am Ende als Materialprofil speichern', + + // ---- Dialog: Titel + 'wizard.aria': 'Material einmessen', + 'wizard.title.setup': 'Material einmessen – Startwerte', + 'wizard.title.rate': 'Material einmessen – Test bewerten', + 'wizard.title.adjust': 'Material einmessen – Werte anpassen', + 'wizard.title.save': 'Material einmessen – Profil speichern', + 'wizard.title.running': 'Testschnitt läuft …', + 'wizard.title.paused': 'Pausiert – Medium prüfen', + 'wizard.title.cancelled': 'Abgebrochen', + 'wizard.title.error': 'Fehler', + 'wizard.mat.aria': 'Vorschau der Testschnitte auf der Arbeitsfläche', + 'wizard.close.tooltip': 'Schließen – der Stand bleibt erhalten, bis die App beendet wird', + + // ---- Schritt 1: Startwerte und Testart + 'wizard.setup.intro': 'Der Assistent schneidet kleine Testformen mit deinen Startwerten. Du bewertest das Ergebnis, die Werte werden angepasst – so lange, bis der Schnitt passt. Am Ende speicherst du sie als Materialprofil. Die Werte hier ändern deine aktuellen Einstellungen nicht.', + 'wizard.setup.startFrom': 'Startwerte von', + 'wizard.setup.startCurrent': 'Aktuelle Einstellungen', + 'wizard.mode.aria': 'Testart', + 'wizard.mode.single': 'Einzeltests nacheinander', + 'wizard.mode.singleTooltip': 'Ein Testmuster nach dem anderen schneiden und jeweils bewerten', + 'wizard.mode.grid': 'Raster (Reihe)', + 'wizard.mode.gridTooltip': 'Eine Reihe kleiner Quadrate mit steigendem Druck, Tempo oder steigender Klinge in einem Zug schneiden', + 'wizard.mode.singleHint': 'Schneidet das Testmuster (Quadrat, Dreieck, Kreis) mit Strichmarken darüber, die die Versuchsnummer zeigen. Jeder Test kommt neben den vorherigen.', + 'wizard.grid.param.aria': 'Variierter Wert', + 'wizard.grid.bladeManual': 'Bei von Hand eingestellter Klinge nicht möglich – das Programm kann sie nicht verstellen', + 'wizard.grid.start': 'Start', + 'wizard.grid.step': 'Schritt', + 'wizard.grid.count': 'Anzahl', + 'wizard.grid.variants': 'Varianten ({param}): {list}', + 'wizard.grid.hint': 'Schneidet eine Reihe kleiner Quadrate nacheinander, jedes mit seiner Nummer als Strichmarken darüber. Danach wählst du die Nummer, die am besten geschnitten hat.', + 'wizard.grid.variantLabel': 'Nr. {n} · {param} {value}', + 'wizard.note.label': 'Notiz (z. B. Klinge, Matte)', + 'wizard.note.placeholder': 'z. B. rote Klinge, neue Matte', + + // ---- Ausfahren (nur Assistent) + 'wizard.eject.label': 'Material nach dem Test genau passend ausfahren', + 'wizard.eject.tooltip': 'Fährt nach dem Schnitt so weit vor, dass du den Test abziehen kannst. Gilt nur für den Assistenten und ändert die Einstellung „Nach dem Schneiden“ nicht.', + 'wizard.eject.distance': 'Zusatz', + 'wizard.eject.hint': 'Nach dem Ausfahren das Material wieder an dieselbe Stelle einlegen, wenn die Platzzählung weiterlaufen soll. Bei einem neuen Stück unten „Neues Materialstück eingelegt“ wählen.', + + // ---- Platz auf dem Material + 'wizard.slots.status': '{used} von {total} Testplätzen belegt', + 'wizard.slots.full': 'Material voll – neues Stück einlegen', + 'wizard.slots.fullGrid': 'Für das Raster ist keine freie Zeile mehr oder die Fläche zu schmal – neues Stück einlegen', + 'wizard.slots.newPiece': 'Neues Materialstück eingelegt', + 'wizard.slots.newPieceTooltip': 'Setzt die Platzzählung zurück: der nächste Test wird wieder oben links geschnitten', + + // ---- Schneiden + 'wizard.running.gridStep': 'Schnitt {n} von {total}', + + // ---- Schritt 2: Bewerten + 'wizard.rate.intro': 'Versuch {n} ist geschnitten. Folie vorsichtig abziehen und den Schnitt prüfen.', + 'wizard.rate.question': 'Wie ist der Schnitt?', + 'wizard.rate.good': 'Passt – speichern', + 'wizard.rate.gridIntro': 'Raster geschnitten. Welche Nummer (Strichmarken) hat am besten geschnitten? Die Werte dieser Variante werden übernommen.', + 'wizard.rate.gridNone': 'Keine passt – Raster neu einstellen', + 'wizard.verdict.good': 'Passt', + 'wizard.verdict.notThrough': 'Nicht durchgeschnitten', + 'wizard.verdict.tooDeep': 'Zu tief', + 'wizard.verdict.cornersTorn': 'Ecken ausgerissen', + 'wizard.verdict.liftsOff': 'Folie hebt sich ab', + 'wizard.verdict.tip.notThrough': 'Die Folie hängt noch zusammen oder lässt sich nur mit Mühe lösen', + 'wizard.verdict.tip.tooDeep': 'Trägerpapier oder Matte sind stark eingeschnitten', + 'wizard.verdict.tip.cornersTorn': 'An Ecken und Kurven reißt oder verzieht sich die Folie', + 'wizard.verdict.tip.liftsOff': 'Die Folie verrutscht oder löst sich beim Schneiden vom Träger', + + // ---- Schritt 3: Anpassen + 'wizard.adjust.verdict': 'Urteil: {verdict}', + 'wizard.adjust.suggestion': 'Vorschlag', + 'wizard.adjust.changedLegend': 'Orange markierte Werte ändern sich gegenüber dem letzten Test (alt → neu).', + 'wizard.adjust.noChange': 'Keine Änderung gegenüber dem letzten Test – es wird mit denselben Werten geschnitten.', + 'wizard.adjust.suggestionTooltip': 'Die vorgeschlagenen Werte wiederherstellen', + 'wizard.adjust.rerate': 'Bewertung ändern', + 'wizard.adjust.toGrid': 'Stattdessen als Raster testen', + 'wizard.adjust.toGridTooltip': 'Mehrere Varianten in einer Reihe schneiden und die beste wählen', + 'wizard.reason.good': 'Die Werte bleiben unverändert.', + 'wizard.reason.notThrough': 'Mehr Druck (+2), damit das Messer ganz durchschneidet.', + 'wizard.reason.notThroughPasses': 'Der Druck ist schon hoch – stattdessen ein Durchgang mehr, damit das Messer ganz durchschneidet.', + 'wizard.reason.tooDeep': 'Weniger Druck (−2), damit Träger und Matte geschont werden.', + 'wizard.reason.tooDeepBlade': 'Weniger Druck (−2) und eine flachere Klingentiefe (−1), damit Träger und Matte geschont werden.', + 'wizard.reason.tooDeepBladeManual': 'Weniger Druck (−2) und die Klinge am Messer eine Stufe zurückdrehen (−1), damit Träger und Matte geschont werden.', + 'wizard.reason.cornersTorn': 'Langsamer (−1) und etwas weniger Druck (−1): so folgt das Messer Ecken sauberer und reißt die Folie nicht aus.', + 'wizard.reason.liftsOff': 'Langsamer (−1): weniger Zug an der Folie, sie bleibt besser am Träger.', + 'wizard.reason.limit': 'Die Werte sind schon am Rand des möglichen Bereichs – bitte anders anpassen (z. B. Klinge oder Material prüfen).', + + // ---- Schritt 4: Speichern + 'wizard.save.intro': '{n, plural, one {Nach # Test passen die Werte.} other {Nach # Tests passen die Werte.}} Speichere sie als Materialprofil.', + 'wizard.save.back': 'Zurück zur Bewertung', + 'wizard.save.history': 'Wizard: {n, plural, one {# Versuch} other {# Versuche}}, Druck {force}, Geschwindigkeit {speed}', + 'wizard.save.historyNote': 'Wird an die Notiz angehängt: {history}', + 'wizard.save.done': 'Profil „{name}“ gespeichert – die Werte sind jetzt aktiv.', + 'wizard.save.applied': 'Werte übernommen (noch nicht als Profil gespeichert).', + + // ---- Schaltflächen + 'wizard.btn.cutSingle': 'Testschnitt starten', + 'wizard.btn.cutGrid': 'Raster schneiden', + 'wizard.btn.cutNext': 'Nächsten Test schneiden', + 'wizard.btn.cutSame': 'Gleiche Werte nochmal', + 'wizard.btn.cutSameTooltip': 'Noch einmal mit den Werten des letzten Tests schneiden', + 'wizard.btn.cutConfirm': 'Zur Bestätigung nochmal schneiden', + 'wizard.btn.cutConfirmTooltip': 'Einen weiteren Einzeltest mit diesen Werten schneiden, bevor du speicherst', + 'wizard.btn.apply': 'Nur Werte übernehmen', + 'wizard.btn.applyTooltip': 'Die Werte in die Schnitteinstellungen übernehmen, ohne ein Profil zu speichern', + 'wizard.btn.save': 'Als Profil speichern', + 'wizard.btn.back': 'Zurück', + 'wizard.btn.reset': 'Neu beginnen', + 'wizard.reset.tooltip': 'Alle Versuche und Einstellungen des Assistenten verwerfen', + 'wizard.reset.title': 'Assistent zurücksetzen', + 'wizard.reset.message': 'Alle bisherigen Versuche und Einstellungen des Assistenten verwerfen?', + 'wizard.reset.confirm': 'Verwerfen', + + // ---- Tabelle der Versuche + 'wizard.table.title': 'Bisherige Versuche', + 'wizard.table.no': 'Nr.', + 'wizard.table.verdict': 'Urteil', + 'wizard.table.open': 'offen', + 'wizard.table.grid': 'Raster {n}' +} diff --git a/src/shared/i18n/en.ts b/src/shared/i18n/en.ts index 3fc1cb7..f8566e4 100644 --- a/src/shared/i18n/en.ts +++ b/src/shared/i18n/en.ts @@ -4,6 +4,7 @@ */ import type { MessageKey } from './de' import { enCut } from './en.cut' +import { enWizard } from './en.wizard' import { enTrace } from './en.trace' import { enShell } from './en.shell' @@ -282,5 +283,6 @@ export const en: Record = { 'mock.error.notReady': 'No device ready', 'mock.error.fileNotFound': 'File not found: {path}', - ...enCut + ...enCut, + ...enWizard } diff --git a/src/shared/i18n/en.wizard.ts b/src/shared/i18n/en.wizard.ts new file mode 100644 index 0000000..34de229 --- /dev/null +++ b/src/shared/i18n/en.wizard.ts @@ -0,0 +1,126 @@ +import type { deWizard } from './de.wizard' + +/** English texts of the “Calibrate material” wizard (wizard.*); included in en.ts. */ +export const enWizard: Record = { + // ---- Trigger in the cut settings panel + 'wizard.open': 'Calibrate material', + 'wizard.open.tooltip': 'Cuts small test shapes, you rate them and the wizard finds suitable values step by step – save them as a material profile at the end', + + // ---- Dialog: titles + 'wizard.aria': 'Calibrate material', + 'wizard.title.setup': 'Calibrate material – start values', + 'wizard.title.rate': 'Calibrate material – rate test', + 'wizard.title.adjust': 'Calibrate material – adjust values', + 'wizard.title.save': 'Calibrate material – save profile', + 'wizard.title.running': 'Test cut running …', + 'wizard.title.paused': 'Paused – check the media', + 'wizard.title.cancelled': 'Cancelled', + 'wizard.title.error': 'Error', + 'wizard.mat.aria': 'Preview of the test cuts on the work area', + 'wizard.close.tooltip': 'Close – your progress is kept until the app is closed', + + // ---- Step 1: start values and test type + 'wizard.setup.intro': 'The wizard cuts small test shapes with your start values. You rate the result and the values are adjusted – until the cut is right. At the end you save them as a material profile. The values here do not change your current settings.', + 'wizard.setup.startFrom': 'Start values from', + 'wizard.setup.startCurrent': 'Current settings', + 'wizard.mode.aria': 'Test type', + 'wizard.mode.single': 'Single tests in turn', + 'wizard.mode.singleTooltip': 'Cut one test pattern after the other and rate each', + 'wizard.mode.grid': 'Grid (row)', + 'wizard.mode.gridTooltip': 'Cut a row of small squares with increasing force, speed or blade in one go', + 'wizard.mode.singleHint': 'Cuts the test pattern (square, triangle, circle) with tick marks above it showing the trial number. Each test goes next to the previous ones.', + 'wizard.grid.param.aria': 'Varied value', + 'wizard.grid.bladeManual': 'Not possible with a manually set blade – the program cannot adjust it', + 'wizard.grid.start': 'Start', + 'wizard.grid.step': 'Step', + 'wizard.grid.count': 'Count', + 'wizard.grid.variants': 'Variants ({param}): {list}', + 'wizard.grid.hint': 'Cuts a row of small squares one after the other, each with its number as tick marks above it. Afterwards you pick the number that cut best.', + 'wizard.grid.variantLabel': 'No. {n} · {param} {value}', + 'wizard.note.label': 'Note (e.g. blade, mat)', + 'wizard.note.placeholder': 'e.g. red blade, new mat', + + // ---- Eject (wizard only) + 'wizard.eject.label': 'Feed out exactly the right amount of material after the test', + 'wizard.eject.tooltip': 'Advances the material after the cut so you can peel off the test. Applies to the wizard only and does not change the “After cutting” setting.', + 'wizard.eject.distance': 'Extra', + 'wizard.eject.hint': 'After ejecting, put the material back in the same place if the position counter should keep going. For a new piece, choose “New piece of material inserted” below.', + + // ---- Room on the material + 'wizard.slots.status': '{used} of {total} test positions used', + 'wizard.slots.full': 'Material full – insert a new piece', + 'wizard.slots.fullGrid': 'No free row left for the grid or the area is too narrow – insert a new piece', + 'wizard.slots.newPiece': 'New piece of material inserted', + 'wizard.slots.newPieceTooltip': 'Resets the position counter: the next test is cut at the top left again', + + // ---- Cutting + 'wizard.running.gridStep': 'Cut {n} of {total}', + + // ---- Step 2: rate + 'wizard.rate.intro': 'Trial {n} is cut. Carefully peel off the material and check the cut.', + 'wizard.rate.question': 'How is the cut?', + 'wizard.rate.good': 'Looks good – save', + 'wizard.rate.gridIntro': 'Grid cut. Which number (tick marks) cut best? The values of that variant are taken over.', + 'wizard.rate.gridNone': 'None fits – set up the grid again', + 'wizard.verdict.good': 'Good', + 'wizard.verdict.notThrough': 'Not cut through', + 'wizard.verdict.tooDeep': 'Too deep', + 'wizard.verdict.cornersTorn': 'Corners torn', + 'wizard.verdict.liftsOff': 'Material lifts off', + 'wizard.verdict.tip.notThrough': 'The material is still connected or hard to release', + 'wizard.verdict.tip.tooDeep': 'The backing or mat is cut deeply', + 'wizard.verdict.tip.cornersTorn': 'The material tears or distorts at corners and curves', + 'wizard.verdict.tip.liftsOff': 'The material shifts or comes off the backing while cutting', + + // ---- Step 3: adjust + 'wizard.adjust.verdict': 'Verdict: {verdict}', + 'wizard.adjust.suggestion': 'Suggestion', + 'wizard.adjust.changedLegend': 'Values marked in orange change compared with the last test (old → new).', + 'wizard.adjust.noChange': 'No change from the last test – it will be cut with the same values.', + 'wizard.adjust.suggestionTooltip': 'Restore the suggested values', + 'wizard.adjust.rerate': 'Change rating', + 'wizard.adjust.toGrid': 'Test as a grid instead', + 'wizard.adjust.toGridTooltip': 'Cut several variants in a row and pick the best one', + 'wizard.reason.good': 'The values stay unchanged.', + 'wizard.reason.notThrough': 'More force (+2) so the blade cuts all the way through.', + 'wizard.reason.notThroughPasses': 'Force is already high – one more pass instead, so the blade cuts all the way through.', + 'wizard.reason.tooDeep': 'Less force (−2) to spare the backing and mat.', + 'wizard.reason.tooDeepBlade': 'Less force (−2) and a shallower blade depth (−1) to spare the backing and mat.', + 'wizard.reason.tooDeepBladeManual': 'Less force (−2) and turn the blade back one step on the holder (−1) to spare the backing and mat.', + 'wizard.reason.cornersTorn': 'Slower (−1) and slightly less force (−1): the blade follows corners more cleanly and does not tear the material.', + 'wizard.reason.liftsOff': 'Slower (−1): less pull on the material, so it stays on the backing better.', + 'wizard.reason.limit': 'The values are already at the edge of the possible range – please adjust differently (e.g. check the blade or material).', + + // ---- Step 4: save + 'wizard.save.intro': '{n, plural, one {The values fit after # test.} other {The values fit after # tests.}} Save them as a material profile.', + 'wizard.save.back': 'Back to rating', + 'wizard.save.history': 'Wizard: {n, plural, one {# trial} other {# trials}}, force {force}, speed {speed}', + 'wizard.save.historyNote': 'Appended to the note: {history}', + 'wizard.save.done': 'Profile “{name}” saved – the values are now active.', + 'wizard.save.applied': 'Values applied (not saved as a profile yet).', + + // ---- Buttons + 'wizard.btn.cutSingle': 'Start test cut', + 'wizard.btn.cutGrid': 'Cut grid', + 'wizard.btn.cutNext': 'Cut next test', + 'wizard.btn.cutSame': 'Same values again', + 'wizard.btn.cutSameTooltip': 'Cut once more with the values of the last test', + 'wizard.btn.cutConfirm': 'Cut again to confirm', + 'wizard.btn.cutConfirmTooltip': 'Cut one more single test with these values before saving', + 'wizard.btn.apply': 'Only apply values', + 'wizard.btn.applyTooltip': 'Copy the values to the cut settings without saving a profile', + 'wizard.btn.save': 'Save as profile', + 'wizard.btn.back': 'Back', + 'wizard.btn.reset': 'Start over', + 'wizard.reset.tooltip': 'Discard all trials and settings of the wizard', + 'wizard.reset.title': 'Reset wizard', + 'wizard.reset.message': 'Discard all previous trials and settings of the wizard?', + 'wizard.reset.confirm': 'Discard', + + // ---- Table of trials + 'wizard.table.title': 'Trials so far', + 'wizard.table.no': 'No.', + 'wizard.table.verdict': 'Verdict', + 'wizard.table.open': 'open', + 'wizard.table.grid': 'Grid {n}' +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 07226fd..3be4d74 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -62,6 +62,8 @@ export interface MaterialProfile { id?: string name: string cut: CutSettings + /** Freie Notiz zum Material (z. B. Klinge/Matte, Ergebnis des Einmess-Assistenten); max. 200 Zeichen. */ + note?: string } /** Eine installierte Schriftdatei (.ttf/.otf) für das Text-Werkzeug. */