@alfadocs/ui-kit-debug 1.48.0 → 1.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{agenda-card-C4h0xMGi.js → agenda-card-CjjxlA9K.js} +2 -2
- package/dist/_chunks/{agenda-card-C4h0xMGi.js.map → agenda-card-CjjxlA9K.js.map} +1 -1
- package/dist/_chunks/{agenda-tray-DNZYW2xt.js → agenda-tray-BhZASyJm.js} +2 -2
- package/dist/_chunks/{agenda-tray-DNZYW2xt.js.map → agenda-tray-BhZASyJm.js.map} +1 -1
- package/dist/_chunks/{alia-sidebar-Crn8OGPF.js → alia-sidebar-Dx-oeOV2.js} +3 -3
- package/dist/_chunks/{alia-sidebar-Crn8OGPF.js.map → alia-sidebar-Dx-oeOV2.js.map} +1 -1
- package/dist/_chunks/{appointment-card-CvGU0QP6.js → appointment-card-BgLpE6T5.js} +2 -2
- package/dist/_chunks/{appointment-card-CvGU0QP6.js.map → appointment-card-BgLpE6T5.js.map} +1 -1
- package/dist/_chunks/{appointment-peek--dmWznLZ.js → appointment-peek-BDiCIBb-.js} +2 -2
- package/dist/_chunks/{appointment-peek--dmWznLZ.js.map → appointment-peek-BDiCIBb-.js.map} +1 -1
- package/dist/_chunks/{appointment-timeline-y9uYZMUd.js → appointment-timeline-wQ-PdkFV.js} +2 -2
- package/dist/_chunks/{appointment-timeline-y9uYZMUd.js.map → appointment-timeline-wQ-PdkFV.js.map} +1 -1
- package/dist/_chunks/{appointment-tray-BTecNeSb.js → appointment-tray-D7Gt6m8x.js} +2 -2
- package/dist/_chunks/{appointment-tray-BTecNeSb.js.map → appointment-tray-D7Gt6m8x.js.map} +1 -1
- package/dist/_chunks/{avatar-CkDeQOSI.js → avatar-BVvjKNTp.js} +2 -2
- package/dist/_chunks/avatar-BVvjKNTp.js.map +1 -0
- package/dist/_chunks/{balance-badge-cell-CA0YNJMR.js → balance-badge-cell-klaxFNL_.js} +3 -3
- package/dist/_chunks/{balance-badge-cell-CA0YNJMR.js.map → balance-badge-cell-klaxFNL_.js.map} +1 -1
- package/dist/_chunks/{booking-BQYFDcrz.js → booking-BF9pVa2n.js} +377 -381
- package/dist/_chunks/booking-BF9pVa2n.js.map +1 -0
- package/dist/_chunks/{calendar-DjoJ9ovF.js → calendar-Bt44KMNO.js} +3 -2
- package/dist/_chunks/{calendar-DjoJ9ovF.js.map → calendar-Bt44KMNO.js.map} +1 -1
- package/dist/_chunks/calendar-workspace-C_eXL1by.js +10464 -0
- package/dist/_chunks/{calendar-workspace-D8zX9JWm.js.map → calendar-workspace-C_eXL1by.js.map} +1 -1
- package/dist/_chunks/{chat-message-Co_NRGM4.js → chat-message-B4ihjNy3.js} +2 -2
- package/dist/_chunks/{chat-message-Co_NRGM4.js.map → chat-message-B4ihjNy3.js.map} +1 -1
- package/dist/_chunks/{clinical-note-card-DYDQ3q2x.js → clinical-note-card-B7s5BtEl.js} +2 -2
- package/dist/_chunks/{clinical-note-card-DYDQ3q2x.js.map → clinical-note-card-B7s5BtEl.js.map} +1 -1
- package/dist/_chunks/{data-table-DWOSxlsy.js → data-table-CrI3_bjH.js} +411 -410
- package/dist/_chunks/data-table-CrI3_bjH.js.map +1 -0
- package/dist/_chunks/{dependent-selector-BR_8D2Qu.js → dependent-selector-58hTg5rB.js} +2 -2
- package/dist/_chunks/{dependent-selector-BR_8D2Qu.js.map → dependent-selector-58hTg5rB.js.map} +1 -1
- package/dist/_chunks/{entity-summary-Ckz_U00H.js → entity-summary-CFJfBdVP.js} +2 -2
- package/dist/_chunks/{entity-summary-Ckz_U00H.js.map → entity-summary-CFJfBdVP.js.map} +1 -1
- package/dist/_chunks/{file-manager-CqgxLqoA.js → file-manager-C6QQPQV5.js} +2 -2
- package/dist/_chunks/{file-manager-CqgxLqoA.js.map → file-manager-C6QQPQV5.js.map} +1 -1
- package/dist/_chunks/link-cell-renderer-CkNbUsBM.js +867 -0
- package/dist/_chunks/link-cell-renderer-CkNbUsBM.js.map +1 -0
- package/dist/_chunks/{marketplace-app-shell-Dehuxbi-.js → marketplace-app-shell-1uKqs4gD.js} +2 -2
- package/dist/_chunks/{marketplace-app-shell-Dehuxbi-.js.map → marketplace-app-shell-1uKqs4gD.js.map} +1 -1
- package/dist/_chunks/{message-card-DKOtnBHy.js → message-card-C2zsvyj0.js} +2 -2
- package/dist/_chunks/{message-card-DKOtnBHy.js.map → message-card-C2zsvyj0.js.map} +1 -1
- package/dist/_chunks/{message-tray-COMEtmyr.js → message-tray-CMlmxdH2.js} +2 -2
- package/dist/_chunks/{message-tray-COMEtmyr.js.map → message-tray-CMlmxdH2.js.map} +1 -1
- package/dist/_chunks/{notes-panel-BiOxZL_0.js → notes-panel-xxpFt-I1.js} +2 -2
- package/dist/_chunks/{notes-panel-BiOxZL_0.js.map → notes-panel-xxpFt-I1.js.map} +1 -1
- package/dist/_chunks/{operator-hero-5061fkY5.js → operator-hero-DyrNLoRO.js} +2 -2
- package/dist/_chunks/{operator-hero-5061fkY5.js.map → operator-hero-DyrNLoRO.js.map} +1 -1
- package/dist/_chunks/{patient-details-C23Hdm8v.js → patient-details-tTlvrJSU.js} +2 -2
- package/dist/_chunks/{patient-details-C23Hdm8v.js.map → patient-details-tTlvrJSU.js.map} +1 -1
- package/dist/_chunks/{patient-summary-card-C36L3h7h.js → patient-summary-card-DQ__6DR-.js} +2 -2
- package/dist/_chunks/{patient-summary-card-C36L3h7h.js.map → patient-summary-card-DQ__6DR-.js.map} +1 -1
- package/dist/_chunks/{practice-profile-hero-CPy5h2yI.js → practice-profile-hero-B-WcJYNH.js} +2 -2
- package/dist/_chunks/{practice-profile-hero-CPy5h2yI.js.map → practice-profile-hero-B-WcJYNH.js.map} +1 -1
- package/dist/_chunks/{practice-results-t2BHht91.js → practice-results-EKRiqWtQ.js} +2 -2
- package/dist/_chunks/{practice-results-t2BHht91.js.map → practice-results-EKRiqWtQ.js.map} +1 -1
- package/dist/_chunks/{signature-request-15D363w5.js → signature-request-BUGeG8oD.js} +2 -2
- package/dist/_chunks/{signature-request-15D363w5.js.map → signature-request-BUGeG8oD.js.map} +1 -1
- package/dist/_chunks/{task-card-CTTQfPS6.js → task-card-jaOhnj_q.js} +31 -30
- package/dist/_chunks/task-card-jaOhnj_q.js.map +1 -0
- package/dist/_chunks/{task-tray-JA-qp_pB.js → task-tray-HHyxi9ga.js} +2 -2
- package/dist/_chunks/{task-tray-JA-qp_pB.js.map → task-tray-HHyxi9ga.js.map} +1 -1
- package/dist/_chunks/{tasks-panel-C_dVDQKJ.js → tasks-panel-DbSjq_mz.js} +2 -2
- package/dist/_chunks/{tasks-panel-C_dVDQKJ.js.map → tasks-panel-DbSjq_mz.js.map} +1 -1
- package/dist/_chunks/{timeline-61AihzYz.js → timeline-ChY7iZrs.js} +2 -2
- package/dist/_chunks/{timeline-61AihzYz.js.map → timeline-ChY7iZrs.js.map} +1 -1
- package/dist/_chunks/{use-appointment-details-read-D2FH-cHF.js → use-appointment-details-read-5-hV-2xA.js} +4 -4
- package/dist/_chunks/{use-appointment-details-read-D2FH-cHF.js.map → use-appointment-details-read-5-hV-2xA.js.map} +1 -1
- package/dist/agent-catalog.json +1 -1
- package/dist/components/agenda-card/index.js +1 -1
- package/dist/components/agenda-tray/index.js +1 -1
- package/dist/components/appointment-card/index.js +2 -2
- package/dist/components/appointment-details-panel/index.js +1 -1
- package/dist/components/appointment-peek/index.js +1 -1
- package/dist/components/appointment-timeline/index.js +1 -1
- package/dist/components/avatar/avatar.d.ts.map +1 -1
- package/dist/components/avatar/index.js +1 -1
- package/dist/components/booking/booking.d.ts.map +1 -1
- package/dist/components/booking/cascade.d.ts +5 -0
- package/dist/components/booking/cascade.d.ts.map +1 -1
- package/dist/components/booking/index.js +1 -1
- package/dist/components/calendar/calendar.d.ts.map +1 -1
- package/dist/components/calendar/index.js +1 -1
- package/dist/components/chat-message/index.js +1 -1
- package/dist/components/clinical-note-card/index.js +1 -1
- package/dist/components/data-table/filters/number-filter.d.ts +26 -12
- package/dist/components/data-table/filters/number-filter.d.ts.map +1 -1
- package/dist/components/data-table/index.js +2 -2
- package/dist/components/data-table/toolbar.d.ts.map +1 -1
- package/dist/components/dependent-selector/index.js +1 -1
- package/dist/components/entity-summary/index.js +1 -1
- package/dist/components/file-manager/index.js +1 -1
- package/dist/components/message-card/index.js +1 -1
- package/dist/components/message-tray/index.js +1 -1
- package/dist/components/notes-panel/index.js +1 -1
- package/dist/components/operator-hero/index.js +1 -1
- package/dist/components/patient-details/index.js +1 -1
- package/dist/components/patient-summary-card/index.js +1 -1
- package/dist/components/patient-table/index.js +1 -1
- package/dist/components/practice-profile-hero/index.js +1 -1
- package/dist/components/practice-results/index.js +1 -1
- package/dist/components/task-card/index.js +1 -1
- package/dist/components/task-card/task-card.d.ts +3 -2
- package/dist/components/task-card/task-card.d.ts.map +1 -1
- package/dist/components/task-tray/index.js +1 -1
- package/dist/components/tasks-panel/index.js +1 -1
- package/dist/components/timeline/index.js +1 -1
- package/dist/i18n/locales/ar.d.ts +19 -14
- package/dist/i18n/locales/ar.d.ts.map +1 -1
- package/dist/i18n/locales/ar.js +19 -14
- package/dist/i18n/locales/ar.js.map +1 -1
- package/dist/i18n/locales/de.d.ts +19 -14
- package/dist/i18n/locales/de.d.ts.map +1 -1
- package/dist/i18n/locales/de.js +19 -14
- package/dist/i18n/locales/de.js.map +1 -1
- package/dist/i18n/locales/el.d.ts +19 -14
- package/dist/i18n/locales/el.d.ts.map +1 -1
- package/dist/i18n/locales/el.js +19 -14
- package/dist/i18n/locales/el.js.map +1 -1
- package/dist/i18n/locales/en.d.ts +5 -0
- package/dist/i18n/locales/en.d.ts.map +1 -1
- package/dist/i18n/locales/en.js +6 -0
- package/dist/i18n/locales/en.js.map +1 -1
- package/dist/i18n/locales/es.d.ts +19 -14
- package/dist/i18n/locales/es.d.ts.map +1 -1
- package/dist/i18n/locales/es.js +19 -14
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.d.ts +19 -14
- package/dist/i18n/locales/fr.d.ts.map +1 -1
- package/dist/i18n/locales/fr.js +19 -14
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hi.d.ts +19 -14
- package/dist/i18n/locales/hi.d.ts.map +1 -1
- package/dist/i18n/locales/hi.js +19 -14
- package/dist/i18n/locales/hi.js.map +1 -1
- package/dist/i18n/locales/it.d.ts +5 -0
- package/dist/i18n/locales/it.d.ts.map +1 -1
- package/dist/i18n/locales/it.js +6 -0
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/ja.d.ts +19 -14
- package/dist/i18n/locales/ja.d.ts.map +1 -1
- package/dist/i18n/locales/ja.js +19 -14
- package/dist/i18n/locales/ja.js.map +1 -1
- package/dist/i18n/locales/nl.d.ts +19 -14
- package/dist/i18n/locales/nl.d.ts.map +1 -1
- package/dist/i18n/locales/nl.js +19 -14
- package/dist/i18n/locales/nl.js.map +1 -1
- package/dist/i18n/locales/pl.d.ts +19 -14
- package/dist/i18n/locales/pl.d.ts.map +1 -1
- package/dist/i18n/locales/pl.js +19 -14
- package/dist/i18n/locales/pl.js.map +1 -1
- package/dist/i18n/locales/pt.d.ts +19 -14
- package/dist/i18n/locales/pt.d.ts.map +1 -1
- package/dist/i18n/locales/pt.js +19 -14
- package/dist/i18n/locales/pt.js.map +1 -1
- package/dist/i18n/locales/ro.d.ts +19 -14
- package/dist/i18n/locales/ro.d.ts.map +1 -1
- package/dist/i18n/locales/ro.js +19 -14
- package/dist/i18n/locales/ro.js.map +1 -1
- package/dist/i18n/locales/ru.d.ts +19 -14
- package/dist/i18n/locales/ru.d.ts.map +1 -1
- package/dist/i18n/locales/ru.js +19 -14
- package/dist/i18n/locales/ru.js.map +1 -1
- package/dist/i18n/locales/sq.d.ts +19 -14
- package/dist/i18n/locales/sq.d.ts.map +1 -1
- package/dist/i18n/locales/sq.js +19 -14
- package/dist/i18n/locales/sq.js.map +1 -1
- package/dist/i18n/locales/sv.d.ts +19 -14
- package/dist/i18n/locales/sv.d.ts.map +1 -1
- package/dist/i18n/locales/sv.js +19 -14
- package/dist/i18n/locales/sv.js.map +1 -1
- package/dist/i18n/locales/tr.d.ts +19 -14
- package/dist/i18n/locales/tr.d.ts.map +1 -1
- package/dist/i18n/locales/tr.js +19 -14
- package/dist/i18n/locales/tr.js.map +1 -1
- package/dist/i18n/locales/zh.d.ts +19 -14
- package/dist/i18n/locales/zh.d.ts.map +1 -1
- package/dist/i18n/locales/zh.js +19 -14
- package/dist/i18n/locales/zh.js.map +1 -1
- package/dist/index.js +34 -34
- package/dist/locales/ar.json +19 -14
- package/dist/locales/de.json +19 -14
- package/dist/locales/el.json +19 -14
- package/dist/locales/en.json +5 -0
- package/dist/locales/es.json +19 -14
- package/dist/locales/fr.json +19 -14
- package/dist/locales/hi.json +19 -14
- package/dist/locales/it.json +5 -0
- package/dist/locales/ja.json +19 -14
- package/dist/locales/nl.json +19 -14
- package/dist/locales/pl.json +19 -14
- package/dist/locales/pt.json +19 -14
- package/dist/locales/ro.json +19 -14
- package/dist/locales/ru.json +19 -14
- package/dist/locales/sq.json +19 -14
- package/dist/locales/sv.json +19 -14
- package/dist/locales/tr.json +19 -14
- package/dist/locales/zh.json +19 -14
- package/dist/patterns/alia-assistant/index.js +1 -1
- package/dist/patterns/calendar/calendar-workspace.d.ts +10 -0
- package/dist/patterns/calendar/calendar-workspace.d.ts.map +1 -1
- package/dist/patterns/calendar/calendar.surface.d.ts +4 -1
- package/dist/patterns/calendar/calendar.surface.d.ts.map +1 -1
- package/dist/patterns/calendar/index.js +1 -1
- package/dist/patterns/marketplace-app-shell/index.js +1 -1
- package/dist/patterns/signature-request/index.js +1 -1
- package/dist/tokens.css +1 -1
- package/package.json +12 -12
- package/dist/_chunks/avatar-CkDeQOSI.js.map +0 -1
- package/dist/_chunks/booking-BQYFDcrz.js.map +0 -1
- package/dist/_chunks/calendar-workspace-D8zX9JWm.js +0 -10423
- package/dist/_chunks/data-table-DWOSxlsy.js.map +0 -1
- package/dist/_chunks/link-cell-renderer-Tswqf6BT.js +0 -778
- package/dist/_chunks/link-cell-renderer-Tswqf6BT.js.map +0 -1
- package/dist/_chunks/task-card-CTTQfPS6.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notes-panel-BiOxZL_0.js","sources":["../../src/components/notes-panel/notes-panel.agent.ts","../../src/components/notes-panel/notes-panel.tsx"],"sourcesContent":["/* -------------------------------------------------------------------- */\n/* Agent adapter — NotesPanel. */\n/* */\n/* The Notes tool: a composer over a note timeline. The agent reads the */\n/* timeline STRUCTURE (note ids + pinned / flagged / clinical / deleted */\n/* flags, never the note body or author, both PHI), composes and commits */\n/* a new note, and toggles a note's pinned / flagged state. The toggles */\n/* return the host's promise: a refusal rejects, and the panel restores */\n/* the note and explains it. A toggle the panel refuses (deleted note, */\n/* gate, write still pending) rejects too, without reaching the host. */\n/* `add_note` carries the `phi` safety class: a note body is */\n/* patient-identifiable clinical content, so the host gates it behind the */\n/* same confirm-before-act as a destructive write and never auto-confirms.*/\n/* A clinical submission also requires the host's */\n/* `practice_add_clinical_note` permission (the handle drops it when the */\n/* gate is closed). Delete stays a panel control */\n/* the reader confirms, not an agent action. Host-owned per-note */\n/* `noteActions` sit outside this handle: an agent reaches them through */\n/* the host's own adapters. */\n/* -------------------------------------------------------------------- */\n\nimport type { AgentAdapter } from '../../agent/types';\nimport type { NotesPanelHandle } from './notes-panel';\n\nexport const notesPanelAgent: AgentAdapter<NotesPanelHandle> = {\n id: 'notes-panel',\n // 'submit' backs add_note (compose + commit a note). pin / flag are toggles\n // with no dedicated capability in the closed vocabulary.\n capabilities: ['submit'],\n state: {\n notes: {\n type: 'Array<{ id?: string; pinned: boolean; flagged: boolean; clinical: boolean; deleted: boolean }>',\n descriptionKey: 'ui.agent.notesPanel.state.notes',\n description:\n 'Timeline note ids + pinned / flagged / clinical / deleted flags. Never the note body or author (both PHI). A note whose delete is in flight is left out; a pin or flag in flight is reported with its new value. A deleted note takes no pin or flag.',\n read: (handle) => handle.getNotes(),\n },\n canAddClinical: {\n type: 'boolean',\n descriptionKey: 'ui.agent.notesPanel.state.canAddClinical',\n description:\n 'Whether the current user may write clinical notes (the practice_add_clinical_note permission gate).',\n read: (handle) => handle.canAddClinical(),\n },\n currentNoteId: {\n type: 'string | null',\n descriptionKey: 'ui.agent.notesPanel.state.currentNoteId',\n description:\n 'Id of the note the host has addressed — the one marked, scrolled to and focused. Null when none is. An id only, never note content.',\n read: (handle) => handle.getCurrentNoteId(),\n },\n },\n actions: {\n add_note: {\n // Writes a clinical/admin note body — patient-identifiable content. PHI.\n safety: 'phi',\n argsType: '{ content: string; clinical: boolean }',\n argsSchema: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description:\n 'Note body. Rich HTML for the rich composer, else plain text.',\n },\n clinical: {\n type: 'boolean',\n description:\n 'Whether the note is clinical. Requires the clinical-note permission; the submission is dropped when the gate is closed.',\n },\n },\n required: ['content', 'clinical'],\n },\n openWorld: true,\n descriptionKey: 'ui.agent.notesPanel.actions.addNote',\n description:\n 'Compose and commit a new note. A clinical note requires the clinical-note permission (read canAddClinical first).',\n examples: [\n {\n args: { content: 'Patient reported improvement.', clinical: true },\n note: 'Add a clinical note.',\n },\n ],\n invoke: (handle, args: { content: string; clinical: boolean }) => {\n return handle.addNote(args);\n },\n },\n toggle_pin: {\n // A host write; it re-orders the timeline (pinned notes lead).\n safety: 'write',\n argsType: '{ id: string }',\n argsSchema: {\n type: 'object',\n properties: { id: { type: 'string' } },\n required: ['id'],\n },\n idempotent: false,\n // Reaches the host's data source; the result is the host's promise.\n openWorld: true,\n errors: [\n 'The panel offers no pin here: no onTogglePin, no note with this id, a deleted note, or actions.pin is false.',\n 'A pin or delete for this note is still pending. Read notes again once it has settled.',\n \"The host refused the change. The pin is restored and the panel shows the host's message.\",\n ],\n descriptionKey: 'ui.agent.notesPanel.actions.togglePin',\n description:\n \"Toggle the pinned state of the note with the given id. Returns the host's promise; a refusal restores the pin and the panel shows the host's message. Rejects without reaching the host when the panel refuses: a deleted note, actions.pin false, or a write for the note still pending.\",\n invoke: (handle, args: { id: string }) => handle.togglePin(args.id),\n },\n toggle_flag: {\n safety: 'write',\n argsType: '{ id: string }',\n argsSchema: {\n type: 'object',\n properties: { id: { type: 'string' } },\n required: ['id'],\n },\n idempotent: false,\n // Reaches the host's data source; the result is the host's promise.\n openWorld: true,\n errors: [\n 'The panel offers no flag here: no onToggleFlag, no note with this id, or a deleted note.',\n 'A flag or delete for this note is still pending. Read notes again once it has settled.',\n \"The host refused the change. The flag is restored and the panel shows the host's message.\",\n ],\n descriptionKey: 'ui.agent.notesPanel.actions.toggleFlag',\n description:\n \"Toggle the flagged state of the note with the given id. Returns the host's promise; a refusal restores the flag and the panel shows the host's message. Rejects without reaching the host when the panel refuses: a deleted note, or a write for the note still pending.\",\n invoke: (handle, args: { id: string }) => handle.toggleFlag(args.id),\n },\n },\n domHooks: {\n root: {\n attr: 'data-component',\n value: 'notes-panel',\n description: 'Marks the NotesPanel region.',\n },\n instanceId: {\n attr: 'data-component-id',\n sourceProp: 'id',\n description:\n 'Sourced from the id prop. Required to address a specific notes panel from the agent.',\n },\n item: {\n attr: 'data-note-id',\n description:\n 'Stable note id on each rendered note row. Row controls carry data-note-action: edit, delete, pin or flag.',\n },\n },\n};\n","import {\n forwardRef,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport { cva } from 'class-variance-authority';\nimport { useTranslation } from 'react-i18next';\nimport { getErrorMessage } from '../_shared/get-error-message';\nimport { handledRejection } from '../_shared/handled-rejection';\nimport { useAgentRegistration } from '../../agent/registry';\nimport { notesPanelAgent } from './notes-panel.agent';\nimport { ClinicalNoteCard } from '../clinical-note-card';\nimport type { ClinicalNoteCardProps } from '../clinical-note-card';\nimport { RichTextEditor } from '../rich-text-editor';\nimport type {\n RichTextEditorHandle,\n RichTextEditorProps,\n RichTextEditorToolbar,\n RedactorFactory,\n AiConsentGate,\n} from '../rich-text-editor';\nimport { TextArea } from '../text-area';\nimport { Alert } from '../alert';\nimport { Button, IconButton } from '../button';\nimport { Switch } from '../switch';\nimport { Tooltip } from '../tooltip';\nimport { Card } from '../card/card';\nimport { CONTENT_ENTER_CLASS, Skeleton } from '../skeleton/skeleton';\nimport { Dialog } from '../dialog';\nimport { NotebookPen, Pencil, Trash2 } from 'lucide-react';\nimport { PanelHeader } from '../panel-header';\nimport { REFLOW_ROW_CLASS, useListReflow } from '../../hooks/use-list-reflow';\nimport { useExitTransition } from '../../hooks/use-exit-transition';\nimport { useIsomorphicLayoutEffect } from '../../hooks/use-isomorphic-layout-effect';\nimport { useTheme } from '../../hooks/use-theme';\n\n/* ------------------------------------------------------------------ */\n/* NotesPanel — the Notes tool for the Control Room rail. */\n/* */\n/* A composer over an elevated ClinicalNoteCard timeline. Drops */\n/* into a ControlRoomRail tool `panel`, the patient profile, or the */\n/* care-plan editor — anywhere notes about the open entity belong. */\n/* The composer is the kit RichTextEditor by default (degrades to a */\n/* textarea where Redactor is absent), carries a permission-gated */\n/* \"clinical note\" toggle, and forwards the editor's AI affordances. */\n/* The note attaches to whatever entity the host is showing — the */\n/* host owns the attachment; the panel only emits content + clinical. */\n/* Pinned notes lead; pin / flag are inline per-note toggles. */\n/* ------------------------------------------------------------------ */\n\n/**\n * One note in the panel — the data subset of `ClinicalNoteCard`.\n *\n * `aria-label` names the card for assistive tech. Set it whenever a row is not\n * a clinical note: the card's fallback name is \"Clinical note\", so an entry\n * that is something else (a dated event, an import) is announced as one.\n */\nexport type NotesPanelNote = Pick<\n ClinicalNoteCardProps,\n | 'id'\n | 'dateIso'\n | 'createdAtIso'\n | 'author'\n | 'clinical'\n | 'attachedTo'\n | 'content'\n | 'contentFormat'\n | 'pinned'\n | 'flagged'\n | 'aria-label'\n | 'deleted'\n | 'operatorName'\n> & {\n /** What the host lets the reader do with this note. */\n actions?: NotesPanelNoteActions;\n /**\n * The host keeps this note when it is deleted and lists it again marked\n * `deleted` (a clinical record, for example). Its delete does not fade\n * the row: the row stays in place, its controls paused, until `notes`\n * marks it deleted or drops it. Host controls from `noteActions` hear\n * `deleting: true` meanwhile, so they can pause too. Leave it unset for\n * a note the host removes, or the row fades out and then comes back.\n */\n keptOnDelete?: boolean;\n};\n\n/** Per-note write permissions; an absent key means allowed. The panel hides\n * the pencil on `edit: false`, the pin toggle on `pin: false`, the built-in\n * delete on `delete: false`, and the pin, flag, pencil and delete on a\n * deleted note. */\nexport type NotesPanelNoteActions = {\n edit?: boolean;\n delete?: boolean;\n pin?: boolean;\n};\n\n/**\n * Curated agent handle for NotesPanel. Reads the note timeline's STRUCTURE\n * (ids + pinned / flagged / clinical / deleted flags, never the note body\n * or author, both PHI) and drives the composer + per-note toggles. See\n * `notes-panel.agent.ts`.\n */\nexport interface NotesPanelHandle {\n /** Timeline snapshot — ids + flags only, never note content (PHI). A note\n * whose delete is in flight is left out; a pin or flag in flight reports\n * the value it moved to. `deleted` marks a note kept for the record: it\n * takes no pin or flag. */\n getNotes: () => Array<{\n id?: string;\n pinned: boolean;\n flagged: boolean;\n clinical: boolean;\n deleted: boolean;\n }>;\n /** Whether the composer is mounted (onAddNote is wired). */\n canAddNote: () => boolean;\n /** Whether clinical notes may be written (the permission gate). */\n canAddClinical: () => boolean;\n /** Id of the note the host has addressed, or null when none is. */\n getCurrentNoteId: () => string | null;\n /** Commit a new note with explicit content (mirrors the composer's submit). */\n addNote: (submission: NotesPanelSubmission) => void | Promise<void>;\n /**\n * Toggle a note's pinned state: the same path as the pin toggle, with its\n * gate. Returns the host's promise, so a refusal rejects (a synchronous\n * throw comes back as a handled rejection). Also rejects, without calling\n * the host, when the panel refuses: no `onTogglePin`, no note with this\n * id, a deleted note, `actions.pin: false`, or a pin or delete for the\n * note still pending. `undefined` only when the host returned nothing.\n */\n togglePin: (id: string) => void | Promise<void>;\n /** As `togglePin`, for the flag. Refused for a deleted note. */\n toggleFlag: (id: string) => void | Promise<void>;\n}\n\n/** A write the host refused, as `onWriteError` hears it. */\nexport interface NotesPanelWriteFailure {\n /** What did not happen. `unpin` and `unflag` are the toggles turned off;\n * `add` and `edit` are the composer's saves. */\n kind: 'add' | 'edit' | 'delete' | 'pin' | 'unpin' | 'flag' | 'unflag';\n /** The note written to. Absent for `add`: the note never existed. */\n noteId?: string;\n /** What the handler rejected or threw with. */\n error: unknown;\n /**\n * Whether the panel told the reader. `false` when the answer came after\n * the panel unmounted or while it was hidden, inert or aria-hidden (a\n * rail panel on its way out, say), after the note left `notes` (for an\n * edit, also once it was marked deleted), while the note was being\n * deleted, after a newer write on the same note started, or when a new\n * write began before the refusal could show (a new write clears the\n * message). A refused save the panel did not show has lost its draft\n * too. It is decided after the render that follows the refusal, so a\n * host that changes `notes` or hides the panel in the same tick as it\n * rejects is judged on that change.\n */\n shown: boolean;\n}\n\n/** Payload handed to `onAddNote` when the composer commits. */\nexport interface NotesPanelSubmission {\n /** The note body — rich HTML (`composer='rich'`) or plain text. */\n content: string;\n /** Whether the \"clinical note\" toggle was set. */\n clinical: boolean;\n}\n\nexport interface NotesPanelProps extends Omit<\n HTMLAttributes<HTMLElement>,\n 'title' | 'children'\n> {\n /**\n * Stable instance id. Surfaced on the root as `data-component-id` so an\n * agent / MCP UI bridge can address this specific notes panel.\n */\n id?: string;\n /** Notes to render, newest-first by convention. Pinned notes lead. */\n notes: NotesPanelNote[];\n /**\n * Commit a new note. Omit to hide the composer (read-only timeline). Return\n * a promise to keep the draft until the host has saved it: the draft clears\n * when it resolves, and a rejection keeps it and shows the error's message.\n */\n onAddNote?: (submission: NotesPanelSubmission) => void | Promise<void>;\n /** The host's notes read. `'loading'` and `'error'` never show the empty\n * text; notes already held still render. Default `'ready'`. */\n status?: 'ready' | 'loading' | 'error';\n /** Retry a failed read. Renders a retry button in the error state. */\n onRetry?: () => void;\n /**\n * The note the reader ASKED for, addressed by id from somewhere else in the\n * record — a marker in a chart, a row in a grid, an agent. The panel marks\n * it, scrolls it to the middle of its own scroll region and moves focus to\n * it, and renders it unclamped so the thing that was asked for is readable\n * in full without a second click.\n *\n * Opening a panel is not the same as answering a question: a rail's\n * `setActiveTool` moves no focus and announces nothing, so a control whose\n * name promises \"in the notes panel\" produces no perceivable change for a\n * keyboard or screen-reader reader unless the panel lands them on the note.\n * That is what this prop is for; without it, a host has to reach into the\n * panel's DOM to do the same job.\n *\n * Marked on three channels, never colour alone (WCAG 1.4.1): an accent\n * wash that fades in and out over the card (steady where motion is off),\n * the focus outline on the row, and `aria-current` plus a visually-hidden\n * sentence naming the mark. Nothing is left on the row once the wash ends.\n *\n * Ids that match no note are ignored. To address the SAME note twice — the\n * reader pressing the same marker again after scrolling away — bump\n * `currentNoteKey` alongside it; this prop alone is a value, not a request.\n */\n currentNoteId?: string;\n /**\n * Bump on every address to re-scroll and re-focus the note in `currentNoteId`\n * and replay its wash, even when the id has not changed.\n *\n * Addressing is a request, not a value: a reader who presses the same marker\n * a second time (having scrolled away, or having moved focus off the note) is\n * asking to be taken back, and a control whose name promises the notes panel\n * must do something perceivable every time it is pressed. Without this the\n * second press is inert — the panel is already showing that note, so nothing\n * re-runs. Hosts increment a counter in the same handler that opens the tool.\n */\n currentNoteKey?: string | number;\n\n /* ----- Composer ----- */\n /**\n * `'rich'` (default) mounts the kit `RichTextEditor` (Redactor; degrades to a\n * textarea where Redactor is absent). `'plain'` keeps a simple `TextArea` for\n * lightweight surfaces / deterministic tests.\n */\n composer?: 'rich' | 'plain';\n /** Toolbar preset for the rich composer. Defaults to `'standard'`. */\n editorToolbar?: RichTextEditorToolbar;\n /** Inject the Redactor factory for the rich composer (else `window.$R`). */\n redactor?: RedactorFactory;\n /** Consumer image-upload endpoint for the rich composer. */\n imageUploadUrl?: string;\n\n /* ----- Clinical flag (permission-gated) ----- */\n /** Show the \"clinical note\" toggle in the composer. Default `true`. */\n showClinicalToggle?: boolean;\n /**\n * Permission gate — when `false` the clinical toggle is disabled and shows\n * `clinicalGatedReason` on hover/focus. Mirrors platform's\n * `practice_add_clinical_note` permission. Default `true`.\n */\n canAddClinicalNote?: boolean;\n /** Tooltip shown when the clinical toggle is gated off. */\n clinicalGatedReason?: string;\n /** Initial state of the clinical toggle. Default `false`. */\n defaultClinical?: boolean;\n\n /* ----- AI assistance (forwarded to RichTextEditor) ----- */\n onRequestAiDraft?: RichTextEditorProps['onRequestAiDraft'];\n aiDraftFormat?: RichTextEditorProps['aiDraftFormat'];\n aiPrivacyNotice?: RichTextEditorProps['aiPrivacyNotice'];\n onDictate?: RichTextEditorProps['onDictate'];\n onProofread?: RichTextEditorProps['onProofread'];\n onAutoFormat?: RichTextEditorProps['onAutoFormat'];\n /**\n * Patient AI-consent gate for Help-me-write + both mics, forwarded\n * straight to the rich composer. See `AiConsentGate`. Omit for today's\n * ungated behaviour. Ignored by the `'plain'` composer (it offers\n * neither affordance).\n */\n aiConsent?: AiConsentGate;\n /**\n * Template variables for the rich composer's \"Insert variable\" menu and\n * `[[TOKEN]]` chip rendering. Forwarded straight to `RichTextEditor`.\n * Ignored by the `'plain'` composer.\n */\n variables?: RichTextEditorProps['variables'];\n /** Decide whether a `[[TOKEN]]` is valid. See `RichTextEditor`. */\n validateVariable?: RichTextEditorProps['validateVariable'];\n /** The invalid `[[TOKEN]]`s in the draft, reported by the rich composer. */\n onVariableValidityChange?: RichTextEditorProps['onVariableValidityChange'];\n /**\n * Bring your own Help-me-write surface (e.g. practice templates) into the\n * composer, forwarded straight to `RichTextEditor`. See\n * `RichTextEditorProps['renderHelpMeWrite']`.\n */\n renderHelpMeWrite?: RichTextEditorProps['renderHelpMeWrite'];\n /** Practice templates in the composer's AI pill. See `RichTextEditor`. */\n aiTemplates?: RichTextEditorProps['aiTemplates'];\n /** After a pill action rewrote the draft (offer Undo). See `RichTextEditor`. */\n onAiApplied?: RichTextEditorProps['onAiApplied'];\n /** Upload an image yourself and resolve its URL. See `RichTextEditor`. */\n onUploadImage?: RichTextEditorProps['onUploadImage'];\n /** An AI call ran out of credits. See `RichTextEditor`. */\n onAiCreditsExhausted?: RichTextEditorProps['onAiCreditsExhausted'];\n /** Show the editor extensions affordance. See `RichTextEditor`. */\n showExtensions?: RichTextEditorProps['showExtensions'];\n extensions?: RichTextEditorProps['extensions'];\n extensionContext?: RichTextEditorProps['extensionContext'];\n onExtensionRun?: RichTextEditorProps['onExtensionRun'];\n /**\n * Shows the AI-credits/bundles hover card on every AI action trigger in\n * the composer. See `RichTextEditor`.\n */\n aiCreditsNotice?: RichTextEditorProps['aiCreditsNotice'];\n /**\n * Rendered just above the composer — e.g. the Help-me-write templates\n * pattern's `undoNotice`. Renders in both add and edit mode, whenever the\n * composer itself is mounted.\n */\n composerBefore?: ReactNode;\n /**\n * Rendered just after the composer — e.g. the Help-me-write templates\n * pattern's `manager` dialog. Renders in both add and edit mode, whenever\n * the composer itself is mounted.\n */\n composerAfter?: ReactNode;\n\n /* ----- Per-note actions ----- */\n /**\n * Pin or unpin a note; renders a pin toggle per note. Called on the click\n * with the value the note moves to. Return a promise and the panel shows\n * that value at once (a pinned note moves to the top), ignores further\n * clicks on that toggle until the promise settles and `notes` agrees, and\n * on a rejection puts the note back and shows the error's message above\n * the list. Return nothing and the change is left to your next render, as\n * before.\n */\n onTogglePin?: (id: string, next: boolean) => void | Promise<void>;\n /** As `onTogglePin`, for the flagged state (flagging does not re-order).\n * Hidden on a deleted note. */\n onToggleFlag?: (id: string, next: boolean) => void | Promise<void>;\n /**\n * Host-owned actions for each note (share, print…), rendered by the note\n * card beside its pin and flag, aligned to the inline end. The host\n * supplies labelled controls and owns what they do. Deleting belongs to\n * `onDeleteNote` and editing to `onEditNote`, which keep the panel's\n * confirm, rollback and focus. `state.deleting` is true while a delete\n * for the note is in flight: pause your controls then, as the panel\n * pauses its own.\n */\n noteActions?: (\n note: NotesPanelNote,\n state: { deleting: boolean },\n ) => ReactNode;\n /**\n * Save an edit to an existing note. When provided, each note the reader may\n * edit gets a pencil; it loads the note into the SAME composer that writes\n * new notes, in place, so a rich note is edited as rich text and keeps its\n * formatting. Return a promise to hold the pending state; a rejection keeps\n * the draft. Hidden on `actions.edit: false` and on a deleted note.\n */\n onEditNote?: (\n id: string,\n submission: NotesPanelSubmission,\n ) => void | Promise<void>;\n /**\n * Let an edit change a note's clinical flag. Default `false`: the \"Clinical\n * note\" toggle is hidden while editing and the submission carries the\n * note's existing flag. Most hosts save a note's content only, and a live\n * toggle that changes nothing is a lie. Set `true` only when the host\n * persists `submission.clinical` on edit.\n */\n editClinical?: boolean;\n /**\n * Delete a note; renders a delete button per note. Called on the click\n * that confirms it (on the delete click itself with\n * `confirmDelete={false}`), before the row fades, so the write reaches you\n * even if the panel unmounts during the fade. The row fades and stays out\n * of the list until `notes` drops it or returns it marked `deleted`. A\n * note marked `keptOnDelete` does not fade: its row stays in place, its\n * controls paused, until then. A reload that finishes (`status` from\n * `'loading'` to `'ready'`) and still lists it brings it back. Resolve\n * once the delete has landed; a rejection brings the row back and shows\n * the error's message. A synchronous return counts as landed, and the\n * row stays out: return the request's promise, and don't open your own\n * confirm in here (a cancel would still hide the note). Dropping\n * the note from `notes` in the same tick skips the fade (the rows below\n * still slide up). Hidden on `actions.delete: false` and on a deleted\n * note.\n */\n onDeleteNote?: (id: string) => void | Promise<void>;\n /**\n * Hears every refused write: a save from the composer, a delete, a pin or\n * a flag, with `shown` saying whether the panel told the reader. Report\n * the ones it did not (`shown: false`, for example when the panel\n * unmounted first) yourself, in a toast. Leave the rest to the panel, or\n * the reader hears it twice.\n */\n onWriteError?: (failure: NotesPanelWriteFailure) => void;\n /**\n * Confirm in an alert dialog before calling `onDeleteNote`. Default\n * `true`. `false` deletes on the click.\n */\n confirmDelete?: boolean;\n\n /* ----- Labels / chrome ----- */\n /** Panel heading. Defaults to the localised \"Notes\". */\n title?: string;\n /** Composer placeholder. */\n composerPlaceholder?: string;\n /** Save-button label. */\n addNoteLabel?: string;\n /** Rendered when there are no notes. */\n emptyState?: ReactNode;\n /** Accessible name for the panel region (defaults to `title`). */\n 'aria-label'?: string;\n}\n\n/* Lifts the card's content above the wash layer, so the wash tints the card\n surface only: note text and badges keep their own colours and contrast. */\nconst NOTE_CONTENT_ABOVE_WASH =\n 'ds:isolate ds:[&_[data-component=card]>*]:relative ds:[&_[data-component=card]>*]:z-[1]';\n\n/* The timeline row. The addressed row takes the keyboard focus outline; its\n visual mark is the wash layer below, so no row carries a border stripe. */\nconst noteItemVariants = cva(\n 'ds:relative ds:flex ds:flex-col ds:rounded-[var(--radius-lg)]',\n {\n variants: {\n current: {\n true: 'ds:focus:outline-[length:var(--focus-ring-width)] ds:focus:outline-solid ds:focus:outline-[color:var(--ring)] ds:focus:outline-offset-[length:var(--focus-ring-offset)]',\n false: '',\n },\n washed: { true: NOTE_CONTENT_ABOVE_WASH, false: '' },\n },\n defaultVariants: { current: false, washed: false },\n },\n);\n\n/* The accent wash on a row's card surface. `addressed` arrives, holds and\n leaves no mark; `editing` is steady for as long as the edit lasts. With\n motion off (OS setting, accessible theme) `addressed` holds steady too. */\nconst noteWashVariants = cva(\n 'ds:pointer-events-none ds:absolute ds:inset-0 ds:rounded-[var(--radius-lg)] ds:bg-[color:var(--accent)]',\n {\n variants: {\n state: {\n addressed: [\n 'ds:opacity-0',\n 'ds:animate-[note-addressed_calc(var(--animation-duration)*9)_var(--ease-in-out)]',\n 'ds:motion-reduce:animate-none ds:motion-reduce:opacity-[var(--opacity-12)]',\n 'ds:[.theme-accessible_&]:animate-none ds:[.theme-accessible_&]:opacity-[var(--opacity-12)]',\n ].join(' '),\n editing: 'ds:opacity-[var(--opacity-12)]',\n },\n },\n },\n);\n\n/* The panel root and the empty text. They take focus only from script, as\n the last place to land, so they show the kit's ring for a keyboard\n reader. */\nconst focusTargetClass = [\n 'ds:rounded-[var(--radius-lg)] ds:outline-none',\n 'ds:focus-visible:outline-[length:var(--focus-ring-width)] ds:focus-visible:outline-solid',\n 'ds:focus-visible:outline-[color:var(--ring)] ds:focus-visible:outline-offset-[length:var(--focus-ring-offset)]',\n].join(' ');\nconst rootClass = ['ds:flex ds:flex-col', focusTargetClass].join(' ');\n\n/* A row on its way out fades in place; the reflow hook then slides the\n rows below up to close the gap. Declared at rest so the transition has\n a value to animate from the moment the leaving class lands. */\nconst noteLeavingClass = 'ds:opacity-0';\nconst noteElevationClass = [\n 'ds:transition-opacity ds:duration-[var(--animation-duration)]',\n 'ds:ease-[var(--ease-out)] ds:motion-reduce:transition-none',\n].join(' ');\n\n/* Body lines per placeholder note. Uneven, so three cards do not read as one\n repeated stamp. */\nconst NOTE_SKELETON_LINES = [3, 2, 3] as const;\n\n/** Strip tags / entities to test whether a rich draft holds real content. */\nfunction hasRichContent(html: string): boolean {\n if (!html) return false;\n if (/<img\\b/i.test(html)) return true;\n return (\n html\n .replace(/<[^>]*>/g, '')\n .replace(/ /gi, ' ')\n .trim().length > 0\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* Writes at click time. Same algorithm and names as TasksPanel's */\n/* server mode (tasks-panel.tsx), so the two can share one hook later. */\n/* ------------------------------------------------------------------ */\n\ntype NoteWriteKind = 'delete' | 'pin' | 'flag';\n\n/* A write the host has been asked for and `notes` has not caught up with. */\ninterface NoteWrite {\n /** Pin and flag only: the value the toggle moved to. */\n next?: boolean;\n /** The host's promise has resolved. */\n settled: boolean;\n /** Loads finished when it resolved. */\n edgeAtSettle: number;\n /** The notes signature when it resolved. */\n sigAtSettle: string;\n}\n\n/* Up to one write of each kind per note. */\ntype NoteWrites = Partial<Record<NoteWriteKind, NoteWrite>>;\n\n/* What a click or a handle call did. `result` goes back to an agent;\n `refusal` says why the panel did not call the host. */\ninterface WriteAttempt {\n started: boolean;\n result?: void | Promise<void>;\n refusal?: string;\n}\n\n/* The refused write the Alert above the list explains. */\ninterface WriteFailure {\n kind: NotesPanelWriteFailure['kind'];\n noteId: string;\n /** The host's own words, or empty. */\n message: string;\n /** Remounts the Alert, so a repeat refusal is announced again. */\n seq: number;\n}\n\n/* Where focus was, so it can be put back near there when its row leaves. */\ninterface FocusRecord {\n el: HTMLElement;\n noteId: string | null;\n action: string | null;\n index: number;\n /** Inside the write-error Alert (its Close button). */\n inWriteError: boolean;\n}\n\n/* What the stable agent handle reaches through to, refreshed each render. */\ninterface PanelActions {\n toggle: (noteId: string, kind: 'pin' | 'flag') => WriteAttempt;\n}\n\n/* An agent hears a refusal as a rejection, so `undefined` can only mean\n the host returned nothing. */\nfunction agentToggle(\n actions: PanelActions | null,\n noteId: string,\n kind: 'pin' | 'flag',\n): void | Promise<void> {\n const attempt = actions?.toggle(noteId, kind);\n const refusal = attempt ? attempt.refusal : 'the panel is not mounted';\n return refusal === undefined\n ? attempt?.result\n : handledRejection(new Error(`NotesPanel: ${kind} refused (${refusal}).`));\n}\n\nconst EMPTY_WRITES: ReadonlyMap<string, NoteWrites> = new Map();\nconst EMPTY_HIDDEN: ReadonlySet<string> = new Set();\n\n/* One string per list state that changes when an id or a flag does. */\nfunction sigOf(notes: readonly NotesPanelNote[]): string {\n return notes\n .map(\n (n) =>\n `${n.id ?? ''}:${n.pinned ? 1 : 0}${n.flagged ? 1 : 0}${n.deleted ? 1 : 0}`,\n )\n .join('|');\n}\n\n/* A promise from any realm counts, as the composer's commit already does. */\nfunction isThenable(value: unknown): value is PromiseLike<void> {\n return (\n typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n );\n}\n\n/* A row's place among the rows a reader can still act on. A row waiting\n on its own delete sits where the next live row starts. */\nfunction liveIndexOf(\n liveIds: readonly string[],\n orderedIds: readonly string[],\n noteId: string,\n): number {\n const live = liveIds.indexOf(noteId);\n if (live >= 0) return live;\n const at = orderedIds.indexOf(noteId);\n if (at < 0) return -1;\n const liveSet = new Set(liveIds);\n return orderedIds.slice(0, at).filter((id) => liveSet.has(id)).length;\n}\n\n/* Focus an element outside the tab order, from script. It is focusable only\n while it holds focus: a lasting tabindex on the panel would take every\n mouse click on a note's text and move where Tab starts from. */\nfunction focusFromScript(el: HTMLElement): void {\n if (el.hasAttribute('tabindex')) {\n el.focus();\n return;\n }\n const release = () => el.removeAttribute('tabindex');\n el.setAttribute('tabindex', '-1');\n el.focus();\n if (document.activeElement === el) {\n el.addEventListener('blur', release, { once: true });\n } else release();\n}\n\nexport const NotesPanel = forwardRef<HTMLElement, NotesPanelProps>(\n function NotesPanel(\n {\n id,\n notes,\n onAddNote,\n status = 'ready',\n onRetry,\n currentNoteId,\n currentNoteKey,\n composer = 'rich',\n editorToolbar = 'standard',\n redactor,\n imageUploadUrl,\n showClinicalToggle = true,\n canAddClinicalNote = true,\n clinicalGatedReason,\n defaultClinical = false,\n onRequestAiDraft,\n aiDraftFormat,\n aiPrivacyNotice,\n onDictate,\n onProofread,\n onAutoFormat,\n aiConsent,\n variables,\n validateVariable,\n onVariableValidityChange,\n renderHelpMeWrite,\n aiTemplates,\n onAiApplied,\n onUploadImage,\n onAiCreditsExhausted,\n showExtensions,\n aiCreditsNotice,\n extensions,\n extensionContext,\n onExtensionRun,\n composerBefore,\n composerAfter,\n onTogglePin,\n onToggleFlag,\n noteActions,\n onEditNote,\n editClinical = false,\n onDeleteNote,\n onWriteError,\n confirmDelete = true,\n title,\n composerPlaceholder,\n addNoteLabel,\n emptyState,\n className,\n 'aria-label': ariaLabel,\n ...rest\n },\n ref,\n ) {\n const { t, i18n } = useTranslation();\n const editorRef = useRef<RichTextEditorHandle>(null);\n const [draft, setDraft] = useState('');\n const [clinical, setClinical] = useState(defaultClinical);\n const [pending, setPending] = useState(false);\n const [addError, setAddError] = useState<string | null>(null);\n // The note loaded into the composer for editing, or null when composing.\n const [editingId, setEditingId] = useState<string | null>(null);\n const editingIdRef = useRef(editingId);\n editingIdRef.current = editingId;\n /* Settle in only when this content REPLACES a skeleton. Content that was\n simply there from the start must not fade: it would read as invisible\n for one animation to any test or reader that looks at once. */\n const followedLoading = useRef(false);\n if (status === 'loading') followedLoading.current = true;\n const enterClass = followedLoading.current ? CONTENT_ENTER_CLASS : '';\n\n const heading = title ?? t('notesPanel.title', { defaultValue: 'Notes' });\n const headingId = useId();\n const placeholder =\n composerPlaceholder ??\n t('notesPanel.placeholder', { defaultValue: 'Add a note…' });\n const composerLabel =\n editingId !== null\n ? t('notesPanel.edit', { defaultValue: 'Edit note' })\n : t('notesPanel.composerLabel', { defaultValue: 'New note' });\n\n // Live content check: plain reads the draft directly; rich strips the draft\n // (debounced) for the disabled state but commits from the editor handle.\n const hasContent =\n composer === 'rich' ? hasRichContent(draft) : draft.trim().length > 0;\n\n /* ----- Writes in flight (delete, pin, flag) ----- */\n const notesRef = useRef(notes);\n notesRef.current = notes;\n const [writes, setWritesState] =\n useState<ReadonlyMap<string, NoteWrites>>(EMPTY_WRITES);\n const writesRef = useRef<ReadonlyMap<string, NoteWrites>>(EMPTY_WRITES);\n const [hidden, setHiddenState] =\n useState<ReadonlySet<string>>(EMPTY_HIDDEN);\n const hiddenRef = useRef<ReadonlySet<string>>(EMPTY_HIDDEN);\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const rootRef = useRef<HTMLElement>(null);\n const onWriteErrorRef = useRef(onWriteError);\n onWriteErrorRef.current = onWriteError;\n /* Whether a message shown now reaches the reader: not once the panel\n has unmounted, nor while a host keeps it mounted but hidden, inert\n or aria-hidden (a rail panel on its way out, say). */\n const panelShown = useCallback((): boolean => {\n const root = rootRef.current;\n if (\n !mountedRef.current ||\n !root ||\n root.closest('[hidden],[inert],[aria-hidden=\"true\"]')\n ) {\n return false;\n }\n return typeof root.checkVisibility === 'function'\n ? root.checkVisibility()\n : true;\n }, []);\n\n /* A refusal is judged after the render it causes: a host that changes\n `notes` or hides the panel in the same tick as it rejects has its\n change committed by then. `live` is false once the panel unmounts. */\n const judgementsRef = useRef<Array<(live: boolean) => void>>([]);\n const [judgeSeq, setJudgeSeq] = useState(0);\n const judgeLater = useCallback((judge: (live: boolean) => void): void => {\n if (!mountedRef.current) {\n judge(false);\n return;\n }\n judgementsRef.current.push(judge);\n setJudgeSeq((seq) => seq + 1);\n }, []);\n useEffect(() => {\n const queued = judgementsRef.current;\n judgementsRef.current = [];\n queued.forEach((judge) => judge(true));\n }, [judgeSeq]);\n useEffect(\n () => () => {\n const queued = judgementsRef.current;\n judgementsRef.current = [];\n queued.forEach((judge) => judge(false));\n },\n [],\n );\n\n // The refs are written first, so a guard read in the same tick sees the\n // change before React re-renders.\n const updatePending = (\n edit: (m: Map<string, NoteWrites>) => void,\n ): void => {\n const next = new Map(writesRef.current);\n edit(next);\n writesRef.current = next;\n setWritesState(next);\n };\n const updateHidden = (edit: (s: Set<string>) => void): void => {\n const next = new Set(hiddenRef.current);\n edit(next);\n hiddenRef.current = next;\n setHiddenState(next);\n };\n const writeOf = (\n noteId: string,\n kind: NoteWriteKind,\n ): NoteWrite | undefined => writesRef.current.get(noteId)?.[kind];\n const setWrite = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite | undefined,\n ): void =>\n updatePending((m) => {\n const entry: NoteWrites = { ...m.get(noteId) };\n if (write) entry[kind] = write;\n else delete entry[kind];\n if (Object.keys(entry).length > 0) m.set(noteId, entry);\n else m.delete(noteId);\n });\n // A note whose delete is in flight takes no second delete.\n const deleting = (noteId: string | undefined): boolean =>\n noteId != null && !!writesRef.current.get(noteId)?.delete;\n\n const commit = useCallback(() => {\n const save = editingId !== null ? onEditNote : onAddNote;\n if (!save || pending) return;\n const rich = composer === 'rich';\n const content = rich\n ? (editorRef.current?.getHTML() ?? draft)\n : draft.trim();\n if (rich ? !hasRichContent(content) : !content) return;\n const reset = () => {\n if (rich) editorRef.current?.clear();\n setDraft('');\n setClinical(defaultClinical);\n setEditingId(null);\n };\n setAddError(null);\n const edited = editingId;\n // A refused save reaches `onWriteError` too: one the panel could not\n // show has lost its draft, so the host must tell the reader. An edit\n // dropped meanwhile (its note left or was deleted) is not shown.\n const refused = (error: unknown): void =>\n judgeLater((live) => {\n const draftKept =\n live &&\n (edited === null ||\n (editingIdRef.current === edited &&\n notesRef.current.some((n) => n.id === edited && !n.deleted)));\n if (draftKept) {\n setAddError(getErrorMessage(error, t('notesPanel.addFailed')));\n }\n onWriteErrorRef.current?.({\n kind: edited !== null ? 'edit' : 'add',\n noteId: edited ?? undefined,\n error,\n shown: draftKept && panelShown(),\n });\n });\n let result: void | Promise<void>;\n try {\n result =\n editingId !== null && onEditNote\n ? onEditNote(editingId, { content, clinical })\n : onAddNote?.({ content, clinical });\n } catch (error: unknown) {\n refused(error);\n return;\n }\n if (!result || typeof result.then !== 'function') return reset();\n // A failed save keeps the draft, so nothing typed is lost.\n setPending(true);\n Promise.resolve(result)\n .then(reset, refused)\n .finally(() => setPending(false));\n }, [\n composer,\n draft,\n clinical,\n defaultClinical,\n editingId,\n judgeLater,\n onAddNote,\n onEditNote,\n panelShown,\n pending,\n t,\n ]);\n\n const clinicalToggleShown =\n showClinicalToggle && (editingId === null || editClinical);\n // The note being edited is being deleted: Save waits for the host.\n const editBlocked = editingId !== null && !!writes.get(editingId)?.delete;\n\n /* Every row carries the SAME action words, so each accessible name adds\n the note's own date: otherwise a screen reader hears a list of\n identical \"Edit note\" buttons. The tooltip keeps the short words. */\n const noteStamp = useCallback(\n (note: NotesPanelNote): string => {\n try {\n return new Intl.DateTimeFormat(i18n.language, {\n day: 'numeric',\n month: 'long',\n year: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n }).format(new Date(note.dateIso));\n } catch {\n return note.dateIso;\n }\n },\n [i18n.language],\n );\n\n /* ----- Edit in place: the composer takes the note, and gives it back ----- */\n const startEdit = useCallback(\n (note: NotesPanelNote) => {\n if (!note.id || pending) return;\n if (writesRef.current.get(note.id)?.delete) return;\n const content = note.content ?? '';\n setAddError(null);\n setEditingId(note.id);\n setClinical(note.clinical ?? false);\n setDraft(content);\n if (composer === 'rich') {\n editorRef.current?.clear();\n editorRef.current?.insertAtCursor(content, { asHtml: true });\n }\n editorRef.current?.focus();\n },\n [composer, pending],\n );\n const cancelEdit = useCallback(() => {\n if (composer === 'rich') editorRef.current?.clear();\n setDraft('');\n setClinical(defaultClinical);\n setAddError(null);\n setEditingId(null);\n }, [composer, defaultClinical]);\n // The note being edited went away (deleted, or another patient's notes\n // arrived): its draft must not be saved against whatever comes next.\n const editingStillThere =\n editingId === null ||\n notes.some((note) => note.id === editingId && !note.deleted);\n useEffect(() => {\n if (!editingStillThere) cancelEdit();\n }, [editingStillThere, cancelEdit]);\n\n /* A pin or flag in flight shows the value it moved to. */\n const effectivePinned = (note: NotesPanelNote): boolean =>\n (note.id ? writes.get(note.id)?.pin?.next : undefined) ?? !!note.pinned;\n const effectiveFlagged = (note: NotesPanelNote): boolean =>\n (note.id ? writes.get(note.id)?.flag?.next : undefined) ?? !!note.flagged;\n\n // A deleted row stays out until the host drops it or marks it deleted.\n // Pinned notes lead; order within each group is preserved.\n const ordered = notes\n .filter((note) => !note.id || !hidden.has(note.id))\n .sort((a, b) => Number(effectivePinned(b)) - Number(effectivePinned(a)));\n const orderedIds = ordered.flatMap((note) => (note.id ? [note.id] : []));\n // The rows a reader can still act on: none on its way out.\n const liveIdsRef = useRef<string[]>([]);\n liveIdsRef.current = orderedIds.filter(\n (noteId) => !writes.get(noteId)?.delete,\n );\n const orderedIdsRef = useRef<string[]>([]);\n orderedIdsRef.current = orderedIds;\n\n /* The accessible theme zeroes `--animation-duration`, so its CSS plays\n nothing — the JS must agree, or a row would sit still for the delay\n and then vanish anyway. `undefined` leaves the media query in charge. */\n const { resolvedTheme } = useTheme();\n const reduceMotion = resolvedTheme.endsWith('-accessible') || undefined;\n\n /* Closing the gap a removed row leaves: the rows below slide up rather\n than jumping, so the eye keeps its place in the list. Fires on add,\n delete, and re-order (pinning) — any change to the visible id\n sequence. */\n const { containerRef: reflowRef } = useListReflow<HTMLUListElement>({\n key: ordered.map((n) => n.id).join(),\n reduceMotion,\n });\n\n /* A deleted note fades out; once it has, it stays hidden until the host\n drops it. The reflow hook then slides the rows below up. */\n const deleteExit = useExitTransition({ reduceMotion });\n\n /* ----- Refusals and announcements ----- */\n const [writeFailure, setWriteFailure] = useState<WriteFailure | null>(null);\n const failureSeqRef = useRef(0);\n // Counts writes started. Each clears the message, so a refusal judged\n // after a newer write began would never be seen.\n const writeEpochRef = useRef(0);\n const clearForWrite = (): void => {\n writeEpochRef.current += 1;\n setWriteFailure(null);\n };\n /* Every refusal reaches `onWriteError`. The Alert shows it only while\n the reader can see the note it is about. `current` is false when a\n newer write, or a reload, has replaced the one refused. */\n const reportFailure = (\n kind: WriteFailure['kind'],\n noteId: string,\n error: unknown,\n current = true,\n ): void => {\n const epoch = writeEpochRef.current;\n judgeLater((live) => {\n const shown =\n live &&\n current &&\n epoch === writeEpochRef.current &&\n panelShown() &&\n notesRef.current.some((note) => note.id === noteId) &&\n (kind === 'delete' ||\n (!deleting(noteId) && !hiddenRef.current.has(noteId)));\n if (shown) {\n failureSeqRef.current += 1;\n setWriteFailure({\n kind,\n noteId,\n message: getErrorMessage(error, ''),\n seq: failureSeqRef.current,\n });\n }\n onWriteErrorRef.current?.({ kind, noteId, error, shown });\n });\n };\n /* Every row reads alike, so the message names its note by date, as the\n row controls do; an undated note gets the plain sentence. Literal\n keys, so the i18n coverage gate sees each one. */\n const failureTitle = (failure: WriteFailure): string => {\n const note = notes.find((n) => n.id === failure.noteId);\n const date = note?.dateIso ? noteStamp(note) : '';\n if (date) {\n switch (failure.kind) {\n case 'delete':\n return t('notesPanel.deleteFailedNamed', { date });\n case 'pin':\n return t('notesPanel.pinFailedNamed', { date });\n case 'unpin':\n return t('notesPanel.unpinFailedNamed', { date });\n case 'flag':\n return t('notesPanel.flagFailedNamed', { date });\n default:\n return t('notesPanel.unflagFailedNamed', { date });\n }\n }\n switch (failure.kind) {\n case 'delete':\n return t('notesPanel.deleteFailed');\n case 'pin':\n return t('notesPanel.pinFailed');\n case 'unpin':\n return t('notesPanel.unpinFailed');\n case 'flag':\n return t('notesPanel.flagFailed');\n default:\n return t('notesPanel.unflagFailed');\n }\n };\n // The refusal belongs to its note: it goes when the note does.\n const failureShown =\n writeFailure !== null &&\n notes.some((note) => note.id === writeFailure.noteId);\n // The last one on screen: where focus goes if it vanishes under Close.\n const shownFailureRef = useRef<WriteFailure | null>(null);\n if (writeFailure && failureShown) shownFailureRef.current = writeFailure;\n useEffect(() => {\n if (writeFailure && !failureShown) setWriteFailure(null);\n }, [writeFailure, failureShown]);\n\n // Each message renders a new text node, so a second one within the\n // second is heard too. Cleared after a second.\n const [announcement, setAnnouncement] = useState({ text: '', seq: 0 });\n const announceTimerRef = useRef<number | undefined>(undefined);\n const announce = (text: string): void => {\n setAnnouncement((prev) => ({ text, seq: prev.seq + 1 }));\n window.clearTimeout(announceTimerRef.current);\n announceTimerRef.current = window.setTimeout(\n () => setAnnouncement((prev) => ({ ...prev, text: '' })),\n 1000,\n );\n };\n useEffect(() => () => window.clearTimeout(announceTimerRef.current), []);\n const announceDeleted = (): void => announce(t('notesPanel.deleted'));\n\n /* ----- Settle, reconcile, rollback ----- */\n /* Loads finished: +1 each time `status` goes from loading to ready. A\n write that settled before a load finished can then let go. */\n const loadEdgesRef = useRef(0);\n const prevStatusRef = useRef(status);\n useEffect(() => {\n if (prevStatusRef.current === 'loading' && status === 'ready') {\n loadEdgesRef.current += 1;\n }\n prevStatusRef.current = status;\n }, [status]);\n\n /* Let go of writes the host's list has caught up with. Never keyed on\n the identity of the `notes` array. */\n const reconcile = (): void => {\n const list = notesRef.current;\n const sig = sigOf(list);\n const byId = new Map(list.map((note) => [note.id, note]));\n const dropped: Array<[string, NoteWriteKind]> = [];\n writesRef.current.forEach((entry, noteId) => {\n const note = byId.get(noteId);\n (Object.keys(entry) as NoteWriteKind[]).forEach((kind) => {\n const write = entry[kind];\n if (!write) return;\n if (!note) {\n dropped.push([noteId, kind]);\n return;\n }\n if (!write.settled) return;\n const hostAgrees =\n kind === 'delete'\n ? note.deleted === true\n : (kind === 'pin' ? !!note.pinned : !!note.flagged) ===\n write.next;\n // A delete answers to a reload or its own note, never to a change\n // in another note.\n const listMoved =\n loadEdgesRef.current > write.edgeAtSettle ||\n (kind !== 'delete' && sig !== write.sigAtSettle);\n if (hostAgrees || listMoved) dropped.push([noteId, kind]);\n });\n });\n if (dropped.length === 0) return;\n updatePending((m) =>\n dropped.forEach(([noteId, kind]) => {\n const entry: NoteWrites = { ...m.get(noteId) };\n delete entry[kind];\n if (Object.keys(entry).length > 0) m.set(noteId, entry);\n else m.delete(noteId);\n }),\n );\n const deletes = dropped\n .filter(([, kind]) => kind === 'delete')\n .map(([noteId]) => noteId);\n if (deletes.some((noteId) => hiddenRef.current.has(noteId))) {\n updateHidden((set) => deletes.forEach((noteId) => set.delete(noteId)));\n }\n // A row the host kept, or returned marked deleted, fades back in.\n deletes.forEach((noteId) => deleteExit.cancel(noteId));\n };\n\n /* Settle and rollback act only on the write their promise started. A\n newer write for the same note, started after a reload dropped this\n one, answers for itself. */\n const settle = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite,\n ): void => {\n if (writeOf(noteId, kind) !== write) return;\n setWrite(noteId, kind, {\n ...write,\n settled: true,\n edgeAtSettle: loadEdgesRef.current,\n sigAtSettle: sigOf(notesRef.current),\n });\n // A host that updated `notes` before resolving is caught here.\n reconcile();\n };\n\n /* Undo a write the host refused: the row comes back and the toggle\n reverts, because both read from `writes`. Focus stays where it is.\n Returns false when the write had already been let go. */\n const rollback = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite,\n ): boolean => {\n if (writeOf(noteId, kind) !== write) return false;\n setWrite(noteId, kind, undefined);\n if (kind !== 'delete') return true;\n if (hiddenRef.current.has(noteId)) {\n updateHidden((set) => set.delete(noteId));\n }\n deleteExit.cancel(noteId);\n return true;\n };\n\n const notesSig = useMemo(() => sigOf(notes), [notes]);\n useEffect(() => {\n reconcile();\n // `reconcile` reads refs only; the list signature is the trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [notesSig, status]);\n\n /* Pin and flag: the host is told on the click, with the value the note\n moves to. Only a returned promise is tracked; a host that returns\n nothing decides through its next render, as before. */\n const runToggle = (noteId: string, kind: 'pin' | 'flag'): WriteAttempt => {\n const handler = kind === 'pin' ? onTogglePin : onToggleFlag;\n const refuse = (refusal: string): WriteAttempt => ({\n started: false,\n refusal,\n });\n if (!handler) {\n return refuse(kind === 'pin' ? 'no onTogglePin' : 'no onToggleFlag');\n }\n const note = notesRef.current.find((n) => n.id === noteId);\n if (!note) return refuse('no note has this id');\n if (note.deleted) return refuse('the note is deleted');\n if (kind === 'pin' && note.actions?.pin === false) {\n return refuse('actions.pin is false for this note');\n }\n const entry = writesRef.current.get(noteId);\n if (entry?.delete) return refuse('the note is being deleted');\n if (entry?.[kind]) {\n return refuse(`a ${kind} write for this note is still pending`);\n }\n const next = !(kind === 'pin' ? note.pinned : note.flagged);\n const failure: WriteFailure['kind'] =\n kind === 'pin' ? (next ? 'pin' : 'unpin') : next ? 'flag' : 'unflag';\n clearForWrite();\n let result: void | Promise<void>;\n try {\n result = handler(noteId, next);\n } catch (error: unknown) {\n reportFailure(failure, noteId, error);\n return { started: false, result: handledRejection(error) };\n }\n if (!isThenable(result)) return { started: true, result };\n const write: NoteWrite = {\n next,\n settled: false,\n edgeAtSettle: 0,\n sigAtSettle: '',\n };\n setWrite(noteId, kind, write);\n const hostPromise = Promise.resolve(result);\n hostPromise.then(\n () => {\n if (mountedRef.current) settle(noteId, kind, write);\n },\n (error: unknown) => {\n const current = mountedRef.current && rollback(noteId, kind, write);\n reportFailure(failure, noteId, error, current);\n },\n );\n return { started: true, result: hostPromise };\n };\n\n /* Delete: the host is told on the (confirming) click, before the fade,\n so a panel that unmounts mid-fade loses nothing. */\n const runDelete = (noteId: string): boolean => {\n if (!onDeleteNote) return false;\n const note = notesRef.current.find((n) => n.id === noteId);\n if (!note || note.deleted || note.actions?.delete === false) {\n return false;\n }\n if (writeOf(noteId, 'delete')) return false;\n clearForWrite();\n let result: void | Promise<void>;\n try {\n result = onDeleteNote(noteId);\n } catch (error: unknown) {\n reportFailure('delete', noteId, error);\n return false;\n }\n if (isThenable(result)) {\n const write: NoteWrite = {\n settled: false,\n edgeAtSettle: 0,\n sigAtSettle: '',\n };\n setWrite(noteId, 'delete', write);\n // A kept row waits in place, marked busy, which some screen readers\n // skip: say once that it is waiting.\n if (note.keptOnDelete) {\n announce(\n note.dateIso\n ? t('notesPanel.deletingNamed', { date: noteStamp(note) })\n : t('notesPanel.deleting'),\n );\n }\n Promise.resolve(result).then(\n () => {\n if (!mountedRef.current) return;\n announceDeleted();\n settle(noteId, 'delete', write);\n },\n (error: unknown) => {\n const current =\n mountedRef.current && rollback(noteId, 'delete', write);\n reportFailure('delete', noteId, error, current);\n },\n );\n } else {\n // A synchronous return counts as landed.\n setWrite(noteId, 'delete', {\n settled: true,\n edgeAtSettle: loadEdgesRef.current,\n sigAtSettle: sigOf(notesRef.current),\n });\n announceDeleted();\n }\n // A note the host keeps holds its place, paused, until it comes back\n // marked deleted: fading it out would only bring it back.\n if (!note.keptOnDelete) {\n deleteExit.leave(noteId, () => {\n if (writeOf(noteId, 'delete')) {\n updateHidden((set) => set.add(noteId));\n }\n });\n }\n return true;\n };\n\n const [pendingDelete, setPendingDelete] = useState<string | null>(null);\n // Where focus goes once the confirm dialog closes: `started` false\n // means back to the delete that opened it.\n const deleteFocusRef = useRef<{\n noteId: string;\n index: number;\n started: boolean;\n } | null>(null);\n const handleDeleteNote = (noteId: string): void => {\n if (!onDeleteNote || deleting(noteId)) return;\n // Its edit is being saved: the delete waits, as Save waits on a delete.\n if (pending && editingId === noteId) return;\n if (!confirmDelete) {\n runDelete(noteId);\n return;\n }\n deleteFocusRef.current = { noteId, index: -1, started: false };\n setPendingDelete(noteId);\n };\n const confirmDeleteNote = (): void => {\n const noteId = pendingDelete;\n if (!noteId) return;\n const index = liveIdsRef.current.indexOf(noteId);\n if (runDelete(noteId)) {\n deleteFocusRef.current = { noteId, index, started: true };\n }\n setPendingDelete(null);\n };\n // A dialog opened for one note never confirms against another list.\n const dialogOpen =\n pendingDelete !== null &&\n notes.some((note) => note.id === pendingDelete && !note.deleted);\n useEffect(() => {\n if (pendingDelete !== null && !dialogOpen) setPendingDelete(null);\n }, [pendingDelete, dialogOpen]);\n\n /* ----- Focus: a row that leaves or moves keeps the reader's place ----- */\n useImperativeHandle(ref, () => rootRef.current as HTMLElement, []);\n\n /* A control in a note row, by action; any action when `action` is null. */\n const inRow = (\n noteId: string | null | undefined,\n action: string | null,\n ): HTMLElement | null =>\n noteId\n ? (rootRef.current?.querySelector<HTMLElement>(\n `[data-note-id=\"${CSS.escape(noteId)}\"] ${\n action\n ? `[data-note-action=\"${CSS.escape(action)}\"]`\n : '[data-note-action]'\n }`,\n ) ?? null)\n : null;\n /* Where focus lands when a row leaves: the same action in the row now\n at `index`, else in the row above, else any action in those rows.\n Rows on their way out do not count. */\n const nearTarget = (\n index: number,\n action: string | null,\n ): HTMLElement | null => {\n const ids = liveIdsRef.current;\n return (\n inRow(ids[index], action) ??\n inRow(ids[index - 1], action) ??\n inRow(ids[index], null) ??\n inRow(ids[index - 1], null)\n );\n };\n /* No note control left: the empty text, else the panel itself. */\n const landLast = (): void => {\n const root = rootRef.current;\n const last =\n root?.querySelector<HTMLElement>('[data-notes-panel-empty]') ?? root;\n if (last) focusFromScript(last);\n };\n const landNear = (target: HTMLElement | null): void => {\n if (target) target.focus();\n else landLast();\n };\n\n /* Radix returns focus only to a Dialog.Trigger, and this dialog has\n none. A cancel goes back to the delete that opened it. A confirmed\n delete lands once, where the reader will end up: the next note's\n delete. While the last note fades, focus waits on its delete and the\n rescue below moves it to the empty text once the row goes. */\n const handleDialogCloseFocus = (event: Event): void => {\n const record = deleteFocusRef.current;\n deleteFocusRef.current = null;\n if (!record) return;\n event.preventDefault();\n const trigger = inRow(record.noteId, 'delete');\n landNear(\n record.started\n ? (nearTarget(record.index, 'delete') ?? trigger)\n : trigger,\n );\n };\n\n /* Dismissing the error unmounts the focused Close button. Hand focus to\n the control whose write was refused, as WarningStack hands it on,\n unless the reader has already moved it. */\n const writeErrorRef = useRef<HTMLDivElement>(null);\n const failureTarget = (failure: WriteFailure): HTMLElement | null => {\n const action =\n failure.kind === 'delete'\n ? 'delete'\n : failure.kind.endsWith('pin')\n ? 'pin'\n : 'flag';\n const index = liveIdsRef.current.indexOf(failure.noteId);\n return (\n inRow(failure.noteId, action) ??\n inRow(failure.noteId, null) ??\n (index >= 0 ? nearTarget(index, action) : null)\n );\n };\n const dismissWriteFailure = (failure: WriteFailure): void => {\n if (writeErrorRef.current?.contains(document.activeElement)) {\n landNear(failureTarget(failure));\n }\n setWriteFailure(null);\n };\n\n /* The row with focus left without the dialog (confirmDelete off, or the\n host dropped it): put focus on the same control in the row that took\n its place. Mirrors tasks-panel.tsx. */\n const focusRef = useRef<FocusRecord | null>(null);\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return undefined;\n const onFocusIn = (event: FocusEvent) => {\n const el = event.target;\n if (!(el instanceof HTMLElement)) return;\n const noteId =\n el.closest<HTMLElement>('[data-note-id]')?.dataset.noteId ?? null;\n focusRef.current = {\n el,\n noteId,\n action:\n el.closest<HTMLElement>('[data-note-action]')?.dataset.noteAction ??\n null,\n index: noteId\n ? liveIndexOf(liveIdsRef.current, orderedIdsRef.current, noteId)\n : -1,\n inWriteError: !!el.closest('[data-notes-panel-write-error]'),\n };\n };\n const onFocusOut = (event: FocusEvent) => {\n const to = event.relatedTarget;\n if (to instanceof Node) {\n if (!root.contains(to)) focusRef.current = null;\n return;\n }\n // No target: a click on empty space, or the row being removed. Decide\n // after the render: a removed row is rescued by then, and one still\n // here but unfocused was left by the user.\n const from = event.target;\n queueMicrotask(() => {\n const record = focusRef.current;\n if (\n record &&\n record.el === from &&\n record.el.isConnected &&\n document.activeElement !== record.el\n ) {\n focusRef.current = null;\n }\n });\n };\n root.addEventListener('focusin', onFocusIn);\n root.addEventListener('focusout', onFocusOut);\n return () => {\n root.removeEventListener('focusin', onFocusIn);\n root.removeEventListener('focusout', onFocusOut);\n };\n }, []);\n\n /* React puts focus back on a row it only moved (a re-sort), so only a\n control that left needs rescuing. Runs after every render, as a row\n can lose its controls without moving (the host marks it deleted). */\n useIsomorphicLayoutEffect(() => {\n const record = focusRef.current;\n if (!record || !rootRef.current) return;\n if (record.el.isConnected) {\n // Keep the position current while the row is still listed.\n const live = record.noteId\n ? liveIndexOf(\n liveIdsRef.current,\n orderedIdsRef.current,\n record.noteId,\n )\n : -1;\n if (live >= 0) record.index = live;\n return;\n }\n focusRef.current = null;\n const active = document.activeElement;\n if (active && active !== document.body) return;\n const moved = record.action ? inRow(record.noteId, record.action) : null;\n if (moved) moved.focus();\n else if (record.noteId) {\n landNear(nearTarget(record.index, record.action));\n } else if (record.el.hasAttribute('data-notes-panel-empty')) {\n // A note came back where the empty text held focus: a refused\n // delete, or a record the host kept.\n landNear(nearTarget(0, 'delete'));\n } else if (record.inWriteError) {\n // The error went from under its Close button without a dismiss: a\n // newer refusal replaced it, a write cleared it, or its note left.\n const close = writeErrorRef.current?.querySelector<HTMLElement>(\n '[data-alert-dismiss]',\n );\n const failure = shownFailureRef.current;\n if (close) close.focus();\n else landNear(failure ? failureTarget(failure) : null);\n }\n });\n\n /* ----- The addressed note (see `currentNoteId`) ----- */\n const currentItemRef = useRef<HTMLLIElement>(null);\n useEffect(() => {\n if (!currentNoteId) return;\n // `center`, not `nearest`: nearest parks the note flush against the edge\n // of the scroll region, which is the least readable place to land.\n currentItemRef.current?.scrollIntoView({ block: 'center' });\n currentItemRef.current?.focus();\n // `currentNoteKey` is in the deps so a REPEAT address of the same note\n // re-runs — see the prop doc. Addressing is a request, not a value.\n }, [currentNoteId, currentNoteKey]);\n\n /* ----- Agent handle (structural reads + composer / toggles) ----- */\n /* Stable for the life of the panel: everything is read through refs, so\n a registered handle never goes stale and never re-registers. */\n const onAddNoteRef = useRef(onAddNote);\n onAddNoteRef.current = onAddNote;\n const canAddClinicalRef = useRef(canAddClinicalNote);\n canAddClinicalRef.current = canAddClinicalNote;\n const currentNoteIdRef = useRef(currentNoteId);\n currentNoteIdRef.current = currentNoteId;\n const actionsRef = useRef<PanelActions | null>(null);\n actionsRef.current = { toggle: runToggle };\n\n const handle = useMemo<NotesPanelHandle>(\n () => ({\n // Ids + flags only — never the note body or author (both PHI).\n getNotes: () =>\n notesRef.current\n .filter((n) => !(n.id && writesRef.current.get(n.id)?.delete))\n .map((n) => {\n const entry = n.id ? writesRef.current.get(n.id) : undefined;\n return {\n id: n.id,\n pinned: entry?.pin?.next ?? !!n.pinned,\n flagged: entry?.flag?.next ?? !!n.flagged,\n clinical: !!n.clinical,\n deleted: !!n.deleted,\n };\n }),\n canAddNote: () => !!onAddNoteRef.current,\n canAddClinical: () => canAddClinicalRef.current,\n getCurrentNoteId: () => currentNoteIdRef.current ?? null,\n addNote: (submission) => {\n // A clinical submission requires the permission gate to be open.\n if (submission.clinical && !canAddClinicalRef.current) return;\n return onAddNoteRef.current?.(submission);\n },\n togglePin: (noteId) => agentToggle(actionsRef.current, noteId, 'pin'),\n toggleFlag: (noteId) => agentToggle(actionsRef.current, noteId, 'flag'),\n }),\n [],\n );\n useAgentRegistration(notesPanelAgent, handle, id);\n\n return (\n <section\n ref={rootRef}\n data-component=\"notes-panel\"\n data-component-id={id}\n aria-labelledby={ariaLabel ? undefined : headingId}\n aria-label={ariaLabel}\n className={[rootClass, className].filter(Boolean).join(' ')}\n {...rest}\n >\n {/* Shared rail header — pins to the top of the panel's scroll region\n while the composer + note timeline scroll beneath it. The rail\n injects the favourite / close actions via PanelHeaderActionsProvider. */}\n <PanelHeader\n title={heading}\n icon={<NotebookPen aria-hidden=\"true\" />}\n headingId={ariaLabel ? undefined : headingId}\n sticky\n divider\n />\n\n <div className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-md)] ds:p-[var(--spacing-md)]\">\n {onAddNote || editingId !== null ? (\n <div\n data-notes-panel-composer={editingId !== null ? 'edit' : 'add'}\n className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\"\n >\n {composerBefore}\n {composer === 'rich' ? (\n <RichTextEditor\n ref={editorRef}\n ariaLabel={composerLabel}\n placeholder={placeholder}\n toolbar={editorToolbar}\n minHeight=\"fill\"\n redactor={redactor}\n imageUploadUrl={imageUploadUrl}\n readOnly={pending}\n onChange={({ html }) => setDraft(html)}\n onRequestAiDraft={onRequestAiDraft}\n aiDraftFormat={aiDraftFormat}\n aiPrivacyNotice={aiPrivacyNotice}\n onDictate={onDictate}\n onProofread={onProofread}\n onAutoFormat={onAutoFormat}\n aiConsent={aiConsent}\n variables={variables}\n validateVariable={validateVariable}\n onVariableValidityChange={onVariableValidityChange}\n renderHelpMeWrite={renderHelpMeWrite}\n aiTemplates={aiTemplates}\n onAiApplied={onAiApplied}\n onUploadImage={onUploadImage}\n onAiCreditsExhausted={onAiCreditsExhausted}\n showExtensions={showExtensions}\n aiCreditsNotice={aiCreditsNotice}\n extensions={extensions}\n extensionContext={extensionContext}\n onExtensionRun={onExtensionRun}\n // The panel's own title is an h2 (PanelHeader below); the\n // gate's banner nests one level under it so the h2 → h3\n // sequence stays valid (axe heading-order) instead of\n // jumping straight to the banner's own h5 default.\n aiConsentHeadingLevel={3}\n />\n ) : (\n <TextArea\n value={draft}\n readOnly={pending}\n onChange={(event) => setDraft(event.target.value)}\n placeholder={placeholder}\n autoResize\n minRows={2}\n maxRows={6}\n aria-label={composerLabel}\n />\n )}\n <div\n className={[\n 'ds:flex ds:flex-wrap ds:items-center ds:gap-[var(--spacing-sm)]',\n clinicalToggleShown ? 'ds:justify-between' : 'ds:justify-end',\n ].join(' ')}\n >\n {clinicalToggleShown\n ? (() => {\n const clinicalDisabled = pending || !canAddClinicalNote;\n const clinicalReason = canAddClinicalNote\n ? undefined\n : (clinicalGatedReason ??\n t('notesPanel.clinicalGated', {\n defaultValue:\n 'You do not have permission to write clinical notes.',\n }));\n const clinicalSwitch = (\n <Switch\n size=\"sm\"\n label={t('notesPanel.clinicalToggle', {\n defaultValue: 'Clinical note',\n })}\n checked={clinical}\n onCheckedChange={setClinical}\n disabled={clinicalDisabled}\n />\n );\n // A disabled Radix Switch renders a native `disabled`\n // button, which drops out of the tab order — Tooltip\n // alone would leave the reason unreachable by keyboard.\n // The focusable wrapping span is the kit's documented\n // workaround (see tooltip.mdx / tooltip.stories.tsx).\n return clinicalDisabled && clinicalReason ? (\n <Tooltip label={clinicalReason}>\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper so Tooltip works around the disabled Switch (which can't receive focus or hover events) */}\n <span tabIndex={0}>{clinicalSwitch}</span>\n </Tooltip>\n ) : (\n clinicalSwitch\n );\n })()\n : null}\n <span className=\"ds:flex ds:items-center ds:gap-[var(--spacing-xs)]\">\n {editingId !== null ? (\n <Button\n type=\"button\"\n size=\"sm\"\n intent=\"ghost\"\n onClick={cancelEdit}\n disabled={pending}\n >\n {t('notesPanel.cancelEdit', { defaultValue: 'Cancel' })}\n </Button>\n ) : null}\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={commit}\n disabled={!hasContent || editBlocked}\n loading={pending}\n >\n {editingId !== null\n ? t('notesPanel.saveEdit', { defaultValue: 'Save note' })\n : (addNoteLabel ??\n t('notesPanel.add', { defaultValue: 'Add note' }))}\n </Button>\n </span>\n </div>\n {addError ? (\n <Alert variant=\"error\">\n <Alert.Description>{addError}</Alert.Description>\n </Alert>\n ) : null}\n {composerAfter}\n </div>\n ) : null}\n\n {status === 'loading' && ordered.length === 0 ? (\n /* Note-shaped placeholders, not a spinner: the reader sees where\n the notes will land and how many to expect. The status text is\n for assistive tech only; sighted readers get the motion. */\n <div\n data-notes-panel-loading=\"\"\n aria-busy=\"true\"\n className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\"\n >\n <span role=\"status\" className=\"ds:sr-only\">\n {t('notesPanel.loading')}\n </span>\n {NOTE_SKELETON_LINES.map((lines, index) => (\n <Card key={index} variant=\"elevated\" aria-hidden=\"true\">\n <Card.Body>\n <div className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\">\n <div className=\"ds:flex ds:items-center ds:gap-[var(--spacing-sm)]\">\n <Skeleton\n variant=\"circular\"\n size=\"sm\"\n stagger={index * 2}\n />\n <div className=\"ds:flex ds:flex-1 ds:flex-col ds:gap-[var(--spacing-xs)]\">\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n stagger={index * 2}\n width=\"40%\"\n />\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n stagger={index * 2}\n width=\"25%\"\n />\n </div>\n </div>\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n lines={lines}\n stagger={index * 2 + 1}\n />\n </div>\n </Card.Body>\n </Card>\n ))}\n </div>\n ) : status === 'error' ? (\n <Alert variant=\"error\">\n <Alert.Description>{t('notesPanel.loadError')}</Alert.Description>\n {onRetry ? (\n <Alert.Action>\n <Button intent=\"secondary\" size=\"sm\" onClick={onRetry}>\n {t('notesPanel.retry')}\n </Button>\n </Alert.Action>\n ) : null}\n </Alert>\n ) : null}\n\n {/* A refused delete, pin or flag, explained just above the list. */}\n {writeFailure && failureShown ? (\n <Alert\n key={writeFailure.seq}\n ref={writeErrorRef}\n variant=\"error\"\n dismissible\n onOpenChange={(open) => {\n if (!open) dismissWriteFailure(writeFailure);\n }}\n data-notes-panel-write-error={writeFailure.kind}\n >\n <Alert.Title as=\"p\">{failureTitle(writeFailure)}</Alert.Title>\n {writeFailure.message ? (\n <Alert.Description>{writeFailure.message}</Alert.Description>\n ) : null}\n </Alert>\n ) : null}\n {/* Always mounted, so a landed delete is heard. No role: hosts that\n query the panel's one status line keep finding it. */}\n <span\n aria-live=\"polite\"\n aria-atomic=\"true\"\n data-notes-panel-announcer=\"\"\n className=\"ds:sr-only\"\n >\n {announcement.text ? (\n <span key={announcement.seq}>{announcement.text}</span>\n ) : null}\n </span>\n\n {/* A refresh keeps the notes it has: real notes never give way to\n placeholders. The list is marked busy and says so to a reader. */}\n {status === 'loading' && ordered.length > 0 ? (\n <span role=\"status\" className=\"ds:sr-only\">\n {t('notesPanel.loading')}\n </span>\n ) : null}\n {ordered.length > 0 ? (\n <ul\n ref={reflowRef}\n aria-busy={status === 'loading' || undefined}\n className={`ds:m-0 ds:flex ds:list-none ds:flex-col ds:gap-[var(--spacing-sm)] ds:p-0 ${enterClass}`.trim()}\n >\n {ordered.map(({ actions, keptOnDelete, ...note }, index) => {\n const isCurrent =\n currentNoteId != null && note.id === currentNoteId;\n const noteId = note.id as string | undefined;\n const isEditing = noteId != null && editingId === noteId;\n const leaving = noteId != null && deleteExit.isLeaving(noteId);\n const write = noteId ? writes.get(noteId) : undefined;\n const inert = !!write?.delete;\n // A kept note waits in place for the host, and says so.\n const holding = inert && !!keptOnDelete;\n const editSaving = pending && isEditing;\n return (\n <li\n key={note.id ?? index}\n ref={isCurrent ? currentItemRef : undefined}\n data-note-id={noteId}\n // Focus lands on the row, not inside the card, so the\n // sentence below and `aria-current` are read out before the\n // note — and the rail's own Escape still bubbles.\n tabIndex={isCurrent ? -1 : undefined}\n aria-current={isCurrent ? 'true' : undefined}\n data-reflow-id={noteId}\n data-leaving={leaving ? '' : undefined}\n data-editing={isEditing ? '' : undefined}\n aria-busy={holding || undefined}\n className={[\n noteItemVariants({\n current: isCurrent,\n washed: isCurrent || isEditing,\n }),\n noteElevationClass,\n REFLOW_ROW_CLASS,\n leaving ? noteLeavingClass : '',\n ]\n .filter(Boolean)\n .join(' ')}\n >\n {isCurrent ? (\n <span className=\"ds:sr-only\">\n {t('notesPanel.current', {\n defaultValue: 'Current note',\n })}\n </span>\n ) : null}\n {/* aria-busy is not read out as a state, so a waiting\n row says it in words too. */}\n {holding ? (\n <span data-notes-panel-deleting=\"\" className=\"ds:sr-only\">\n {t('notesPanel.deleting')}\n </span>\n ) : null}\n {/* Elevated card per note; the list gap (not a separator)\n spaces them. Bodies clamp to five lines with read-more —\n except the addressed one, which is what the reader came\n for and opens in full. */}\n {/* Keyed on the address, so a repeat address of the same\n note remounts the layer and the wash plays again. Editing\n wins: a steady state must not pulse. */}\n {isEditing ? (\n <span\n aria-hidden=\"true\"\n data-notes-panel-wash=\"editing\"\n className={noteWashVariants({ state: 'editing' })}\n />\n ) : isCurrent ? (\n <span\n key={`${currentNoteId}:${currentNoteKey ?? ''}`}\n aria-hidden=\"true\"\n data-notes-panel-wash=\"addressed\"\n className={noteWashVariants({ state: 'addressed' })}\n />\n ) : null}\n <ClinicalNoteCard\n surface=\"elevated\"\n truncate={!isCurrent}\n headerActions={\n <>\n {noteActions\n ? noteActions(\n { ...note, actions, keptOnDelete },\n { deleting: inert },\n )\n : null}\n {onEditNote &&\n noteId &&\n !note.deleted &&\n actions?.edit !== false ? (\n <IconButton\n icon={<Pencil />}\n intent=\"ghost\"\n size=\"sm\"\n aria-label={t('notesPanel.editNamed', {\n date: noteStamp(note),\n defaultValue: 'Edit note · {{date}}',\n })}\n tooltip={t('notesPanel.edit', {\n defaultValue: 'Edit note',\n })}\n aria-pressed={editingId === noteId}\n disabled={pending || inert}\n data-notes-panel-edit=\"\"\n data-note-action=\"edit\"\n onClick={() =>\n editingId === noteId\n ? cancelEdit()\n : startEdit(note)\n }\n />\n ) : null}\n {onDeleteNote &&\n noteId &&\n !note.deleted &&\n actions?.delete !== false ? (\n <IconButton\n icon={<Trash2 />}\n intent=\"ghost\"\n size=\"sm\"\n aria-label={t('notesPanel.deleteNamed', {\n date: noteStamp(note),\n defaultValue: 'Delete note · {{date}}',\n })}\n tooltip={t('notesPanel.delete', {\n defaultValue: 'Delete note',\n })}\n data-note-action=\"delete\"\n // aria-disabled, not disabled: focus can wait\n // here while the host answers.\n aria-disabled={holding || editSaving || undefined}\n aria-busy={holding || undefined}\n onClick={() => handleDeleteNote(noteId)}\n />\n ) : null}\n </>\n }\n {...note}\n pinned={effectivePinned(note)}\n flagged={effectiveFlagged(note)}\n pinPending={!!write?.pin || inert}\n flagPending={!!write?.flag || inert}\n onTogglePin={\n onTogglePin &&\n noteId &&\n actions?.pin !== false &&\n !note.deleted\n ? () => runToggle(noteId, 'pin')\n : undefined\n }\n onToggleFlag={\n onToggleFlag && noteId && !note.deleted\n ? () => runToggle(noteId, 'flag')\n : undefined\n }\n />\n </li>\n );\n })}\n </ul>\n ) : status !== 'ready' ? null : (\n /* Where focus lands, from script, when the last note leaves. */\n <div data-notes-panel-empty=\"\" className={focusTargetClass}>\n {emptyState ?? (\n <p className=\"ds:m-0 type-body-sm ds:text-[color:var(--muted-foreground)]\">\n {t('notesPanel.empty', { defaultValue: 'No notes yet.' })}\n </p>\n )}\n </div>\n )}\n </div>\n\n {onDeleteNote && confirmDelete ? (\n <Dialog\n open={dialogOpen}\n onOpenChange={(next) => !next && setPendingDelete(null)}\n >\n <Dialog.Content\n variant=\"alert\"\n size=\"sm\"\n onCloseAutoFocus={handleDialogCloseFocus}\n >\n <Dialog.Header>\n <Dialog.Title>\n {t('notesPanel.deleteConfirmTitle', {\n defaultValue: 'Delete this note?',\n })}\n </Dialog.Title>\n </Dialog.Header>\n <Dialog.Body>\n <Dialog.Description>\n {t('notesPanel.deleteConfirmBody', {\n defaultValue: 'The note will be removed from the record.',\n })}\n </Dialog.Description>\n </Dialog.Body>\n <Dialog.Footer>\n <Dialog.Close asChild>\n <Button\n intent=\"secondary\"\n size=\"sm\"\n onClick={() => setPendingDelete(null)}\n >\n {t('notesPanel.deleteConfirmCancel', {\n defaultValue: 'Cancel',\n })}\n </Button>\n </Dialog.Close>\n <Button\n intent=\"destructive\"\n size=\"sm\"\n onClick={confirmDeleteNote}\n >\n {t('notesPanel.deleteConfirmAction', {\n defaultValue: 'Delete',\n })}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n </Dialog>\n ) : null}\n </section>\n );\n },\n);\n"],"names":["notesPanelAgent","handle","args","NOTE_CONTENT_ABOVE_WASH","noteItemVariants","cva","noteWashVariants","focusTargetClass","rootClass","noteLeavingClass","noteElevationClass","NOTE_SKELETON_LINES","hasRichContent","html","agentToggle","actions","noteId","kind","attempt","refusal","handledRejection","EMPTY_WRITES","EMPTY_HIDDEN","sigOf","notes","n","isThenable","value","liveIndexOf","liveIds","orderedIds","live","at","liveSet","id","focusFromScript","el","release","NotesPanel","forwardRef","onAddNote","status","onRetry","currentNoteId","currentNoteKey","composer","editorToolbar","redactor","imageUploadUrl","showClinicalToggle","canAddClinicalNote","clinicalGatedReason","defaultClinical","onRequestAiDraft","aiDraftFormat","aiPrivacyNotice","onDictate","onProofread","onAutoFormat","aiConsent","variables","validateVariable","onVariableValidityChange","renderHelpMeWrite","aiTemplates","onAiApplied","onUploadImage","onAiCreditsExhausted","showExtensions","aiCreditsNotice","extensions","extensionContext","onExtensionRun","composerBefore","composerAfter","onTogglePin","onToggleFlag","noteActions","onEditNote","editClinical","onDeleteNote","onWriteError","confirmDelete","title","composerPlaceholder","addNoteLabel","emptyState","className","ariaLabel","rest","ref","t","i18n","useTranslation","editorRef","useRef","draft","setDraft","useState","clinical","setClinical","pending","setPending","addError","setAddError","editingId","setEditingId","editingIdRef","followedLoading","enterClass","CONTENT_ENTER_CLASS","heading","headingId","useId","placeholder","composerLabel","hasContent","notesRef","writes","setWritesState","writesRef","hidden","setHiddenState","hiddenRef","mountedRef","useEffect","rootRef","onWriteErrorRef","panelShown","useCallback","root","judgementsRef","judgeSeq","setJudgeSeq","judgeLater","judge","seq","queued","updatePending","edit","next","updateHidden","writeOf","_a","setWrite","write","m","entry","deleting","commit","rich","content","reset","edited","refused","error","draftKept","getErrorMessage","result","clinicalToggleShown","editBlocked","noteStamp","note","startEdit","_b","_c","_d","cancelEdit","editingStillThere","effectivePinned","effectiveFlagged","ordered","a","b","liveIdsRef","orderedIdsRef","resolvedTheme","useTheme","reduceMotion","reflowRef","useListReflow","deleteExit","useExitTransition","writeFailure","setWriteFailure","failureSeqRef","writeEpochRef","clearForWrite","reportFailure","current","epoch","shown","failureTitle","failure","date","failureShown","shownFailureRef","announcement","setAnnouncement","announceTimerRef","announce","text","prev","announceDeleted","loadEdgesRef","prevStatusRef","reconcile","list","sig","byId","dropped","hostAgrees","listMoved","deletes","set","settle","rollback","notesSig","useMemo","runToggle","handler","refuse","hostPromise","runDelete","pendingDelete","setPendingDelete","deleteFocusRef","handleDeleteNote","confirmDeleteNote","index","dialogOpen","useImperativeHandle","inRow","action","nearTarget","ids","landLast","last","landNear","target","handleDialogCloseFocus","event","record","trigger","writeErrorRef","failureTarget","dismissWriteFailure","focusRef","onFocusIn","onFocusOut","to","from","useIsomorphicLayoutEffect","active","moved","close","currentItemRef","onAddNoteRef","canAddClinicalRef","currentNoteIdRef","actionsRef","submission","useAgentRegistration","jsxs","jsx","PanelHeader","NotebookPen","RichTextEditor","TextArea","clinicalDisabled","clinicalReason","clinicalSwitch","Switch","Tooltip","Button","Alert","lines","Card","Skeleton","open","keptOnDelete","isCurrent","isEditing","leaving","inert","holding","editSaving","REFLOW_ROW_CLASS","ClinicalNoteCard","Fragment","IconButton","Pencil","Trash2","Dialog"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBO,MAAMA,KAAkD;AAAA,EAC7D,IAAI;AAAA;AAAA;AAAA,EAGJ,cAAc,CAAC,QAAQ;AAAA,EACvB,OAAO;AAAA,IACL,OAAO;AAAA,MACL,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACC,MAAWA,EAAO,SAAA;AAAA,IAAS;AAAA,IAEpC,gBAAgB;AAAA,MACd,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACA,MAAWA,EAAO,eAAA;AAAA,IAAe;AAAA,IAE1C,eAAe;AAAA,MACb,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACA,MAAWA,EAAO,iBAAA;AAAA,IAAiB;AAAA,EAC5C;AAAA,EAEF,SAAS;AAAA,IACP,UAAU;AAAA;AAAA,MAER,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,YAAY;AAAA,QACV,MAAM;AAAA,QACN,YAAY;AAAA,UACV,SAAS;AAAA,YACP,MAAM;AAAA,YACN,aACE;AAAA,UAAA;AAAA,UAEJ,UAAU;AAAA,YACR,MAAM;AAAA,YACN,aACE;AAAA,UAAA;AAAA,QACJ;AAAA,QAE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R,MAAK;AAAA,kBACL,kBAAkBrD;AAAA,kBAElB,UAAA;AAAA,oBAAA,gBAAAwB,EAAC6B,EAAO,QAAP,EACC,UAAA,gBAAA7B,EAAC6B,EAAO,OAAP,EACE,YAAE,iCAAiC;AAAA,sBAClC,cAAc;AAAA,oBAAA,CACf,GACH,EAAA,CACF;AAAA,oBACA,gBAAA7B,EAAC6B,EAAO,MAAP,EACC,4BAACA,EAAO,aAAP,EACE,UAAA1M,EAAE,gCAAgC;AAAA,sBACjC,cAAc;AAAA,oBAAA,CACf,GACH,EAAA,CACF;AAAA,oBACA,gBAAA4K,EAAC8B,EAAO,QAAP,EACC,UAAA;AAAA,sBAAA,gBAAA7B,EAAC6B,EAAO,OAAP,EAAa,SAAO,IACnB,UAAA,gBAAA7B;AAAA,wBAACU;AAAA,wBAAA;AAAA,0BACC,QAAO;AAAA,0BACP,MAAK;AAAA,0BACL,SAAS,MAAMjD,EAAiB,IAAI;AAAA,0BAEnC,YAAE,kCAAkC;AAAA,4BACnC,cAAc;AAAA,0BAAA,CACf;AAAA,wBAAA;AAAA,sBAAA,GAEL;AAAA,sBACA,gBAAAuC;AAAA,wBAACU;AAAA,wBAAA;AAAA,0BACC,QAAO;AAAA,0BACP,MAAK;AAAA,0BACL,SAAS9C;AAAA,0BAER,YAAE,kCAAkC;AAAA,4BACnC,cAAc;AAAA,0BAAA,CACf;AAAA,wBAAA;AAAA,sBAAA;AAAA,oBACH,EAAA,CACF;AAAA,kBAAA;AAAA,gBAAA;AAAA,cAAA;AAAA,YACF;AAAA,UAAA,IAEA;AAAA,QAAA;AAAA,MAAA;AAAA,IAAA;AAAA,EAGV;AACF;"}
|
|
1
|
+
{"version":3,"file":"notes-panel-xxpFt-I1.js","sources":["../../src/components/notes-panel/notes-panel.agent.ts","../../src/components/notes-panel/notes-panel.tsx"],"sourcesContent":["/* -------------------------------------------------------------------- */\n/* Agent adapter — NotesPanel. */\n/* */\n/* The Notes tool: a composer over a note timeline. The agent reads the */\n/* timeline STRUCTURE (note ids + pinned / flagged / clinical / deleted */\n/* flags, never the note body or author, both PHI), composes and commits */\n/* a new note, and toggles a note's pinned / flagged state. The toggles */\n/* return the host's promise: a refusal rejects, and the panel restores */\n/* the note and explains it. A toggle the panel refuses (deleted note, */\n/* gate, write still pending) rejects too, without reaching the host. */\n/* `add_note` carries the `phi` safety class: a note body is */\n/* patient-identifiable clinical content, so the host gates it behind the */\n/* same confirm-before-act as a destructive write and never auto-confirms.*/\n/* A clinical submission also requires the host's */\n/* `practice_add_clinical_note` permission (the handle drops it when the */\n/* gate is closed). Delete stays a panel control */\n/* the reader confirms, not an agent action. Host-owned per-note */\n/* `noteActions` sit outside this handle: an agent reaches them through */\n/* the host's own adapters. */\n/* -------------------------------------------------------------------- */\n\nimport type { AgentAdapter } from '../../agent/types';\nimport type { NotesPanelHandle } from './notes-panel';\n\nexport const notesPanelAgent: AgentAdapter<NotesPanelHandle> = {\n id: 'notes-panel',\n // 'submit' backs add_note (compose + commit a note). pin / flag are toggles\n // with no dedicated capability in the closed vocabulary.\n capabilities: ['submit'],\n state: {\n notes: {\n type: 'Array<{ id?: string; pinned: boolean; flagged: boolean; clinical: boolean; deleted: boolean }>',\n descriptionKey: 'ui.agent.notesPanel.state.notes',\n description:\n 'Timeline note ids + pinned / flagged / clinical / deleted flags. Never the note body or author (both PHI). A note whose delete is in flight is left out; a pin or flag in flight is reported with its new value. A deleted note takes no pin or flag.',\n read: (handle) => handle.getNotes(),\n },\n canAddClinical: {\n type: 'boolean',\n descriptionKey: 'ui.agent.notesPanel.state.canAddClinical',\n description:\n 'Whether the current user may write clinical notes (the practice_add_clinical_note permission gate).',\n read: (handle) => handle.canAddClinical(),\n },\n currentNoteId: {\n type: 'string | null',\n descriptionKey: 'ui.agent.notesPanel.state.currentNoteId',\n description:\n 'Id of the note the host has addressed — the one marked, scrolled to and focused. Null when none is. An id only, never note content.',\n read: (handle) => handle.getCurrentNoteId(),\n },\n },\n actions: {\n add_note: {\n // Writes a clinical/admin note body — patient-identifiable content. PHI.\n safety: 'phi',\n argsType: '{ content: string; clinical: boolean }',\n argsSchema: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description:\n 'Note body. Rich HTML for the rich composer, else plain text.',\n },\n clinical: {\n type: 'boolean',\n description:\n 'Whether the note is clinical. Requires the clinical-note permission; the submission is dropped when the gate is closed.',\n },\n },\n required: ['content', 'clinical'],\n },\n openWorld: true,\n descriptionKey: 'ui.agent.notesPanel.actions.addNote',\n description:\n 'Compose and commit a new note. A clinical note requires the clinical-note permission (read canAddClinical first).',\n examples: [\n {\n args: { content: 'Patient reported improvement.', clinical: true },\n note: 'Add a clinical note.',\n },\n ],\n invoke: (handle, args: { content: string; clinical: boolean }) => {\n return handle.addNote(args);\n },\n },\n toggle_pin: {\n // A host write; it re-orders the timeline (pinned notes lead).\n safety: 'write',\n argsType: '{ id: string }',\n argsSchema: {\n type: 'object',\n properties: { id: { type: 'string' } },\n required: ['id'],\n },\n idempotent: false,\n // Reaches the host's data source; the result is the host's promise.\n openWorld: true,\n errors: [\n 'The panel offers no pin here: no onTogglePin, no note with this id, a deleted note, or actions.pin is false.',\n 'A pin or delete for this note is still pending. Read notes again once it has settled.',\n \"The host refused the change. The pin is restored and the panel shows the host's message.\",\n ],\n descriptionKey: 'ui.agent.notesPanel.actions.togglePin',\n description:\n \"Toggle the pinned state of the note with the given id. Returns the host's promise; a refusal restores the pin and the panel shows the host's message. Rejects without reaching the host when the panel refuses: a deleted note, actions.pin false, or a write for the note still pending.\",\n invoke: (handle, args: { id: string }) => handle.togglePin(args.id),\n },\n toggle_flag: {\n safety: 'write',\n argsType: '{ id: string }',\n argsSchema: {\n type: 'object',\n properties: { id: { type: 'string' } },\n required: ['id'],\n },\n idempotent: false,\n // Reaches the host's data source; the result is the host's promise.\n openWorld: true,\n errors: [\n 'The panel offers no flag here: no onToggleFlag, no note with this id, or a deleted note.',\n 'A flag or delete for this note is still pending. Read notes again once it has settled.',\n \"The host refused the change. The flag is restored and the panel shows the host's message.\",\n ],\n descriptionKey: 'ui.agent.notesPanel.actions.toggleFlag',\n description:\n \"Toggle the flagged state of the note with the given id. Returns the host's promise; a refusal restores the flag and the panel shows the host's message. Rejects without reaching the host when the panel refuses: a deleted note, or a write for the note still pending.\",\n invoke: (handle, args: { id: string }) => handle.toggleFlag(args.id),\n },\n },\n domHooks: {\n root: {\n attr: 'data-component',\n value: 'notes-panel',\n description: 'Marks the NotesPanel region.',\n },\n instanceId: {\n attr: 'data-component-id',\n sourceProp: 'id',\n description:\n 'Sourced from the id prop. Required to address a specific notes panel from the agent.',\n },\n item: {\n attr: 'data-note-id',\n description:\n 'Stable note id on each rendered note row. Row controls carry data-note-action: edit, delete, pin or flag.',\n },\n },\n};\n","import {\n forwardRef,\n useCallback,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n} from 'react';\nimport { cva } from 'class-variance-authority';\nimport { useTranslation } from 'react-i18next';\nimport { getErrorMessage } from '../_shared/get-error-message';\nimport { handledRejection } from '../_shared/handled-rejection';\nimport { useAgentRegistration } from '../../agent/registry';\nimport { notesPanelAgent } from './notes-panel.agent';\nimport { ClinicalNoteCard } from '../clinical-note-card';\nimport type { ClinicalNoteCardProps } from '../clinical-note-card';\nimport { RichTextEditor } from '../rich-text-editor';\nimport type {\n RichTextEditorHandle,\n RichTextEditorProps,\n RichTextEditorToolbar,\n RedactorFactory,\n AiConsentGate,\n} from '../rich-text-editor';\nimport { TextArea } from '../text-area';\nimport { Alert } from '../alert';\nimport { Button, IconButton } from '../button';\nimport { Switch } from '../switch';\nimport { Tooltip } from '../tooltip';\nimport { Card } from '../card/card';\nimport { CONTENT_ENTER_CLASS, Skeleton } from '../skeleton/skeleton';\nimport { Dialog } from '../dialog';\nimport { NotebookPen, Pencil, Trash2 } from 'lucide-react';\nimport { PanelHeader } from '../panel-header';\nimport { REFLOW_ROW_CLASS, useListReflow } from '../../hooks/use-list-reflow';\nimport { useExitTransition } from '../../hooks/use-exit-transition';\nimport { useIsomorphicLayoutEffect } from '../../hooks/use-isomorphic-layout-effect';\nimport { useTheme } from '../../hooks/use-theme';\n\n/* ------------------------------------------------------------------ */\n/* NotesPanel — the Notes tool for the Control Room rail. */\n/* */\n/* A composer over an elevated ClinicalNoteCard timeline. Drops */\n/* into a ControlRoomRail tool `panel`, the patient profile, or the */\n/* care-plan editor — anywhere notes about the open entity belong. */\n/* The composer is the kit RichTextEditor by default (degrades to a */\n/* textarea where Redactor is absent), carries a permission-gated */\n/* \"clinical note\" toggle, and forwards the editor's AI affordances. */\n/* The note attaches to whatever entity the host is showing — the */\n/* host owns the attachment; the panel only emits content + clinical. */\n/* Pinned notes lead; pin / flag are inline per-note toggles. */\n/* ------------------------------------------------------------------ */\n\n/**\n * One note in the panel — the data subset of `ClinicalNoteCard`.\n *\n * `aria-label` names the card for assistive tech. Set it whenever a row is not\n * a clinical note: the card's fallback name is \"Clinical note\", so an entry\n * that is something else (a dated event, an import) is announced as one.\n */\nexport type NotesPanelNote = Pick<\n ClinicalNoteCardProps,\n | 'id'\n | 'dateIso'\n | 'createdAtIso'\n | 'author'\n | 'clinical'\n | 'attachedTo'\n | 'content'\n | 'contentFormat'\n | 'pinned'\n | 'flagged'\n | 'aria-label'\n | 'deleted'\n | 'operatorName'\n> & {\n /** What the host lets the reader do with this note. */\n actions?: NotesPanelNoteActions;\n /**\n * The host keeps this note when it is deleted and lists it again marked\n * `deleted` (a clinical record, for example). Its delete does not fade\n * the row: the row stays in place, its controls paused, until `notes`\n * marks it deleted or drops it. Host controls from `noteActions` hear\n * `deleting: true` meanwhile, so they can pause too. Leave it unset for\n * a note the host removes, or the row fades out and then comes back.\n */\n keptOnDelete?: boolean;\n};\n\n/** Per-note write permissions; an absent key means allowed. The panel hides\n * the pencil on `edit: false`, the pin toggle on `pin: false`, the built-in\n * delete on `delete: false`, and the pin, flag, pencil and delete on a\n * deleted note. */\nexport type NotesPanelNoteActions = {\n edit?: boolean;\n delete?: boolean;\n pin?: boolean;\n};\n\n/**\n * Curated agent handle for NotesPanel. Reads the note timeline's STRUCTURE\n * (ids + pinned / flagged / clinical / deleted flags, never the note body\n * or author, both PHI) and drives the composer + per-note toggles. See\n * `notes-panel.agent.ts`.\n */\nexport interface NotesPanelHandle {\n /** Timeline snapshot — ids + flags only, never note content (PHI). A note\n * whose delete is in flight is left out; a pin or flag in flight reports\n * the value it moved to. `deleted` marks a note kept for the record: it\n * takes no pin or flag. */\n getNotes: () => Array<{\n id?: string;\n pinned: boolean;\n flagged: boolean;\n clinical: boolean;\n deleted: boolean;\n }>;\n /** Whether the composer is mounted (onAddNote is wired). */\n canAddNote: () => boolean;\n /** Whether clinical notes may be written (the permission gate). */\n canAddClinical: () => boolean;\n /** Id of the note the host has addressed, or null when none is. */\n getCurrentNoteId: () => string | null;\n /** Commit a new note with explicit content (mirrors the composer's submit). */\n addNote: (submission: NotesPanelSubmission) => void | Promise<void>;\n /**\n * Toggle a note's pinned state: the same path as the pin toggle, with its\n * gate. Returns the host's promise, so a refusal rejects (a synchronous\n * throw comes back as a handled rejection). Also rejects, without calling\n * the host, when the panel refuses: no `onTogglePin`, no note with this\n * id, a deleted note, `actions.pin: false`, or a pin or delete for the\n * note still pending. `undefined` only when the host returned nothing.\n */\n togglePin: (id: string) => void | Promise<void>;\n /** As `togglePin`, for the flag. Refused for a deleted note. */\n toggleFlag: (id: string) => void | Promise<void>;\n}\n\n/** A write the host refused, as `onWriteError` hears it. */\nexport interface NotesPanelWriteFailure {\n /** What did not happen. `unpin` and `unflag` are the toggles turned off;\n * `add` and `edit` are the composer's saves. */\n kind: 'add' | 'edit' | 'delete' | 'pin' | 'unpin' | 'flag' | 'unflag';\n /** The note written to. Absent for `add`: the note never existed. */\n noteId?: string;\n /** What the handler rejected or threw with. */\n error: unknown;\n /**\n * Whether the panel told the reader. `false` when the answer came after\n * the panel unmounted or while it was hidden, inert or aria-hidden (a\n * rail panel on its way out, say), after the note left `notes` (for an\n * edit, also once it was marked deleted), while the note was being\n * deleted, after a newer write on the same note started, or when a new\n * write began before the refusal could show (a new write clears the\n * message). A refused save the panel did not show has lost its draft\n * too. It is decided after the render that follows the refusal, so a\n * host that changes `notes` or hides the panel in the same tick as it\n * rejects is judged on that change.\n */\n shown: boolean;\n}\n\n/** Payload handed to `onAddNote` when the composer commits. */\nexport interface NotesPanelSubmission {\n /** The note body — rich HTML (`composer='rich'`) or plain text. */\n content: string;\n /** Whether the \"clinical note\" toggle was set. */\n clinical: boolean;\n}\n\nexport interface NotesPanelProps extends Omit<\n HTMLAttributes<HTMLElement>,\n 'title' | 'children'\n> {\n /**\n * Stable instance id. Surfaced on the root as `data-component-id` so an\n * agent / MCP UI bridge can address this specific notes panel.\n */\n id?: string;\n /** Notes to render, newest-first by convention. Pinned notes lead. */\n notes: NotesPanelNote[];\n /**\n * Commit a new note. Omit to hide the composer (read-only timeline). Return\n * a promise to keep the draft until the host has saved it: the draft clears\n * when it resolves, and a rejection keeps it and shows the error's message.\n */\n onAddNote?: (submission: NotesPanelSubmission) => void | Promise<void>;\n /** The host's notes read. `'loading'` and `'error'` never show the empty\n * text; notes already held still render. Default `'ready'`. */\n status?: 'ready' | 'loading' | 'error';\n /** Retry a failed read. Renders a retry button in the error state. */\n onRetry?: () => void;\n /**\n * The note the reader ASKED for, addressed by id from somewhere else in the\n * record — a marker in a chart, a row in a grid, an agent. The panel marks\n * it, scrolls it to the middle of its own scroll region and moves focus to\n * it, and renders it unclamped so the thing that was asked for is readable\n * in full without a second click.\n *\n * Opening a panel is not the same as answering a question: a rail's\n * `setActiveTool` moves no focus and announces nothing, so a control whose\n * name promises \"in the notes panel\" produces no perceivable change for a\n * keyboard or screen-reader reader unless the panel lands them on the note.\n * That is what this prop is for; without it, a host has to reach into the\n * panel's DOM to do the same job.\n *\n * Marked on three channels, never colour alone (WCAG 1.4.1): an accent\n * wash that fades in and out over the card (steady where motion is off),\n * the focus outline on the row, and `aria-current` plus a visually-hidden\n * sentence naming the mark. Nothing is left on the row once the wash ends.\n *\n * Ids that match no note are ignored. To address the SAME note twice — the\n * reader pressing the same marker again after scrolling away — bump\n * `currentNoteKey` alongside it; this prop alone is a value, not a request.\n */\n currentNoteId?: string;\n /**\n * Bump on every address to re-scroll and re-focus the note in `currentNoteId`\n * and replay its wash, even when the id has not changed.\n *\n * Addressing is a request, not a value: a reader who presses the same marker\n * a second time (having scrolled away, or having moved focus off the note) is\n * asking to be taken back, and a control whose name promises the notes panel\n * must do something perceivable every time it is pressed. Without this the\n * second press is inert — the panel is already showing that note, so nothing\n * re-runs. Hosts increment a counter in the same handler that opens the tool.\n */\n currentNoteKey?: string | number;\n\n /* ----- Composer ----- */\n /**\n * `'rich'` (default) mounts the kit `RichTextEditor` (Redactor; degrades to a\n * textarea where Redactor is absent). `'plain'` keeps a simple `TextArea` for\n * lightweight surfaces / deterministic tests.\n */\n composer?: 'rich' | 'plain';\n /** Toolbar preset for the rich composer. Defaults to `'standard'`. */\n editorToolbar?: RichTextEditorToolbar;\n /** Inject the Redactor factory for the rich composer (else `window.$R`). */\n redactor?: RedactorFactory;\n /** Consumer image-upload endpoint for the rich composer. */\n imageUploadUrl?: string;\n\n /* ----- Clinical flag (permission-gated) ----- */\n /** Show the \"clinical note\" toggle in the composer. Default `true`. */\n showClinicalToggle?: boolean;\n /**\n * Permission gate — when `false` the clinical toggle is disabled and shows\n * `clinicalGatedReason` on hover/focus. Mirrors platform's\n * `practice_add_clinical_note` permission. Default `true`.\n */\n canAddClinicalNote?: boolean;\n /** Tooltip shown when the clinical toggle is gated off. */\n clinicalGatedReason?: string;\n /** Initial state of the clinical toggle. Default `false`. */\n defaultClinical?: boolean;\n\n /* ----- AI assistance (forwarded to RichTextEditor) ----- */\n onRequestAiDraft?: RichTextEditorProps['onRequestAiDraft'];\n aiDraftFormat?: RichTextEditorProps['aiDraftFormat'];\n aiPrivacyNotice?: RichTextEditorProps['aiPrivacyNotice'];\n onDictate?: RichTextEditorProps['onDictate'];\n onProofread?: RichTextEditorProps['onProofread'];\n onAutoFormat?: RichTextEditorProps['onAutoFormat'];\n /**\n * Patient AI-consent gate for Help-me-write + both mics, forwarded\n * straight to the rich composer. See `AiConsentGate`. Omit for today's\n * ungated behaviour. Ignored by the `'plain'` composer (it offers\n * neither affordance).\n */\n aiConsent?: AiConsentGate;\n /**\n * Template variables for the rich composer's \"Insert variable\" menu and\n * `[[TOKEN]]` chip rendering. Forwarded straight to `RichTextEditor`.\n * Ignored by the `'plain'` composer.\n */\n variables?: RichTextEditorProps['variables'];\n /** Decide whether a `[[TOKEN]]` is valid. See `RichTextEditor`. */\n validateVariable?: RichTextEditorProps['validateVariable'];\n /** The invalid `[[TOKEN]]`s in the draft, reported by the rich composer. */\n onVariableValidityChange?: RichTextEditorProps['onVariableValidityChange'];\n /**\n * Bring your own Help-me-write surface (e.g. practice templates) into the\n * composer, forwarded straight to `RichTextEditor`. See\n * `RichTextEditorProps['renderHelpMeWrite']`.\n */\n renderHelpMeWrite?: RichTextEditorProps['renderHelpMeWrite'];\n /** Practice templates in the composer's AI pill. See `RichTextEditor`. */\n aiTemplates?: RichTextEditorProps['aiTemplates'];\n /** After a pill action rewrote the draft (offer Undo). See `RichTextEditor`. */\n onAiApplied?: RichTextEditorProps['onAiApplied'];\n /** Upload an image yourself and resolve its URL. See `RichTextEditor`. */\n onUploadImage?: RichTextEditorProps['onUploadImage'];\n /** An AI call ran out of credits. See `RichTextEditor`. */\n onAiCreditsExhausted?: RichTextEditorProps['onAiCreditsExhausted'];\n /** Show the editor extensions affordance. See `RichTextEditor`. */\n showExtensions?: RichTextEditorProps['showExtensions'];\n extensions?: RichTextEditorProps['extensions'];\n extensionContext?: RichTextEditorProps['extensionContext'];\n onExtensionRun?: RichTextEditorProps['onExtensionRun'];\n /**\n * Shows the AI-credits/bundles hover card on every AI action trigger in\n * the composer. See `RichTextEditor`.\n */\n aiCreditsNotice?: RichTextEditorProps['aiCreditsNotice'];\n /**\n * Rendered just above the composer — e.g. the Help-me-write templates\n * pattern's `undoNotice`. Renders in both add and edit mode, whenever the\n * composer itself is mounted.\n */\n composerBefore?: ReactNode;\n /**\n * Rendered just after the composer — e.g. the Help-me-write templates\n * pattern's `manager` dialog. Renders in both add and edit mode, whenever\n * the composer itself is mounted.\n */\n composerAfter?: ReactNode;\n\n /* ----- Per-note actions ----- */\n /**\n * Pin or unpin a note; renders a pin toggle per note. Called on the click\n * with the value the note moves to. Return a promise and the panel shows\n * that value at once (a pinned note moves to the top), ignores further\n * clicks on that toggle until the promise settles and `notes` agrees, and\n * on a rejection puts the note back and shows the error's message above\n * the list. Return nothing and the change is left to your next render, as\n * before.\n */\n onTogglePin?: (id: string, next: boolean) => void | Promise<void>;\n /** As `onTogglePin`, for the flagged state (flagging does not re-order).\n * Hidden on a deleted note. */\n onToggleFlag?: (id: string, next: boolean) => void | Promise<void>;\n /**\n * Host-owned actions for each note (share, print…), rendered by the note\n * card beside its pin and flag, aligned to the inline end. The host\n * supplies labelled controls and owns what they do. Deleting belongs to\n * `onDeleteNote` and editing to `onEditNote`, which keep the panel's\n * confirm, rollback and focus. `state.deleting` is true while a delete\n * for the note is in flight: pause your controls then, as the panel\n * pauses its own.\n */\n noteActions?: (\n note: NotesPanelNote,\n state: { deleting: boolean },\n ) => ReactNode;\n /**\n * Save an edit to an existing note. When provided, each note the reader may\n * edit gets a pencil; it loads the note into the SAME composer that writes\n * new notes, in place, so a rich note is edited as rich text and keeps its\n * formatting. Return a promise to hold the pending state; a rejection keeps\n * the draft. Hidden on `actions.edit: false` and on a deleted note.\n */\n onEditNote?: (\n id: string,\n submission: NotesPanelSubmission,\n ) => void | Promise<void>;\n /**\n * Let an edit change a note's clinical flag. Default `false`: the \"Clinical\n * note\" toggle is hidden while editing and the submission carries the\n * note's existing flag. Most hosts save a note's content only, and a live\n * toggle that changes nothing is a lie. Set `true` only when the host\n * persists `submission.clinical` on edit.\n */\n editClinical?: boolean;\n /**\n * Delete a note; renders a delete button per note. Called on the click\n * that confirms it (on the delete click itself with\n * `confirmDelete={false}`), before the row fades, so the write reaches you\n * even if the panel unmounts during the fade. The row fades and stays out\n * of the list until `notes` drops it or returns it marked `deleted`. A\n * note marked `keptOnDelete` does not fade: its row stays in place, its\n * controls paused, until then. A reload that finishes (`status` from\n * `'loading'` to `'ready'`) and still lists it brings it back. Resolve\n * once the delete has landed; a rejection brings the row back and shows\n * the error's message. A synchronous return counts as landed, and the\n * row stays out: return the request's promise, and don't open your own\n * confirm in here (a cancel would still hide the note). Dropping\n * the note from `notes` in the same tick skips the fade (the rows below\n * still slide up). Hidden on `actions.delete: false` and on a deleted\n * note.\n */\n onDeleteNote?: (id: string) => void | Promise<void>;\n /**\n * Hears every refused write: a save from the composer, a delete, a pin or\n * a flag, with `shown` saying whether the panel told the reader. Report\n * the ones it did not (`shown: false`, for example when the panel\n * unmounted first) yourself, in a toast. Leave the rest to the panel, or\n * the reader hears it twice.\n */\n onWriteError?: (failure: NotesPanelWriteFailure) => void;\n /**\n * Confirm in an alert dialog before calling `onDeleteNote`. Default\n * `true`. `false` deletes on the click.\n */\n confirmDelete?: boolean;\n\n /* ----- Labels / chrome ----- */\n /** Panel heading. Defaults to the localised \"Notes\". */\n title?: string;\n /** Composer placeholder. */\n composerPlaceholder?: string;\n /** Save-button label. */\n addNoteLabel?: string;\n /** Rendered when there are no notes. */\n emptyState?: ReactNode;\n /** Accessible name for the panel region (defaults to `title`). */\n 'aria-label'?: string;\n}\n\n/* Lifts the card's content above the wash layer, so the wash tints the card\n surface only: note text and badges keep their own colours and contrast. */\nconst NOTE_CONTENT_ABOVE_WASH =\n 'ds:isolate ds:[&_[data-component=card]>*]:relative ds:[&_[data-component=card]>*]:z-[1]';\n\n/* The timeline row. The addressed row takes the keyboard focus outline; its\n visual mark is the wash layer below, so no row carries a border stripe. */\nconst noteItemVariants = cva(\n 'ds:relative ds:flex ds:flex-col ds:rounded-[var(--radius-lg)]',\n {\n variants: {\n current: {\n true: 'ds:focus:outline-[length:var(--focus-ring-width)] ds:focus:outline-solid ds:focus:outline-[color:var(--ring)] ds:focus:outline-offset-[length:var(--focus-ring-offset)]',\n false: '',\n },\n washed: { true: NOTE_CONTENT_ABOVE_WASH, false: '' },\n },\n defaultVariants: { current: false, washed: false },\n },\n);\n\n/* The accent wash on a row's card surface. `addressed` arrives, holds and\n leaves no mark; `editing` is steady for as long as the edit lasts. With\n motion off (OS setting, accessible theme) `addressed` holds steady too. */\nconst noteWashVariants = cva(\n 'ds:pointer-events-none ds:absolute ds:inset-0 ds:rounded-[var(--radius-lg)] ds:bg-[color:var(--accent)]',\n {\n variants: {\n state: {\n addressed: [\n 'ds:opacity-0',\n 'ds:animate-[note-addressed_calc(var(--animation-duration)*9)_var(--ease-in-out)]',\n 'ds:motion-reduce:animate-none ds:motion-reduce:opacity-[var(--opacity-12)]',\n 'ds:[.theme-accessible_&]:animate-none ds:[.theme-accessible_&]:opacity-[var(--opacity-12)]',\n ].join(' '),\n editing: 'ds:opacity-[var(--opacity-12)]',\n },\n },\n },\n);\n\n/* The panel root and the empty text. They take focus only from script, as\n the last place to land, so they show the kit's ring for a keyboard\n reader. */\nconst focusTargetClass = [\n 'ds:rounded-[var(--radius-lg)] ds:outline-none',\n 'ds:focus-visible:outline-[length:var(--focus-ring-width)] ds:focus-visible:outline-solid',\n 'ds:focus-visible:outline-[color:var(--ring)] ds:focus-visible:outline-offset-[length:var(--focus-ring-offset)]',\n].join(' ');\nconst rootClass = ['ds:flex ds:flex-col', focusTargetClass].join(' ');\n\n/* A row on its way out fades in place; the reflow hook then slides the\n rows below up to close the gap. Declared at rest so the transition has\n a value to animate from the moment the leaving class lands. */\nconst noteLeavingClass = 'ds:opacity-0';\nconst noteElevationClass = [\n 'ds:transition-opacity ds:duration-[var(--animation-duration)]',\n 'ds:ease-[var(--ease-out)] ds:motion-reduce:transition-none',\n].join(' ');\n\n/* Body lines per placeholder note. Uneven, so three cards do not read as one\n repeated stamp. */\nconst NOTE_SKELETON_LINES = [3, 2, 3] as const;\n\n/** Strip tags / entities to test whether a rich draft holds real content. */\nfunction hasRichContent(html: string): boolean {\n if (!html) return false;\n if (/<img\\b/i.test(html)) return true;\n return (\n html\n .replace(/<[^>]*>/g, '')\n .replace(/ /gi, ' ')\n .trim().length > 0\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* Writes at click time. Same algorithm and names as TasksPanel's */\n/* server mode (tasks-panel.tsx), so the two can share one hook later. */\n/* ------------------------------------------------------------------ */\n\ntype NoteWriteKind = 'delete' | 'pin' | 'flag';\n\n/* A write the host has been asked for and `notes` has not caught up with. */\ninterface NoteWrite {\n /** Pin and flag only: the value the toggle moved to. */\n next?: boolean;\n /** The host's promise has resolved. */\n settled: boolean;\n /** Loads finished when it resolved. */\n edgeAtSettle: number;\n /** The notes signature when it resolved. */\n sigAtSettle: string;\n}\n\n/* Up to one write of each kind per note. */\ntype NoteWrites = Partial<Record<NoteWriteKind, NoteWrite>>;\n\n/* What a click or a handle call did. `result` goes back to an agent;\n `refusal` says why the panel did not call the host. */\ninterface WriteAttempt {\n started: boolean;\n result?: void | Promise<void>;\n refusal?: string;\n}\n\n/* The refused write the Alert above the list explains. */\ninterface WriteFailure {\n kind: NotesPanelWriteFailure['kind'];\n noteId: string;\n /** The host's own words, or empty. */\n message: string;\n /** Remounts the Alert, so a repeat refusal is announced again. */\n seq: number;\n}\n\n/* Where focus was, so it can be put back near there when its row leaves. */\ninterface FocusRecord {\n el: HTMLElement;\n noteId: string | null;\n action: string | null;\n index: number;\n /** Inside the write-error Alert (its Close button). */\n inWriteError: boolean;\n}\n\n/* What the stable agent handle reaches through to, refreshed each render. */\ninterface PanelActions {\n toggle: (noteId: string, kind: 'pin' | 'flag') => WriteAttempt;\n}\n\n/* An agent hears a refusal as a rejection, so `undefined` can only mean\n the host returned nothing. */\nfunction agentToggle(\n actions: PanelActions | null,\n noteId: string,\n kind: 'pin' | 'flag',\n): void | Promise<void> {\n const attempt = actions?.toggle(noteId, kind);\n const refusal = attempt ? attempt.refusal : 'the panel is not mounted';\n return refusal === undefined\n ? attempt?.result\n : handledRejection(new Error(`NotesPanel: ${kind} refused (${refusal}).`));\n}\n\nconst EMPTY_WRITES: ReadonlyMap<string, NoteWrites> = new Map();\nconst EMPTY_HIDDEN: ReadonlySet<string> = new Set();\n\n/* One string per list state that changes when an id or a flag does. */\nfunction sigOf(notes: readonly NotesPanelNote[]): string {\n return notes\n .map(\n (n) =>\n `${n.id ?? ''}:${n.pinned ? 1 : 0}${n.flagged ? 1 : 0}${n.deleted ? 1 : 0}`,\n )\n .join('|');\n}\n\n/* A promise from any realm counts, as the composer's commit already does. */\nfunction isThenable(value: unknown): value is PromiseLike<void> {\n return (\n typeof (value as { then?: unknown } | null | undefined)?.then === 'function'\n );\n}\n\n/* A row's place among the rows a reader can still act on. A row waiting\n on its own delete sits where the next live row starts. */\nfunction liveIndexOf(\n liveIds: readonly string[],\n orderedIds: readonly string[],\n noteId: string,\n): number {\n const live = liveIds.indexOf(noteId);\n if (live >= 0) return live;\n const at = orderedIds.indexOf(noteId);\n if (at < 0) return -1;\n const liveSet = new Set(liveIds);\n return orderedIds.slice(0, at).filter((id) => liveSet.has(id)).length;\n}\n\n/* Focus an element outside the tab order, from script. It is focusable only\n while it holds focus: a lasting tabindex on the panel would take every\n mouse click on a note's text and move where Tab starts from. */\nfunction focusFromScript(el: HTMLElement): void {\n if (el.hasAttribute('tabindex')) {\n el.focus();\n return;\n }\n const release = () => el.removeAttribute('tabindex');\n el.setAttribute('tabindex', '-1');\n el.focus();\n if (document.activeElement === el) {\n el.addEventListener('blur', release, { once: true });\n } else release();\n}\n\nexport const NotesPanel = forwardRef<HTMLElement, NotesPanelProps>(\n function NotesPanel(\n {\n id,\n notes,\n onAddNote,\n status = 'ready',\n onRetry,\n currentNoteId,\n currentNoteKey,\n composer = 'rich',\n editorToolbar = 'standard',\n redactor,\n imageUploadUrl,\n showClinicalToggle = true,\n canAddClinicalNote = true,\n clinicalGatedReason,\n defaultClinical = false,\n onRequestAiDraft,\n aiDraftFormat,\n aiPrivacyNotice,\n onDictate,\n onProofread,\n onAutoFormat,\n aiConsent,\n variables,\n validateVariable,\n onVariableValidityChange,\n renderHelpMeWrite,\n aiTemplates,\n onAiApplied,\n onUploadImage,\n onAiCreditsExhausted,\n showExtensions,\n aiCreditsNotice,\n extensions,\n extensionContext,\n onExtensionRun,\n composerBefore,\n composerAfter,\n onTogglePin,\n onToggleFlag,\n noteActions,\n onEditNote,\n editClinical = false,\n onDeleteNote,\n onWriteError,\n confirmDelete = true,\n title,\n composerPlaceholder,\n addNoteLabel,\n emptyState,\n className,\n 'aria-label': ariaLabel,\n ...rest\n },\n ref,\n ) {\n const { t, i18n } = useTranslation();\n const editorRef = useRef<RichTextEditorHandle>(null);\n const [draft, setDraft] = useState('');\n const [clinical, setClinical] = useState(defaultClinical);\n const [pending, setPending] = useState(false);\n const [addError, setAddError] = useState<string | null>(null);\n // The note loaded into the composer for editing, or null when composing.\n const [editingId, setEditingId] = useState<string | null>(null);\n const editingIdRef = useRef(editingId);\n editingIdRef.current = editingId;\n /* Settle in only when this content REPLACES a skeleton. Content that was\n simply there from the start must not fade: it would read as invisible\n for one animation to any test or reader that looks at once. */\n const followedLoading = useRef(false);\n if (status === 'loading') followedLoading.current = true;\n const enterClass = followedLoading.current ? CONTENT_ENTER_CLASS : '';\n\n const heading = title ?? t('notesPanel.title', { defaultValue: 'Notes' });\n const headingId = useId();\n const placeholder =\n composerPlaceholder ??\n t('notesPanel.placeholder', { defaultValue: 'Add a note…' });\n const composerLabel =\n editingId !== null\n ? t('notesPanel.edit', { defaultValue: 'Edit note' })\n : t('notesPanel.composerLabel', { defaultValue: 'New note' });\n\n // Live content check: plain reads the draft directly; rich strips the draft\n // (debounced) for the disabled state but commits from the editor handle.\n const hasContent =\n composer === 'rich' ? hasRichContent(draft) : draft.trim().length > 0;\n\n /* ----- Writes in flight (delete, pin, flag) ----- */\n const notesRef = useRef(notes);\n notesRef.current = notes;\n const [writes, setWritesState] =\n useState<ReadonlyMap<string, NoteWrites>>(EMPTY_WRITES);\n const writesRef = useRef<ReadonlyMap<string, NoteWrites>>(EMPTY_WRITES);\n const [hidden, setHiddenState] =\n useState<ReadonlySet<string>>(EMPTY_HIDDEN);\n const hiddenRef = useRef<ReadonlySet<string>>(EMPTY_HIDDEN);\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const rootRef = useRef<HTMLElement>(null);\n const onWriteErrorRef = useRef(onWriteError);\n onWriteErrorRef.current = onWriteError;\n /* Whether a message shown now reaches the reader: not once the panel\n has unmounted, nor while a host keeps it mounted but hidden, inert\n or aria-hidden (a rail panel on its way out, say). */\n const panelShown = useCallback((): boolean => {\n const root = rootRef.current;\n if (\n !mountedRef.current ||\n !root ||\n root.closest('[hidden],[inert],[aria-hidden=\"true\"]')\n ) {\n return false;\n }\n return typeof root.checkVisibility === 'function'\n ? root.checkVisibility()\n : true;\n }, []);\n\n /* A refusal is judged after the render it causes: a host that changes\n `notes` or hides the panel in the same tick as it rejects has its\n change committed by then. `live` is false once the panel unmounts. */\n const judgementsRef = useRef<Array<(live: boolean) => void>>([]);\n const [judgeSeq, setJudgeSeq] = useState(0);\n const judgeLater = useCallback((judge: (live: boolean) => void): void => {\n if (!mountedRef.current) {\n judge(false);\n return;\n }\n judgementsRef.current.push(judge);\n setJudgeSeq((seq) => seq + 1);\n }, []);\n useEffect(() => {\n const queued = judgementsRef.current;\n judgementsRef.current = [];\n queued.forEach((judge) => judge(true));\n }, [judgeSeq]);\n useEffect(\n () => () => {\n const queued = judgementsRef.current;\n judgementsRef.current = [];\n queued.forEach((judge) => judge(false));\n },\n [],\n );\n\n // The refs are written first, so a guard read in the same tick sees the\n // change before React re-renders.\n const updatePending = (\n edit: (m: Map<string, NoteWrites>) => void,\n ): void => {\n const next = new Map(writesRef.current);\n edit(next);\n writesRef.current = next;\n setWritesState(next);\n };\n const updateHidden = (edit: (s: Set<string>) => void): void => {\n const next = new Set(hiddenRef.current);\n edit(next);\n hiddenRef.current = next;\n setHiddenState(next);\n };\n const writeOf = (\n noteId: string,\n kind: NoteWriteKind,\n ): NoteWrite | undefined => writesRef.current.get(noteId)?.[kind];\n const setWrite = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite | undefined,\n ): void =>\n updatePending((m) => {\n const entry: NoteWrites = { ...m.get(noteId) };\n if (write) entry[kind] = write;\n else delete entry[kind];\n if (Object.keys(entry).length > 0) m.set(noteId, entry);\n else m.delete(noteId);\n });\n // A note whose delete is in flight takes no second delete.\n const deleting = (noteId: string | undefined): boolean =>\n noteId != null && !!writesRef.current.get(noteId)?.delete;\n\n const commit = useCallback(() => {\n const save = editingId !== null ? onEditNote : onAddNote;\n if (!save || pending) return;\n const rich = composer === 'rich';\n const content = rich\n ? (editorRef.current?.getHTML() ?? draft)\n : draft.trim();\n if (rich ? !hasRichContent(content) : !content) return;\n const reset = () => {\n if (rich) editorRef.current?.clear();\n setDraft('');\n setClinical(defaultClinical);\n setEditingId(null);\n };\n setAddError(null);\n const edited = editingId;\n // A refused save reaches `onWriteError` too: one the panel could not\n // show has lost its draft, so the host must tell the reader. An edit\n // dropped meanwhile (its note left or was deleted) is not shown.\n const refused = (error: unknown): void =>\n judgeLater((live) => {\n const draftKept =\n live &&\n (edited === null ||\n (editingIdRef.current === edited &&\n notesRef.current.some((n) => n.id === edited && !n.deleted)));\n if (draftKept) {\n setAddError(getErrorMessage(error, t('notesPanel.addFailed')));\n }\n onWriteErrorRef.current?.({\n kind: edited !== null ? 'edit' : 'add',\n noteId: edited ?? undefined,\n error,\n shown: draftKept && panelShown(),\n });\n });\n let result: void | Promise<void>;\n try {\n result =\n editingId !== null && onEditNote\n ? onEditNote(editingId, { content, clinical })\n : onAddNote?.({ content, clinical });\n } catch (error: unknown) {\n refused(error);\n return;\n }\n if (!result || typeof result.then !== 'function') return reset();\n // A failed save keeps the draft, so nothing typed is lost.\n setPending(true);\n Promise.resolve(result)\n .then(reset, refused)\n .finally(() => setPending(false));\n }, [\n composer,\n draft,\n clinical,\n defaultClinical,\n editingId,\n judgeLater,\n onAddNote,\n onEditNote,\n panelShown,\n pending,\n t,\n ]);\n\n const clinicalToggleShown =\n showClinicalToggle && (editingId === null || editClinical);\n // The note being edited is being deleted: Save waits for the host.\n const editBlocked = editingId !== null && !!writes.get(editingId)?.delete;\n\n /* Every row carries the SAME action words, so each accessible name adds\n the note's own date: otherwise a screen reader hears a list of\n identical \"Edit note\" buttons. The tooltip keeps the short words. */\n const noteStamp = useCallback(\n (note: NotesPanelNote): string => {\n try {\n return new Intl.DateTimeFormat(i18n.language, {\n day: 'numeric',\n month: 'long',\n year: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n }).format(new Date(note.dateIso));\n } catch {\n return note.dateIso;\n }\n },\n [i18n.language],\n );\n\n /* ----- Edit in place: the composer takes the note, and gives it back ----- */\n const startEdit = useCallback(\n (note: NotesPanelNote) => {\n if (!note.id || pending) return;\n if (writesRef.current.get(note.id)?.delete) return;\n const content = note.content ?? '';\n setAddError(null);\n setEditingId(note.id);\n setClinical(note.clinical ?? false);\n setDraft(content);\n if (composer === 'rich') {\n editorRef.current?.clear();\n editorRef.current?.insertAtCursor(content, { asHtml: true });\n }\n editorRef.current?.focus();\n },\n [composer, pending],\n );\n const cancelEdit = useCallback(() => {\n if (composer === 'rich') editorRef.current?.clear();\n setDraft('');\n setClinical(defaultClinical);\n setAddError(null);\n setEditingId(null);\n }, [composer, defaultClinical]);\n // The note being edited went away (deleted, or another patient's notes\n // arrived): its draft must not be saved against whatever comes next.\n const editingStillThere =\n editingId === null ||\n notes.some((note) => note.id === editingId && !note.deleted);\n useEffect(() => {\n if (!editingStillThere) cancelEdit();\n }, [editingStillThere, cancelEdit]);\n\n /* A pin or flag in flight shows the value it moved to. */\n const effectivePinned = (note: NotesPanelNote): boolean =>\n (note.id ? writes.get(note.id)?.pin?.next : undefined) ?? !!note.pinned;\n const effectiveFlagged = (note: NotesPanelNote): boolean =>\n (note.id ? writes.get(note.id)?.flag?.next : undefined) ?? !!note.flagged;\n\n // A deleted row stays out until the host drops it or marks it deleted.\n // Pinned notes lead; order within each group is preserved.\n const ordered = notes\n .filter((note) => !note.id || !hidden.has(note.id))\n .sort((a, b) => Number(effectivePinned(b)) - Number(effectivePinned(a)));\n const orderedIds = ordered.flatMap((note) => (note.id ? [note.id] : []));\n // The rows a reader can still act on: none on its way out.\n const liveIdsRef = useRef<string[]>([]);\n liveIdsRef.current = orderedIds.filter(\n (noteId) => !writes.get(noteId)?.delete,\n );\n const orderedIdsRef = useRef<string[]>([]);\n orderedIdsRef.current = orderedIds;\n\n /* The accessible theme zeroes `--animation-duration`, so its CSS plays\n nothing — the JS must agree, or a row would sit still for the delay\n and then vanish anyway. `undefined` leaves the media query in charge. */\n const { resolvedTheme } = useTheme();\n const reduceMotion = resolvedTheme.endsWith('-accessible') || undefined;\n\n /* Closing the gap a removed row leaves: the rows below slide up rather\n than jumping, so the eye keeps its place in the list. Fires on add,\n delete, and re-order (pinning) — any change to the visible id\n sequence. */\n const { containerRef: reflowRef } = useListReflow<HTMLUListElement>({\n key: ordered.map((n) => n.id).join(),\n reduceMotion,\n });\n\n /* A deleted note fades out; once it has, it stays hidden until the host\n drops it. The reflow hook then slides the rows below up. */\n const deleteExit = useExitTransition({ reduceMotion });\n\n /* ----- Refusals and announcements ----- */\n const [writeFailure, setWriteFailure] = useState<WriteFailure | null>(null);\n const failureSeqRef = useRef(0);\n // Counts writes started. Each clears the message, so a refusal judged\n // after a newer write began would never be seen.\n const writeEpochRef = useRef(0);\n const clearForWrite = (): void => {\n writeEpochRef.current += 1;\n setWriteFailure(null);\n };\n /* Every refusal reaches `onWriteError`. The Alert shows it only while\n the reader can see the note it is about. `current` is false when a\n newer write, or a reload, has replaced the one refused. */\n const reportFailure = (\n kind: WriteFailure['kind'],\n noteId: string,\n error: unknown,\n current = true,\n ): void => {\n const epoch = writeEpochRef.current;\n judgeLater((live) => {\n const shown =\n live &&\n current &&\n epoch === writeEpochRef.current &&\n panelShown() &&\n notesRef.current.some((note) => note.id === noteId) &&\n (kind === 'delete' ||\n (!deleting(noteId) && !hiddenRef.current.has(noteId)));\n if (shown) {\n failureSeqRef.current += 1;\n setWriteFailure({\n kind,\n noteId,\n message: getErrorMessage(error, ''),\n seq: failureSeqRef.current,\n });\n }\n onWriteErrorRef.current?.({ kind, noteId, error, shown });\n });\n };\n /* Every row reads alike, so the message names its note by date, as the\n row controls do; an undated note gets the plain sentence. Literal\n keys, so the i18n coverage gate sees each one. */\n const failureTitle = (failure: WriteFailure): string => {\n const note = notes.find((n) => n.id === failure.noteId);\n const date = note?.dateIso ? noteStamp(note) : '';\n if (date) {\n switch (failure.kind) {\n case 'delete':\n return t('notesPanel.deleteFailedNamed', { date });\n case 'pin':\n return t('notesPanel.pinFailedNamed', { date });\n case 'unpin':\n return t('notesPanel.unpinFailedNamed', { date });\n case 'flag':\n return t('notesPanel.flagFailedNamed', { date });\n default:\n return t('notesPanel.unflagFailedNamed', { date });\n }\n }\n switch (failure.kind) {\n case 'delete':\n return t('notesPanel.deleteFailed');\n case 'pin':\n return t('notesPanel.pinFailed');\n case 'unpin':\n return t('notesPanel.unpinFailed');\n case 'flag':\n return t('notesPanel.flagFailed');\n default:\n return t('notesPanel.unflagFailed');\n }\n };\n // The refusal belongs to its note: it goes when the note does.\n const failureShown =\n writeFailure !== null &&\n notes.some((note) => note.id === writeFailure.noteId);\n // The last one on screen: where focus goes if it vanishes under Close.\n const shownFailureRef = useRef<WriteFailure | null>(null);\n if (writeFailure && failureShown) shownFailureRef.current = writeFailure;\n useEffect(() => {\n if (writeFailure && !failureShown) setWriteFailure(null);\n }, [writeFailure, failureShown]);\n\n // Each message renders a new text node, so a second one within the\n // second is heard too. Cleared after a second.\n const [announcement, setAnnouncement] = useState({ text: '', seq: 0 });\n const announceTimerRef = useRef<number | undefined>(undefined);\n const announce = (text: string): void => {\n setAnnouncement((prev) => ({ text, seq: prev.seq + 1 }));\n window.clearTimeout(announceTimerRef.current);\n announceTimerRef.current = window.setTimeout(\n () => setAnnouncement((prev) => ({ ...prev, text: '' })),\n 1000,\n );\n };\n useEffect(() => () => window.clearTimeout(announceTimerRef.current), []);\n const announceDeleted = (): void => announce(t('notesPanel.deleted'));\n\n /* ----- Settle, reconcile, rollback ----- */\n /* Loads finished: +1 each time `status` goes from loading to ready. A\n write that settled before a load finished can then let go. */\n const loadEdgesRef = useRef(0);\n const prevStatusRef = useRef(status);\n useEffect(() => {\n if (prevStatusRef.current === 'loading' && status === 'ready') {\n loadEdgesRef.current += 1;\n }\n prevStatusRef.current = status;\n }, [status]);\n\n /* Let go of writes the host's list has caught up with. Never keyed on\n the identity of the `notes` array. */\n const reconcile = (): void => {\n const list = notesRef.current;\n const sig = sigOf(list);\n const byId = new Map(list.map((note) => [note.id, note]));\n const dropped: Array<[string, NoteWriteKind]> = [];\n writesRef.current.forEach((entry, noteId) => {\n const note = byId.get(noteId);\n (Object.keys(entry) as NoteWriteKind[]).forEach((kind) => {\n const write = entry[kind];\n if (!write) return;\n if (!note) {\n dropped.push([noteId, kind]);\n return;\n }\n if (!write.settled) return;\n const hostAgrees =\n kind === 'delete'\n ? note.deleted === true\n : (kind === 'pin' ? !!note.pinned : !!note.flagged) ===\n write.next;\n // A delete answers to a reload or its own note, never to a change\n // in another note.\n const listMoved =\n loadEdgesRef.current > write.edgeAtSettle ||\n (kind !== 'delete' && sig !== write.sigAtSettle);\n if (hostAgrees || listMoved) dropped.push([noteId, kind]);\n });\n });\n if (dropped.length === 0) return;\n updatePending((m) =>\n dropped.forEach(([noteId, kind]) => {\n const entry: NoteWrites = { ...m.get(noteId) };\n delete entry[kind];\n if (Object.keys(entry).length > 0) m.set(noteId, entry);\n else m.delete(noteId);\n }),\n );\n const deletes = dropped\n .filter(([, kind]) => kind === 'delete')\n .map(([noteId]) => noteId);\n if (deletes.some((noteId) => hiddenRef.current.has(noteId))) {\n updateHidden((set) => deletes.forEach((noteId) => set.delete(noteId)));\n }\n // A row the host kept, or returned marked deleted, fades back in.\n deletes.forEach((noteId) => deleteExit.cancel(noteId));\n };\n\n /* Settle and rollback act only on the write their promise started. A\n newer write for the same note, started after a reload dropped this\n one, answers for itself. */\n const settle = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite,\n ): void => {\n if (writeOf(noteId, kind) !== write) return;\n setWrite(noteId, kind, {\n ...write,\n settled: true,\n edgeAtSettle: loadEdgesRef.current,\n sigAtSettle: sigOf(notesRef.current),\n });\n // A host that updated `notes` before resolving is caught here.\n reconcile();\n };\n\n /* Undo a write the host refused: the row comes back and the toggle\n reverts, because both read from `writes`. Focus stays where it is.\n Returns false when the write had already been let go. */\n const rollback = (\n noteId: string,\n kind: NoteWriteKind,\n write: NoteWrite,\n ): boolean => {\n if (writeOf(noteId, kind) !== write) return false;\n setWrite(noteId, kind, undefined);\n if (kind !== 'delete') return true;\n if (hiddenRef.current.has(noteId)) {\n updateHidden((set) => set.delete(noteId));\n }\n deleteExit.cancel(noteId);\n return true;\n };\n\n const notesSig = useMemo(() => sigOf(notes), [notes]);\n useEffect(() => {\n reconcile();\n // `reconcile` reads refs only; the list signature is the trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [notesSig, status]);\n\n /* Pin and flag: the host is told on the click, with the value the note\n moves to. Only a returned promise is tracked; a host that returns\n nothing decides through its next render, as before. */\n const runToggle = (noteId: string, kind: 'pin' | 'flag'): WriteAttempt => {\n const handler = kind === 'pin' ? onTogglePin : onToggleFlag;\n const refuse = (refusal: string): WriteAttempt => ({\n started: false,\n refusal,\n });\n if (!handler) {\n return refuse(kind === 'pin' ? 'no onTogglePin' : 'no onToggleFlag');\n }\n const note = notesRef.current.find((n) => n.id === noteId);\n if (!note) return refuse('no note has this id');\n if (note.deleted) return refuse('the note is deleted');\n if (kind === 'pin' && note.actions?.pin === false) {\n return refuse('actions.pin is false for this note');\n }\n const entry = writesRef.current.get(noteId);\n if (entry?.delete) return refuse('the note is being deleted');\n if (entry?.[kind]) {\n return refuse(`a ${kind} write for this note is still pending`);\n }\n const next = !(kind === 'pin' ? note.pinned : note.flagged);\n const failure: WriteFailure['kind'] =\n kind === 'pin' ? (next ? 'pin' : 'unpin') : next ? 'flag' : 'unflag';\n clearForWrite();\n let result: void | Promise<void>;\n try {\n result = handler(noteId, next);\n } catch (error: unknown) {\n reportFailure(failure, noteId, error);\n return { started: false, result: handledRejection(error) };\n }\n if (!isThenable(result)) return { started: true, result };\n const write: NoteWrite = {\n next,\n settled: false,\n edgeAtSettle: 0,\n sigAtSettle: '',\n };\n setWrite(noteId, kind, write);\n const hostPromise = Promise.resolve(result);\n hostPromise.then(\n () => {\n if (mountedRef.current) settle(noteId, kind, write);\n },\n (error: unknown) => {\n const current = mountedRef.current && rollback(noteId, kind, write);\n reportFailure(failure, noteId, error, current);\n },\n );\n return { started: true, result: hostPromise };\n };\n\n /* Delete: the host is told on the (confirming) click, before the fade,\n so a panel that unmounts mid-fade loses nothing. */\n const runDelete = (noteId: string): boolean => {\n if (!onDeleteNote) return false;\n const note = notesRef.current.find((n) => n.id === noteId);\n if (!note || note.deleted || note.actions?.delete === false) {\n return false;\n }\n if (writeOf(noteId, 'delete')) return false;\n clearForWrite();\n let result: void | Promise<void>;\n try {\n result = onDeleteNote(noteId);\n } catch (error: unknown) {\n reportFailure('delete', noteId, error);\n return false;\n }\n if (isThenable(result)) {\n const write: NoteWrite = {\n settled: false,\n edgeAtSettle: 0,\n sigAtSettle: '',\n };\n setWrite(noteId, 'delete', write);\n // A kept row waits in place, marked busy, which some screen readers\n // skip: say once that it is waiting.\n if (note.keptOnDelete) {\n announce(\n note.dateIso\n ? t('notesPanel.deletingNamed', { date: noteStamp(note) })\n : t('notesPanel.deleting'),\n );\n }\n Promise.resolve(result).then(\n () => {\n if (!mountedRef.current) return;\n announceDeleted();\n settle(noteId, 'delete', write);\n },\n (error: unknown) => {\n const current =\n mountedRef.current && rollback(noteId, 'delete', write);\n reportFailure('delete', noteId, error, current);\n },\n );\n } else {\n // A synchronous return counts as landed.\n setWrite(noteId, 'delete', {\n settled: true,\n edgeAtSettle: loadEdgesRef.current,\n sigAtSettle: sigOf(notesRef.current),\n });\n announceDeleted();\n }\n // A note the host keeps holds its place, paused, until it comes back\n // marked deleted: fading it out would only bring it back.\n if (!note.keptOnDelete) {\n deleteExit.leave(noteId, () => {\n if (writeOf(noteId, 'delete')) {\n updateHidden((set) => set.add(noteId));\n }\n });\n }\n return true;\n };\n\n const [pendingDelete, setPendingDelete] = useState<string | null>(null);\n // Where focus goes once the confirm dialog closes: `started` false\n // means back to the delete that opened it.\n const deleteFocusRef = useRef<{\n noteId: string;\n index: number;\n started: boolean;\n } | null>(null);\n const handleDeleteNote = (noteId: string): void => {\n if (!onDeleteNote || deleting(noteId)) return;\n // Its edit is being saved: the delete waits, as Save waits on a delete.\n if (pending && editingId === noteId) return;\n if (!confirmDelete) {\n runDelete(noteId);\n return;\n }\n deleteFocusRef.current = { noteId, index: -1, started: false };\n setPendingDelete(noteId);\n };\n const confirmDeleteNote = (): void => {\n const noteId = pendingDelete;\n if (!noteId) return;\n const index = liveIdsRef.current.indexOf(noteId);\n if (runDelete(noteId)) {\n deleteFocusRef.current = { noteId, index, started: true };\n }\n setPendingDelete(null);\n };\n // A dialog opened for one note never confirms against another list.\n const dialogOpen =\n pendingDelete !== null &&\n notes.some((note) => note.id === pendingDelete && !note.deleted);\n useEffect(() => {\n if (pendingDelete !== null && !dialogOpen) setPendingDelete(null);\n }, [pendingDelete, dialogOpen]);\n\n /* ----- Focus: a row that leaves or moves keeps the reader's place ----- */\n useImperativeHandle(ref, () => rootRef.current as HTMLElement, []);\n\n /* A control in a note row, by action; any action when `action` is null. */\n const inRow = (\n noteId: string | null | undefined,\n action: string | null,\n ): HTMLElement | null =>\n noteId\n ? (rootRef.current?.querySelector<HTMLElement>(\n `[data-note-id=\"${CSS.escape(noteId)}\"] ${\n action\n ? `[data-note-action=\"${CSS.escape(action)}\"]`\n : '[data-note-action]'\n }`,\n ) ?? null)\n : null;\n /* Where focus lands when a row leaves: the same action in the row now\n at `index`, else in the row above, else any action in those rows.\n Rows on their way out do not count. */\n const nearTarget = (\n index: number,\n action: string | null,\n ): HTMLElement | null => {\n const ids = liveIdsRef.current;\n return (\n inRow(ids[index], action) ??\n inRow(ids[index - 1], action) ??\n inRow(ids[index], null) ??\n inRow(ids[index - 1], null)\n );\n };\n /* No note control left: the empty text, else the panel itself. */\n const landLast = (): void => {\n const root = rootRef.current;\n const last =\n root?.querySelector<HTMLElement>('[data-notes-panel-empty]') ?? root;\n if (last) focusFromScript(last);\n };\n const landNear = (target: HTMLElement | null): void => {\n if (target) target.focus();\n else landLast();\n };\n\n /* Radix returns focus only to a Dialog.Trigger, and this dialog has\n none. A cancel goes back to the delete that opened it. A confirmed\n delete lands once, where the reader will end up: the next note's\n delete. While the last note fades, focus waits on its delete and the\n rescue below moves it to the empty text once the row goes. */\n const handleDialogCloseFocus = (event: Event): void => {\n const record = deleteFocusRef.current;\n deleteFocusRef.current = null;\n if (!record) return;\n event.preventDefault();\n const trigger = inRow(record.noteId, 'delete');\n landNear(\n record.started\n ? (nearTarget(record.index, 'delete') ?? trigger)\n : trigger,\n );\n };\n\n /* Dismissing the error unmounts the focused Close button. Hand focus to\n the control whose write was refused, as WarningStack hands it on,\n unless the reader has already moved it. */\n const writeErrorRef = useRef<HTMLDivElement>(null);\n const failureTarget = (failure: WriteFailure): HTMLElement | null => {\n const action =\n failure.kind === 'delete'\n ? 'delete'\n : failure.kind.endsWith('pin')\n ? 'pin'\n : 'flag';\n const index = liveIdsRef.current.indexOf(failure.noteId);\n return (\n inRow(failure.noteId, action) ??\n inRow(failure.noteId, null) ??\n (index >= 0 ? nearTarget(index, action) : null)\n );\n };\n const dismissWriteFailure = (failure: WriteFailure): void => {\n if (writeErrorRef.current?.contains(document.activeElement)) {\n landNear(failureTarget(failure));\n }\n setWriteFailure(null);\n };\n\n /* The row with focus left without the dialog (confirmDelete off, or the\n host dropped it): put focus on the same control in the row that took\n its place. Mirrors tasks-panel.tsx. */\n const focusRef = useRef<FocusRecord | null>(null);\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return undefined;\n const onFocusIn = (event: FocusEvent) => {\n const el = event.target;\n if (!(el instanceof HTMLElement)) return;\n const noteId =\n el.closest<HTMLElement>('[data-note-id]')?.dataset.noteId ?? null;\n focusRef.current = {\n el,\n noteId,\n action:\n el.closest<HTMLElement>('[data-note-action]')?.dataset.noteAction ??\n null,\n index: noteId\n ? liveIndexOf(liveIdsRef.current, orderedIdsRef.current, noteId)\n : -1,\n inWriteError: !!el.closest('[data-notes-panel-write-error]'),\n };\n };\n const onFocusOut = (event: FocusEvent) => {\n const to = event.relatedTarget;\n if (to instanceof Node) {\n if (!root.contains(to)) focusRef.current = null;\n return;\n }\n // No target: a click on empty space, or the row being removed. Decide\n // after the render: a removed row is rescued by then, and one still\n // here but unfocused was left by the user.\n const from = event.target;\n queueMicrotask(() => {\n const record = focusRef.current;\n if (\n record &&\n record.el === from &&\n record.el.isConnected &&\n document.activeElement !== record.el\n ) {\n focusRef.current = null;\n }\n });\n };\n root.addEventListener('focusin', onFocusIn);\n root.addEventListener('focusout', onFocusOut);\n return () => {\n root.removeEventListener('focusin', onFocusIn);\n root.removeEventListener('focusout', onFocusOut);\n };\n }, []);\n\n /* React puts focus back on a row it only moved (a re-sort), so only a\n control that left needs rescuing. Runs after every render, as a row\n can lose its controls without moving (the host marks it deleted). */\n useIsomorphicLayoutEffect(() => {\n const record = focusRef.current;\n if (!record || !rootRef.current) return;\n if (record.el.isConnected) {\n // Keep the position current while the row is still listed.\n const live = record.noteId\n ? liveIndexOf(\n liveIdsRef.current,\n orderedIdsRef.current,\n record.noteId,\n )\n : -1;\n if (live >= 0) record.index = live;\n return;\n }\n focusRef.current = null;\n const active = document.activeElement;\n if (active && active !== document.body) return;\n const moved = record.action ? inRow(record.noteId, record.action) : null;\n if (moved) moved.focus();\n else if (record.noteId) {\n landNear(nearTarget(record.index, record.action));\n } else if (record.el.hasAttribute('data-notes-panel-empty')) {\n // A note came back where the empty text held focus: a refused\n // delete, or a record the host kept.\n landNear(nearTarget(0, 'delete'));\n } else if (record.inWriteError) {\n // The error went from under its Close button without a dismiss: a\n // newer refusal replaced it, a write cleared it, or its note left.\n const close = writeErrorRef.current?.querySelector<HTMLElement>(\n '[data-alert-dismiss]',\n );\n const failure = shownFailureRef.current;\n if (close) close.focus();\n else landNear(failure ? failureTarget(failure) : null);\n }\n });\n\n /* ----- The addressed note (see `currentNoteId`) ----- */\n const currentItemRef = useRef<HTMLLIElement>(null);\n useEffect(() => {\n if (!currentNoteId) return;\n // `center`, not `nearest`: nearest parks the note flush against the edge\n // of the scroll region, which is the least readable place to land.\n currentItemRef.current?.scrollIntoView({ block: 'center' });\n currentItemRef.current?.focus();\n // `currentNoteKey` is in the deps so a REPEAT address of the same note\n // re-runs — see the prop doc. Addressing is a request, not a value.\n }, [currentNoteId, currentNoteKey]);\n\n /* ----- Agent handle (structural reads + composer / toggles) ----- */\n /* Stable for the life of the panel: everything is read through refs, so\n a registered handle never goes stale and never re-registers. */\n const onAddNoteRef = useRef(onAddNote);\n onAddNoteRef.current = onAddNote;\n const canAddClinicalRef = useRef(canAddClinicalNote);\n canAddClinicalRef.current = canAddClinicalNote;\n const currentNoteIdRef = useRef(currentNoteId);\n currentNoteIdRef.current = currentNoteId;\n const actionsRef = useRef<PanelActions | null>(null);\n actionsRef.current = { toggle: runToggle };\n\n const handle = useMemo<NotesPanelHandle>(\n () => ({\n // Ids + flags only — never the note body or author (both PHI).\n getNotes: () =>\n notesRef.current\n .filter((n) => !(n.id && writesRef.current.get(n.id)?.delete))\n .map((n) => {\n const entry = n.id ? writesRef.current.get(n.id) : undefined;\n return {\n id: n.id,\n pinned: entry?.pin?.next ?? !!n.pinned,\n flagged: entry?.flag?.next ?? !!n.flagged,\n clinical: !!n.clinical,\n deleted: !!n.deleted,\n };\n }),\n canAddNote: () => !!onAddNoteRef.current,\n canAddClinical: () => canAddClinicalRef.current,\n getCurrentNoteId: () => currentNoteIdRef.current ?? null,\n addNote: (submission) => {\n // A clinical submission requires the permission gate to be open.\n if (submission.clinical && !canAddClinicalRef.current) return;\n return onAddNoteRef.current?.(submission);\n },\n togglePin: (noteId) => agentToggle(actionsRef.current, noteId, 'pin'),\n toggleFlag: (noteId) => agentToggle(actionsRef.current, noteId, 'flag'),\n }),\n [],\n );\n useAgentRegistration(notesPanelAgent, handle, id);\n\n return (\n <section\n ref={rootRef}\n data-component=\"notes-panel\"\n data-component-id={id}\n aria-labelledby={ariaLabel ? undefined : headingId}\n aria-label={ariaLabel}\n className={[rootClass, className].filter(Boolean).join(' ')}\n {...rest}\n >\n {/* Shared rail header — pins to the top of the panel's scroll region\n while the composer + note timeline scroll beneath it. The rail\n injects the favourite / close actions via PanelHeaderActionsProvider. */}\n <PanelHeader\n title={heading}\n icon={<NotebookPen aria-hidden=\"true\" />}\n headingId={ariaLabel ? undefined : headingId}\n sticky\n divider\n />\n\n <div className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-md)] ds:p-[var(--spacing-md)]\">\n {onAddNote || editingId !== null ? (\n <div\n data-notes-panel-composer={editingId !== null ? 'edit' : 'add'}\n className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\"\n >\n {composerBefore}\n {composer === 'rich' ? (\n <RichTextEditor\n ref={editorRef}\n ariaLabel={composerLabel}\n placeholder={placeholder}\n toolbar={editorToolbar}\n minHeight=\"fill\"\n redactor={redactor}\n imageUploadUrl={imageUploadUrl}\n readOnly={pending}\n onChange={({ html }) => setDraft(html)}\n onRequestAiDraft={onRequestAiDraft}\n aiDraftFormat={aiDraftFormat}\n aiPrivacyNotice={aiPrivacyNotice}\n onDictate={onDictate}\n onProofread={onProofread}\n onAutoFormat={onAutoFormat}\n aiConsent={aiConsent}\n variables={variables}\n validateVariable={validateVariable}\n onVariableValidityChange={onVariableValidityChange}\n renderHelpMeWrite={renderHelpMeWrite}\n aiTemplates={aiTemplates}\n onAiApplied={onAiApplied}\n onUploadImage={onUploadImage}\n onAiCreditsExhausted={onAiCreditsExhausted}\n showExtensions={showExtensions}\n aiCreditsNotice={aiCreditsNotice}\n extensions={extensions}\n extensionContext={extensionContext}\n onExtensionRun={onExtensionRun}\n // The panel's own title is an h2 (PanelHeader below); the\n // gate's banner nests one level under it so the h2 → h3\n // sequence stays valid (axe heading-order) instead of\n // jumping straight to the banner's own h5 default.\n aiConsentHeadingLevel={3}\n />\n ) : (\n <TextArea\n value={draft}\n readOnly={pending}\n onChange={(event) => setDraft(event.target.value)}\n placeholder={placeholder}\n autoResize\n minRows={2}\n maxRows={6}\n aria-label={composerLabel}\n />\n )}\n <div\n className={[\n 'ds:flex ds:flex-wrap ds:items-center ds:gap-[var(--spacing-sm)]',\n clinicalToggleShown ? 'ds:justify-between' : 'ds:justify-end',\n ].join(' ')}\n >\n {clinicalToggleShown\n ? (() => {\n const clinicalDisabled = pending || !canAddClinicalNote;\n const clinicalReason = canAddClinicalNote\n ? undefined\n : (clinicalGatedReason ??\n t('notesPanel.clinicalGated', {\n defaultValue:\n 'You do not have permission to write clinical notes.',\n }));\n const clinicalSwitch = (\n <Switch\n size=\"sm\"\n label={t('notesPanel.clinicalToggle', {\n defaultValue: 'Clinical note',\n })}\n checked={clinical}\n onCheckedChange={setClinical}\n disabled={clinicalDisabled}\n />\n );\n // A disabled Radix Switch renders a native `disabled`\n // button, which drops out of the tab order — Tooltip\n // alone would leave the reason unreachable by keyboard.\n // The focusable wrapping span is the kit's documented\n // workaround (see tooltip.mdx / tooltip.stories.tsx).\n return clinicalDisabled && clinicalReason ? (\n <Tooltip label={clinicalReason}>\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- focusable wrapper so Tooltip works around the disabled Switch (which can't receive focus or hover events) */}\n <span tabIndex={0}>{clinicalSwitch}</span>\n </Tooltip>\n ) : (\n clinicalSwitch\n );\n })()\n : null}\n <span className=\"ds:flex ds:items-center ds:gap-[var(--spacing-xs)]\">\n {editingId !== null ? (\n <Button\n type=\"button\"\n size=\"sm\"\n intent=\"ghost\"\n onClick={cancelEdit}\n disabled={pending}\n >\n {t('notesPanel.cancelEdit', { defaultValue: 'Cancel' })}\n </Button>\n ) : null}\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={commit}\n disabled={!hasContent || editBlocked}\n loading={pending}\n >\n {editingId !== null\n ? t('notesPanel.saveEdit', { defaultValue: 'Save note' })\n : (addNoteLabel ??\n t('notesPanel.add', { defaultValue: 'Add note' }))}\n </Button>\n </span>\n </div>\n {addError ? (\n <Alert variant=\"error\">\n <Alert.Description>{addError}</Alert.Description>\n </Alert>\n ) : null}\n {composerAfter}\n </div>\n ) : null}\n\n {status === 'loading' && ordered.length === 0 ? (\n /* Note-shaped placeholders, not a spinner: the reader sees where\n the notes will land and how many to expect. The status text is\n for assistive tech only; sighted readers get the motion. */\n <div\n data-notes-panel-loading=\"\"\n aria-busy=\"true\"\n className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\"\n >\n <span role=\"status\" className=\"ds:sr-only\">\n {t('notesPanel.loading')}\n </span>\n {NOTE_SKELETON_LINES.map((lines, index) => (\n <Card key={index} variant=\"elevated\" aria-hidden=\"true\">\n <Card.Body>\n <div className=\"ds:flex ds:flex-col ds:gap-[var(--spacing-sm)]\">\n <div className=\"ds:flex ds:items-center ds:gap-[var(--spacing-sm)]\">\n <Skeleton\n variant=\"circular\"\n size=\"sm\"\n stagger={index * 2}\n />\n <div className=\"ds:flex ds:flex-1 ds:flex-col ds:gap-[var(--spacing-xs)]\">\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n stagger={index * 2}\n width=\"40%\"\n />\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n stagger={index * 2}\n width=\"25%\"\n />\n </div>\n </div>\n <Skeleton\n variant=\"text\"\n size=\"sm\"\n lines={lines}\n stagger={index * 2 + 1}\n />\n </div>\n </Card.Body>\n </Card>\n ))}\n </div>\n ) : status === 'error' ? (\n <Alert variant=\"error\">\n <Alert.Description>{t('notesPanel.loadError')}</Alert.Description>\n {onRetry ? (\n <Alert.Action>\n <Button intent=\"secondary\" size=\"sm\" onClick={onRetry}>\n {t('notesPanel.retry')}\n </Button>\n </Alert.Action>\n ) : null}\n </Alert>\n ) : null}\n\n {/* A refused delete, pin or flag, explained just above the list. */}\n {writeFailure && failureShown ? (\n <Alert\n key={writeFailure.seq}\n ref={writeErrorRef}\n variant=\"error\"\n dismissible\n onOpenChange={(open) => {\n if (!open) dismissWriteFailure(writeFailure);\n }}\n data-notes-panel-write-error={writeFailure.kind}\n >\n <Alert.Title as=\"p\">{failureTitle(writeFailure)}</Alert.Title>\n {writeFailure.message ? (\n <Alert.Description>{writeFailure.message}</Alert.Description>\n ) : null}\n </Alert>\n ) : null}\n {/* Always mounted, so a landed delete is heard. No role: hosts that\n query the panel's one status line keep finding it. */}\n <span\n aria-live=\"polite\"\n aria-atomic=\"true\"\n data-notes-panel-announcer=\"\"\n className=\"ds:sr-only\"\n >\n {announcement.text ? (\n <span key={announcement.seq}>{announcement.text}</span>\n ) : null}\n </span>\n\n {/* A refresh keeps the notes it has: real notes never give way to\n placeholders. The list is marked busy and says so to a reader. */}\n {status === 'loading' && ordered.length > 0 ? (\n <span role=\"status\" className=\"ds:sr-only\">\n {t('notesPanel.loading')}\n </span>\n ) : null}\n {ordered.length > 0 ? (\n <ul\n ref={reflowRef}\n aria-busy={status === 'loading' || undefined}\n className={`ds:m-0 ds:flex ds:list-none ds:flex-col ds:gap-[var(--spacing-sm)] ds:p-0 ${enterClass}`.trim()}\n >\n {ordered.map(({ actions, keptOnDelete, ...note }, index) => {\n const isCurrent =\n currentNoteId != null && note.id === currentNoteId;\n const noteId = note.id as string | undefined;\n const isEditing = noteId != null && editingId === noteId;\n const leaving = noteId != null && deleteExit.isLeaving(noteId);\n const write = noteId ? writes.get(noteId) : undefined;\n const inert = !!write?.delete;\n // A kept note waits in place for the host, and says so.\n const holding = inert && !!keptOnDelete;\n const editSaving = pending && isEditing;\n return (\n <li\n key={note.id ?? index}\n ref={isCurrent ? currentItemRef : undefined}\n data-note-id={noteId}\n // Focus lands on the row, not inside the card, so the\n // sentence below and `aria-current` are read out before the\n // note — and the rail's own Escape still bubbles.\n tabIndex={isCurrent ? -1 : undefined}\n aria-current={isCurrent ? 'true' : undefined}\n data-reflow-id={noteId}\n data-leaving={leaving ? '' : undefined}\n data-editing={isEditing ? '' : undefined}\n aria-busy={holding || undefined}\n className={[\n noteItemVariants({\n current: isCurrent,\n washed: isCurrent || isEditing,\n }),\n noteElevationClass,\n REFLOW_ROW_CLASS,\n leaving ? noteLeavingClass : '',\n ]\n .filter(Boolean)\n .join(' ')}\n >\n {isCurrent ? (\n <span className=\"ds:sr-only\">\n {t('notesPanel.current', {\n defaultValue: 'Current note',\n })}\n </span>\n ) : null}\n {/* aria-busy is not read out as a state, so a waiting\n row says it in words too. */}\n {holding ? (\n <span data-notes-panel-deleting=\"\" className=\"ds:sr-only\">\n {t('notesPanel.deleting')}\n </span>\n ) : null}\n {/* Elevated card per note; the list gap (not a separator)\n spaces them. Bodies clamp to five lines with read-more —\n except the addressed one, which is what the reader came\n for and opens in full. */}\n {/* Keyed on the address, so a repeat address of the same\n note remounts the layer and the wash plays again. Editing\n wins: a steady state must not pulse. */}\n {isEditing ? (\n <span\n aria-hidden=\"true\"\n data-notes-panel-wash=\"editing\"\n className={noteWashVariants({ state: 'editing' })}\n />\n ) : isCurrent ? (\n <span\n key={`${currentNoteId}:${currentNoteKey ?? ''}`}\n aria-hidden=\"true\"\n data-notes-panel-wash=\"addressed\"\n className={noteWashVariants({ state: 'addressed' })}\n />\n ) : null}\n <ClinicalNoteCard\n surface=\"elevated\"\n truncate={!isCurrent}\n headerActions={\n <>\n {noteActions\n ? noteActions(\n { ...note, actions, keptOnDelete },\n { deleting: inert },\n )\n : null}\n {onEditNote &&\n noteId &&\n !note.deleted &&\n actions?.edit !== false ? (\n <IconButton\n icon={<Pencil />}\n intent=\"ghost\"\n size=\"sm\"\n aria-label={t('notesPanel.editNamed', {\n date: noteStamp(note),\n defaultValue: 'Edit note · {{date}}',\n })}\n tooltip={t('notesPanel.edit', {\n defaultValue: 'Edit note',\n })}\n aria-pressed={editingId === noteId}\n disabled={pending || inert}\n data-notes-panel-edit=\"\"\n data-note-action=\"edit\"\n onClick={() =>\n editingId === noteId\n ? cancelEdit()\n : startEdit(note)\n }\n />\n ) : null}\n {onDeleteNote &&\n noteId &&\n !note.deleted &&\n actions?.delete !== false ? (\n <IconButton\n icon={<Trash2 />}\n intent=\"ghost\"\n size=\"sm\"\n aria-label={t('notesPanel.deleteNamed', {\n date: noteStamp(note),\n defaultValue: 'Delete note · {{date}}',\n })}\n tooltip={t('notesPanel.delete', {\n defaultValue: 'Delete note',\n })}\n data-note-action=\"delete\"\n // aria-disabled, not disabled: focus can wait\n // here while the host answers.\n aria-disabled={holding || editSaving || undefined}\n aria-busy={holding || undefined}\n onClick={() => handleDeleteNote(noteId)}\n />\n ) : null}\n </>\n }\n {...note}\n pinned={effectivePinned(note)}\n flagged={effectiveFlagged(note)}\n pinPending={!!write?.pin || inert}\n flagPending={!!write?.flag || inert}\n onTogglePin={\n onTogglePin &&\n noteId &&\n actions?.pin !== false &&\n !note.deleted\n ? () => runToggle(noteId, 'pin')\n : undefined\n }\n onToggleFlag={\n onToggleFlag && noteId && !note.deleted\n ? () => runToggle(noteId, 'flag')\n : undefined\n }\n />\n </li>\n );\n })}\n </ul>\n ) : status !== 'ready' ? null : (\n /* Where focus lands, from script, when the last note leaves. */\n <div data-notes-panel-empty=\"\" className={focusTargetClass}>\n {emptyState ?? (\n <p className=\"ds:m-0 type-body-sm ds:text-[color:var(--muted-foreground)]\">\n {t('notesPanel.empty', { defaultValue: 'No notes yet.' })}\n </p>\n )}\n </div>\n )}\n </div>\n\n {onDeleteNote && confirmDelete ? (\n <Dialog\n open={dialogOpen}\n onOpenChange={(next) => !next && setPendingDelete(null)}\n >\n <Dialog.Content\n variant=\"alert\"\n size=\"sm\"\n onCloseAutoFocus={handleDialogCloseFocus}\n >\n <Dialog.Header>\n <Dialog.Title>\n {t('notesPanel.deleteConfirmTitle', {\n defaultValue: 'Delete this note?',\n })}\n </Dialog.Title>\n </Dialog.Header>\n <Dialog.Body>\n <Dialog.Description>\n {t('notesPanel.deleteConfirmBody', {\n defaultValue: 'The note will be removed from the record.',\n })}\n </Dialog.Description>\n </Dialog.Body>\n <Dialog.Footer>\n <Dialog.Close asChild>\n <Button\n intent=\"secondary\"\n size=\"sm\"\n onClick={() => setPendingDelete(null)}\n >\n {t('notesPanel.deleteConfirmCancel', {\n defaultValue: 'Cancel',\n })}\n </Button>\n </Dialog.Close>\n <Button\n intent=\"destructive\"\n size=\"sm\"\n onClick={confirmDeleteNote}\n >\n {t('notesPanel.deleteConfirmAction', {\n defaultValue: 'Delete',\n })}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n </Dialog>\n ) : null}\n </section>\n );\n },\n);\n"],"names":["notesPanelAgent","handle","args","NOTE_CONTENT_ABOVE_WASH","noteItemVariants","cva","noteWashVariants","focusTargetClass","rootClass","noteLeavingClass","noteElevationClass","NOTE_SKELETON_LINES","hasRichContent","html","agentToggle","actions","noteId","kind","attempt","refusal","handledRejection","EMPTY_WRITES","EMPTY_HIDDEN","sigOf","notes","n","isThenable","value","liveIndexOf","liveIds","orderedIds","live","at","liveSet","id","focusFromScript","el","release","NotesPanel","forwardRef","onAddNote","status","onRetry","currentNoteId","currentNoteKey","composer","editorToolbar","redactor","imageUploadUrl","showClinicalToggle","canAddClinicalNote","clinicalGatedReason","defaultClinical","onRequestAiDraft","aiDraftFormat","aiPrivacyNotice","onDictate","onProofread","onAutoFormat","aiConsent","variables","validateVariable","onVariableValidityChange","renderHelpMeWrite","aiTemplates","onAiApplied","onUploadImage","onAiCreditsExhausted","showExtensions","aiCreditsNotice","extensions","extensionContext","onExtensionRun","composerBefore","composerAfter","onTogglePin","onToggleFlag","noteActions","onEditNote","editClinical","onDeleteNote","onWriteError","confirmDelete","title","composerPlaceholder","addNoteLabel","emptyState","className","ariaLabel","rest","ref","t","i18n","useTranslation","editorRef","useRef","draft","setDraft","useState","clinical","setClinical","pending","setPending","addError","setAddError","editingId","setEditingId","editingIdRef","followedLoading","enterClass","CONTENT_ENTER_CLASS","heading","headingId","useId","placeholder","composerLabel","hasContent","notesRef","writes","setWritesState","writesRef","hidden","setHiddenState","hiddenRef","mountedRef","useEffect","rootRef","onWriteErrorRef","panelShown","useCallback","root","judgementsRef","judgeSeq","setJudgeSeq","judgeLater","judge","seq","queued","updatePending","edit","next","updateHidden","writeOf","_a","setWrite","write","m","entry","deleting","commit","rich","content","reset","edited","refused","error","draftKept","getErrorMessage","result","clinicalToggleShown","editBlocked","noteStamp","note","startEdit","_b","_c","_d","cancelEdit","editingStillThere","effectivePinned","effectiveFlagged","ordered","a","b","liveIdsRef","orderedIdsRef","resolvedTheme","useTheme","reduceMotion","reflowRef","useListReflow","deleteExit","useExitTransition","writeFailure","setWriteFailure","failureSeqRef","writeEpochRef","clearForWrite","reportFailure","current","epoch","shown","failureTitle","failure","date","failureShown","shownFailureRef","announcement","setAnnouncement","announceTimerRef","announce","text","prev","announceDeleted","loadEdgesRef","prevStatusRef","reconcile","list","sig","byId","dropped","hostAgrees","listMoved","deletes","set","settle","rollback","notesSig","useMemo","runToggle","handler","refuse","hostPromise","runDelete","pendingDelete","setPendingDelete","deleteFocusRef","handleDeleteNote","confirmDeleteNote","index","dialogOpen","useImperativeHandle","inRow","action","nearTarget","ids","landLast","last","landNear","target","handleDialogCloseFocus","event","record","trigger","writeErrorRef","failureTarget","dismissWriteFailure","focusRef","onFocusIn","onFocusOut","to","from","useIsomorphicLayoutEffect","active","moved","close","currentItemRef","onAddNoteRef","canAddClinicalRef","currentNoteIdRef","actionsRef","submission","useAgentRegistration","jsxs","jsx","PanelHeader","NotebookPen","RichTextEditor","TextArea","clinicalDisabled","clinicalReason","clinicalSwitch","Switch","Tooltip","Button","Alert","lines","Card","Skeleton","open","keptOnDelete","isCurrent","isEditing","leaving","inert","holding","editSaving","REFLOW_ROW_CLASS","ClinicalNoteCard","Fragment","IconButton","Pencil","Trash2","Dialog"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBO,MAAMA,KAAkD;AAAA,EAC7D,IAAI;AAAA;AAAA;AAAA,EAGJ,cAAc,CAAC,QAAQ;AAAA,EACvB,OAAO;AAAA,IACL,OAAO;AAAA,MACL,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACC,MAAWA,EAAO,SAAA;AAAA,IAAS;AAAA,IAEpC,gBAAgB;AAAA,MACd,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACA,MAAWA,EAAO,eAAA;AAAA,IAAe;AAAA,IAE1C,eAAe;AAAA,MACb,MAAM;AAAA,MACN,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,MAAM,CAACA,MAAWA,EAAO,iBAAA;AAAA,IAAiB;AAAA,EAC5C;AAAA,EAEF,SAAS;AAAA,IACP,UAAU;AAAA;AAAA,MAER,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,YAAY;AAAA,QACV,MAAM;AAAA,QACN,YAAY;AAAA,UACV,SAAS;AAAA,YACP,MAAM;AAAA,YACN,aACE;AAAA,UAAA;AAAA,UAEJ,UAAU;AAAA,YACR,MAAM;AAAA,YACN,aACE;AAAA,UAAA;AAAA,QACJ;AAAA,QAEF,UAAU,CAAC,WAAW,UAAU;AAAA,MAAA;AAAA,MAElC,WAAW;AAAA,MACX,gBAAgB;AAAA,MAChB,aACE;AAAA,MACF,UAAU;AAAA,QACR;AAAA,UACE,MAAM,EAAE,SAAS,iCAAiC,UAAU,GAAA;AAAA,UAC5D,MAAM;AAAA,QAAA;AAAA,MACR;AAAA,MAEF,QAAQ,CAACA,GAAQC,MACRD,EAAO,QAAQC,CAAI;AAAA,IAC5B;AAAA,IAEF,YAAY;AAAA;AAAA,MAEV,QAAQ;AAAA,MAC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