Skip to content

feat(drill): work-zero method picker and redesigned status card - #713

Merged
fixcik merged 2 commits into
masterfrom
feat/workzero-methods
Jul 17, 2026
Merged

feat(drill): work-zero method picker and redesigned status card#713
fixcik merged 2 commits into
masterfrom
feat/workzero-methods

Conversation

@fixcik

@fixcik fixcik commented Jul 17, 2026

Copy link
Copy Markdown
Owner

Refs #708 (эпик #705). Фаза B: карточка «Рабочий ноль» + экран выбора метода + ре-компоновка метода 1 (по хэндоффу дизайнера).

  • Карточка «Рабочий ноль» нового дизайна: статусы (не выставлен / выставлен · метод / станок не подключён), чип качества RMS (good/warn/bad; метод 1 — «без оценки»), рамка по качеству, «сбросить», amber-алерт «отверстия выходят за ход» внутри, подсказка под «Пуск».
  • Экран выбора метода (новый panelMode: "method"): три карточки с чипами-фактов; недоступность с причинами — «нет точек центровки» + кнопка «Открыть редактор» (переход в редактор панели main-окна), «мастер в разработке» (метод 2 при наличии точек — мастер едет следующей фазой), «щуп не настроен» (метод 3); при отключённом станке заблокированы все.
  • Метод 1 (угол-датум): заголовок «‹ Методы», amber-совет про некомпенсируемый перекос; джог/Z — существующие компоненты без изменений; успешный bind пишет метод в новый сессионный workZeroMethodStore.
  • Метаданные метода сбрасываются при падении привязки и при смене проекта с открытым окном сверловки (находка ревью).
  • Чистая логика доступности/состояний в lib/workZeroMethods.ts + тесты по карте состояний дизайнера.
  • Флаговый fiducial-маршрут не тронут (снятие флага — следующая фаза). i18n en/ru с полными плюралами.

Проверки: pnpm build (tsc + i18n-check) чисто, vitest 890 ok. Визуальная проверка — за пользователем.

Summary by CodeRabbit

  • Новые возможности

    • Добавлен выбор из трёх методов установки рабочего нуля с отображением доступности и причин ограничений.
    • Карточка рабочего нуля теперь показывает выбранный метод, качество, смещение, угол и предупреждения.
    • Из окна выбора можно открыть редактор панели для подготовки данных.
    • Добавлены подсказки и предупреждения для недоступных методов, перекоса и выхода за рабочую область.
    • Улучшена навигация между этапами настройки и вкладками проекта.
  • Локализация

    • Добавлены русские и английские тексты для новых экранов, статусов и подсказок.
  • Тесты

    • Добавлены проверки доступности методов и расчёта состояния рабочего нуля.

@fixcik
fixcik enabled auto-merge (squash) July 17, 2026 22:47
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Добавлен экран выбора одного из трёх методов Work Zero, вычисление доступности и состояния карточки, сессионное хранение привязки, обновлённая навигация инспектора и межоконное открытие редактора панели.

Changes

Work Zero

Layer / File(s) Summary
Контракты и вычисление состояния
cuprum-ui/src/lib/workZeroMethods.ts, cuprum-ui/src/workZeroMethodStore.ts, cuprum-ui/src/lib/workZeroMethods.test.ts
Добавлены типы, вычисление доступности методов, состояние карточки, сессионное хранилище и тесты для основных сценариев.
Выбор метода и инспектор
cuprum-ui/src/components/drill/*, cuprum-ui/src/locales/*/drill.json
Инспектор получил режим выбора метода, новый поток привязки и сброса, обновлённую карточку Work Zero, предупреждения и локализацию.
Открытие редактора панели
cuprum-ui/src/components/operations/DrillOperationEditor.tsx, cuprum-ui/src/lib/api.ts, cuprum-ui/src/hooks/useDrillBridge.ts, cuprum-ui/src/navigationStore.ts, cuprum-ui/src/pages/ProjectPage.tsx
Добавлены очистка привязки при смене проекта и межоконный переход к вкладке редактора панели.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DrillPlanInspector
  participant WorkZeroMethodPicker
  participant DrillZeroInspector
  participant WorkZeroStore
  DrillPlanInspector->>WorkZeroMethodPicker: передаёт доступность методов
  WorkZeroMethodPicker->>DrillZeroInspector: запускает выбранный метод
  DrillZeroInspector->>WorkZeroStore: сохраняет результат привязки
  DrillZeroInspector->>DrillPlanInspector: завершает сценарий и возвращает plan
Loading

Possibly related PRs

  • fixcik/cuprum#300 — ранее изменял DrillPlanInspector и его работу с alignmentPoints.
  • fixcik/cuprum#356 — также затрагивал переходы Work Zero в DrillPlanInspector.

Poem

Я, кролик, нулю выбираю путь,
Три метода помогают не свернуть.
Точки, щуп и мастер — всё в строю,
Карточка хранит привязку мою.
В панель редактор прыжок — и вперёд!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно отражает основное изменение: добавлены выбор метода work-zero и переработана статусная карточка.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@fixcik
fixcik merged commit 0cd4de4 into master Jul 17, 2026
3 of 4 checks passed
@fixcik
fixcik deleted the feat/workzero-methods branch July 17, 2026 22:50

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cuprum-ui/src/components/operations/DrillOperationEditor.tsx`:
- Around line 96-105: Replace currentPath-based tracking in the
workZeroProjectRef effect with a stable project identifier, using workingDir or
the project ID from snap. Compare and store that identifier so switching unsaved
projects clears Work Zero metadata, while saving the current project does not
clear it spuriously; keep the existing clearWorkZero behavior.

In `@cuprum-ui/src/locales/en/drill.json`:
- Line 155: Update the noPoints translation in the drill locale to state that
the panel requires at least two alignment points, covering the pointCount < 2
case accurately instead of claiming no points exist.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: fb903355-0049-4468-8567-a848613ad3b6

📥 Commits

Reviewing files that changed from the base of the PR and between e1d6bd5 and 5605ca2.

📒 Files selected for processing (14)
  • cuprum-ui/src/components/drill/DrillPlanInspector.tsx
  • cuprum-ui/src/components/drill/DrillZeroInspector.tsx
  • cuprum-ui/src/components/drill/WorkZeroMethodPicker.tsx
  • cuprum-ui/src/components/drill/WorkZeroStatusCard.tsx
  • cuprum-ui/src/components/operations/DrillOperationEditor.tsx
  • cuprum-ui/src/hooks/useDrillBridge.ts
  • cuprum-ui/src/lib/api.ts
  • cuprum-ui/src/lib/workZeroMethods.test.ts
  • cuprum-ui/src/lib/workZeroMethods.ts
  • cuprum-ui/src/locales/en/drill.json
  • cuprum-ui/src/locales/ru/drill.json
  • cuprum-ui/src/navigationStore.ts
  • cuprum-ui/src/pages/ProjectPage.tsx
  • cuprum-ui/src/workZeroMethodStore.ts

Comment on lines +96 to +105
// The work-zero method metadata (RMS/angle chip) is solved against one panel's
// alignment points; a project switch with the drill window open keeps the
// physical G54 offset but invalidates that metadata — drop it so the status
// card doesn't claim a registration that was never measured for this board.
const workZeroProjectRef = useRef(snap.currentPath);
useEffect(() => {
if (workZeroProjectRef.current === snap.currentPath) return;
workZeroProjectRef.current = snap.currentPath;
useWorkZeroMethod.getState().clearWorkZero();
}, [snap.currentPath]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Не используйте currentPath как идентификатор проекта.

Для несохранённых проектов currentPath остаётся null, поэтому переключение между ними сохраняет чужие Work Zero metadata. И наоборот, первое сохранение того же проекта меняет null на путь и ошибочно очищает metadata. Отслеживайте стабильный workingDir или project ID.

Предлагаемое исправление
-  const workZeroProjectRef = useRef(snap.currentPath);
+  const workZeroProjectRef = useRef(snap.workingDir);
   useEffect(() => {
-    if (workZeroProjectRef.current === snap.currentPath) return;
-    workZeroProjectRef.current = snap.currentPath;
+    if (workZeroProjectRef.current === snap.workingDir) return;
+    workZeroProjectRef.current = snap.workingDir;
     useWorkZeroMethod.getState().clearWorkZero();
-  }, [snap.currentPath]);
+  }, [snap.workingDir]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// The work-zero method metadata (RMS/angle chip) is solved against one panel's
// alignment points; a project switch with the drill window open keeps the
// physical G54 offset but invalidates that metadata — drop it so the status
// card doesn't claim a registration that was never measured for this board.
const workZeroProjectRef = useRef(snap.currentPath);
useEffect(() => {
if (workZeroProjectRef.current === snap.currentPath) return;
workZeroProjectRef.current = snap.currentPath;
useWorkZeroMethod.getState().clearWorkZero();
}, [snap.currentPath]);
// The work-zero method metadata (RMS/angle chip) is solved against one panel's
// alignment points; a project switch with the drill window open keeps the
// physical G54 offset but invalidates that metadata — drop it so the status
// card doesn't claim a registration that was never measured for this board.
const workZeroProjectRef = useRef(snap.workingDir);
useEffect(() => {
if (workZeroProjectRef.current === snap.workingDir) return;
workZeroProjectRef.current = snap.workingDir;
useWorkZeroMethod.getState().clearWorkZero();
}, [snap.workingDir]);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cuprum-ui/src/components/operations/DrillOperationEditor.tsx` around lines 96
- 105, Replace currentPath-based tracking in the workZeroProjectRef effect with
a stable project identifier, using workingDir or the project ID from snap.
Compare and store that identifier so switching unsaved projects clears Work Zero
metadata, while saving the current project does not clear it spuriously; keep
the existing clearWorkZero behavior.

"holes_other": "holes: {{count}}"
},
"unavailable": {
"noPoints": "the panel has no alignment points",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Исправьте причину недоступности для одной точки.

noPoints используется при pointCount < 2, поэтому при одной точке сообщение ошибочно утверждает, что точек нет. Укажите требование минимум двух точек.

Предлагаемое исправление
-      "noPoints": "the panel has no alignment points",
+      "noPoints": "add at least 2 alignment points",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"noPoints": "the panel has no alignment points",
"noPoints": "add at least 2 alignment points",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cuprum-ui/src/locales/en/drill.json` at line 155, Update the noPoints
translation in the drill locale to state that the panel requires at least two
alignment points, covering the pointCount < 2 case accurately instead of
claiming no points exist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant