{"version":3,"file":"chunk-Editable.mjs","names":["useEditable","useMachine","createContext","useEditable","EditablePrimitive","Icon.Icon","_Fragment"],"sources":["../../src/components/Editable/useEditable.ts","../../src/components/Editable/Editable.tsx"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport { type UseEditableReturn as EditableApi, useEditable as useMachine } from '@ark-ui/react/editable';\nimport { type KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\n// The inline-edit state machine — `@ark-ui/react`'s Editable (zag) — behind DXOS's own contract.\n//\n// `Editable` renders an `<input>`, but a markdown field wants a CodeMirror editor and a rendered\n// preview — and those live in packages that depend on this one, so they cannot be reached from\n// here. Both flavours therefore share the behaviour through this hook rather than the component:\n// one definition of what commits, what reverts, and what opens.\n\n/** What turns the preview into an editor. `dblclick` suits rows whose single click already selects. */\nexport type EditableActivation = 'click' | 'dblclick' | 'focus' | 'none';\n\n/** What an interaction outside does with the pending edit. `Escape` always reverts and `Enter` always commits. */\nexport type EditableBlurBehavior = 'commit' | 'revert';\n\nexport type UseEditableOptions = {\n  /** Current text (controlled). */\n  value?: string;\n  /** Initial text when uncontrolled. */\n  defaultValue?: string;\n  /** Called when an edit is committed — never while typing, so a keystroke is not a write. */\n  onValueChange?: (value: string) => void;\n  activation?: EditableActivation;\n  blurBehavior?: EditableBlurBehavior;\n  disabled?: boolean;\n  /** Shown, dimmed, when the value is empty. */\n  placeholder?: string;\n  /** Editing state (controlled); pair with `onEditingChange` to drive it from outside. */\n  editing?: boolean;\n  onEditingChange?: (editing: boolean) => void;\n};\n\n/** Props for whatever draws the resting state, so every flavour opens the same ways. */\nexport type EditablePreviewBinding = ReturnType<EditableApi['getPreviewProps']>;\n\n/**\n * What the preview needs beyond the machine's own props. Empty when the machine already answers the\n * keyboard on its own.\n */\nexport type EditableActivationBinding = {\n  role?: 'button';\n  onKeyDown?: (event: KeyboardEvent) => void;\n};\n\nexport type UseEditableReturn = {\n  value: string;\n  /** The pending text; separate from `value` so `Escape` has something to revert to. */\n  draft: string;\n  editing: boolean;\n  disabled: boolean;\n  setDraft: (draft: string) => void;\n  edit: () => void;\n  /** Commits `next` when given: a caller that already holds the text must not race the draft state. */\n  commit: (next?: string) => void;\n  revert: () => void;\n  previewProps: EditablePreviewBinding;\n  /**\n   * The keyboard door, for a part that renders the machine's own preview and so already has the\n   * rest of {@link UseEditableReturn.previewProps} applied to it.\n   */\n  activationProps: EditableActivationBinding;\n  /** The machine itself, for the parts that render Ark's own anatomy. */\n  api: EditableApi;\n};\n\n/**\n * Inline edit: text that becomes editable in place, with a committed value distinct from the\n * pending one.\n *\n * The machine owns the pending text, which state the field is in, the activation gesture, `Enter` /\n * `Escape`, and what an interaction outside the field does with the edit. This owns the thing it has\n * no notion of — the committed value — so `onValueChange` fires when an edit lands rather than on\n * every keystroke.\n *\n * **The value.** Controlled with `value`, uncontrolled with `defaultValue`; `draft` is the pending\n * text either way and only ever reaches `onValueChange` on a commit. A controlled host that does not\n * echo a commit back is refusing it, and the field returns to the value the host still holds.\n *\n * **Who owns the edit state.** Left alone, the machine does: the field opens on `activation` and\n * closes on `Enter`, `Escape`, or an interaction outside it. Passing `editing` takes that ownership,\n * which is what a pane editor does — the pane IS the editor, so it is held open and never closes.\n * The machine then treats a submit as a request to whoever holds the prop and announces only the\n * state change, so `commit` and `revert` here act on it directly rather than waiting to be told.\n * Either way an edit is delivered exactly once.\n *\n * **Commit and revert.** `commit` writes the pending text — or the text it is handed, for a caller\n * that already holds it and must not race the draft. `revert` restores the last committed text and\n * discards the rest, including on a field that was empty when it opened, which the machine alone\n * would leave holding the discarded text.\n */\nexport const useEditable = ({\n  value: valueProp,\n  defaultValue = '',\n  onValueChange,\n  activation = 'click',\n  blurBehavior = 'commit',\n  disabled = false,\n  placeholder,\n  editing: editingProp,\n  onEditingChange,\n}: UseEditableOptions): UseEditableReturn => {\n  const [valueState, setValueState] = useState(defaultValue);\n  const value = valueProp ?? valueState;\n\n  // The machine's callbacks are handed to it once, so they read the committed text through a ref\n  // rather than closing over whichever render created them.\n  const committed = useRef(value);\n  committed.current = value;\n  const apiRef = useRef<EditableApi | null>(null);\n  const onValueChangeRef = useRef(onValueChange);\n  onValueChangeRef.current = onValueChange;\n\n  /**\n   * The one way an edit lands, whether the machine announced it or a caller asked for it directly.\n   *\n   * Idempotent on the text it already holds, so the two routes can both run in a tick without\n   * writing twice: `committed` is advanced here rather than waiting for the render that reads the\n   * prop back.\n   */\n  const deliver = useCallback((next: string) => {\n    if (next === committed.current) {\n      return;\n    }\n    committed.current = next;\n    setValueState(next);\n    onValueChangeRef.current?.(next);\n  }, []);\n\n  const api = useMachine({\n    defaultValue: value,\n    placeholder,\n    activationMode: activation,\n    submitMode: blurBehavior === 'commit' ? 'both' : 'enter',\n    // Caret at the end rather than a selection: opening a title is usually the start of amending it,\n    // and a select-all turns the next keystroke into a silent delete of the whole value.\n    selectOnFocus: false,\n    disabled,\n    edit: editingProp,\n    onEditChange: ({ edit }) => onEditingChange?.(edit),\n    onValueCommit: ({ value: next }) => deliver(next),\n    // The machine's own revert keeps whatever it holds when the text it opened with was empty, so\n    // `Escape` on a field showing its placeholder would keep the discarded text instead. Restored\n    // inside the machine's own transition rather than left to the reconciling effect below, which\n    // would catch it a render later — after the discarded text had been drawn once.\n    onValueRevert: () => apiRef.current?.setValue(committed.current),\n  });\n  apiRef.current = api;\n\n  // A value that changed elsewhere — a peer's edit, a controlled parent refusing a commit — has to\n  // reach the machine, which otherwise holds the one it was seeded with. Never mid-edit: that would\n  // overwrite what is being typed.\n  useEffect(() => {\n    if (!api.editing && api.value !== value) {\n      api.setValue(value);\n    }\n  }, [api, value]);\n\n  const setDraft = useCallback((draft: string) => api.setValue(draft), [api]);\n\n  /**\n   * Commits, and delivers the edit rather than trusting the machine to announce it.\n   *\n   * A field whose editing state is controlled never leaves edit on its own, so the machine treats\n   * `SUBMIT` as a request to the host and reports only the state change — `onValueCommit` never\n   * runs. A pane held open that way is the whole point of driving `editing` from outside, and its\n   * text would never be written.\n   */\n  const commit = useCallback(\n    (next?: string) => {\n      const text = next ?? api.value;\n      api.setValue(text);\n      api.submit();\n      deliver(text);\n    },\n    [api, deliver],\n  );\n\n  /** Reverts for the same reason `commit` delivers: a controlled field never reaches the machine's own cancel. */\n  const revert = useCallback(() => {\n    api.setValue(committed.current);\n    api.cancel();\n  }, [api]);\n\n  // A gesture the machine only takes from a pointer needs the same door for a keyboard reader. Its\n  // own keyboard answer is `focus` activation, which is wrong for a field a single click opens —\n  // tabbing across a list of them would put every row into edit on the way past.\n  const activationProps = useMemo<EditableActivationBinding>(() => {\n    if (activation !== 'click' && activation !== 'dblclick') {\n      return {};\n    }\n\n    return {\n      role: 'button',\n      onKeyDown: (event: KeyboardEvent) => {\n        if (!event.defaultPrevented && (event.key === 'Enter' || event.key === ' ')) {\n          event.preventDefault();\n          api.edit();\n        }\n      },\n    };\n  }, [activation, api]);\n\n  const previewProps = useMemo<EditablePreviewBinding>(\n    () => ({\n      ...api.getPreviewProps(),\n      // The machine names the preview \"edit\", which is what the gesture does rather than what the\n      // field holds — in a list of rows that is every row with the same name.\n      'aria-label': undefined,\n      ...activationProps,\n    }),\n    [api, activationProps],\n  );\n\n  return {\n    value,\n    draft: api.value,\n    editing: api.editing,\n    disabled,\n    setDraft,\n    edit: api.edit,\n    commit,\n    revert,\n    previewProps,\n    activationProps,\n    api,\n  };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { Editable as EditablePrimitive, useEditableContext } from '@ark-ui/react/editable';\nimport React, { type ComponentPropsWithRef, type PropsWithChildren, forwardRef, useEffect, useRef } from 'react';\n\nimport { createContext } from '@dxos/react-hooks';\nimport { mx } from '@dxos/ui-theme';\nimport { type ThemedClassName } from '@dxos/ui-types';\n\nimport { recipes } from '../../recipes.ts';\nimport * as Icon from '../Icon/Icon.tsx';\nimport { type EditableActivationBinding, type UseEditableOptions, useEditable } from './useEditable.ts';\n\nconst EDITABLE_NAME = 'Editable.Root';\nconst EDITABLE_PREVIEW_NAME = 'Editable.Preview';\nconst EDITABLE_INPUT_NAME = 'Editable.Input';\n\n// The keyboard door onto the preview depends on the activation gesture, which the root is given and the machine the\n// parts read does not expose.\nconst [EditableActivationProvider, useEditableActivation] = createContext<EditableActivationBinding>(EDITABLE_NAME);\n\n// A controlled field's submit never reaches the machine's commit callback, so Save commits through the hook.\nconst [EditableCommitProvider, useEditableCommit] = createContext<{ commit: () => void }>(EDITABLE_NAME);\n\n//\n// Root\n//\n\ntype EditableRootProps = ThemedClassName<\n  PropsWithChildren<UseEditableOptions & Omit<ComponentPropsWithRef<'div'>, keyof UseEditableOptions | 'children'>>\n>;\n\n/** Seeds the machine (through `useEditable`) and lays Preview and Input into one grid cell, so the swap moves nothing. */\nconst EditableRoot = forwardRef<HTMLDivElement, EditableRootProps>(\n  (\n    {\n      children,\n      classNames,\n      value,\n      defaultValue,\n      onValueChange,\n      activation,\n      blurBehavior,\n      disabled,\n      placeholder,\n      editing,\n      onEditingChange,\n      ...props\n    },\n    forwardedRef,\n  ) => {\n    const { api, activationProps, commit } = useEditable({\n      value,\n      defaultValue,\n      onValueChange,\n      activation,\n      blurBehavior,\n      disabled,\n      placeholder,\n      editing,\n      onEditingChange,\n    });\n\n    return (\n      <EditablePrimitive.RootProvider\n        {...props}\n        value={api}\n        className={mx(recipes.editable(), classNames)}\n        ref={forwardedRef}\n      >\n        <EditableActivationProvider {...activationProps}>\n          <EditableCommitProvider commit={commit}>{children}</EditableCommitProvider>\n        </EditableActivationProvider>\n      </EditablePrimitive.RootProvider>\n    );\n  },\n);\n\nEditableRoot.displayName = EDITABLE_NAME;\n\n//\n// Preview\n//\n\ntype EditablePreviewProps = ThemedClassName<Omit<ComponentPropsWithRef<'span'>, 'children'>>;\n\n/** The static text and the activation affordance; hidden by the machine while editing. */\nconst EditablePreview = forwardRef<HTMLSpanElement, EditablePreviewProps>(({ classNames, ...props }, forwardedRef) => {\n  const { valueText, edit } = useEditableContext();\n  const { role, onKeyDown } = useEditableActivation(EDITABLE_PREVIEW_NAME);\n\n  return (\n    <EditablePrimitive.Preview\n      // Ahead of the spread so a caller can still name it: the machine names it \"edit\", what the gesture does rather\n      // than what the field holds, which in a list of rows is every row's name.\n      aria-label={undefined}\n      // The machine opens on a pointer gesture only; without this the preview is a tab stop that answers nothing.\n      role={role}\n      onKeyDown={onKeyDown}\n      {...props}\n      className={mx(recipes.editablePreview(), classNames)}\n      ref={forwardedRef}\n    >\n      <span className={recipes.editablePreviewText()}>{valueText}</span>\n      {/* The pencil is a door of its own: one click opens the field whatever gesture the preview takes (a double-click\n          in a list, where a single click selects the row). */}\n      <Icon.Icon\n        icon='ph--pencil-simple--regular'\n        classNames={recipes.editablePreviewIcon()}\n        data-testid='editable.edit'\n        // A disabled field hides the pencil (`editable.css`), so it takes no click.\n        onClick={(event) => {\n          event.stopPropagation();\n          edit();\n        }}\n      />\n    </EditablePrimitive.Preview>\n  );\n});\n\nEditablePreview.displayName = EDITABLE_PREVIEW_NAME;\n\n//\n// Input\n//\n\ntype EditableInputProps = ThemedClassName<Omit<ComponentPropsWithRef<'input'>, 'value' | 'onChange' | 'placeholder'>>;\n\n/** The field shown while editing, focused with the caret at the end, with a save button at its end. */\nconst EditableInput = forwardRef<HTMLInputElement, EditableInputProps>(({ classNames, ...props }, forwardedRef) => {\n  const { editing } = useEditableContext();\n  const { commit } = useEditableCommit(EDITABLE_INPUT_NAME);\n  const localRef = useRef<HTMLInputElement | null>(null);\n\n  // The machine focuses the input but leaves the caret where the browser puts it, which from the keyboard is the start.\n  useEffect(() => {\n    const element = localRef.current;\n    if (editing && element) {\n      element.focus();\n      const end = element.value.length;\n      element.setSelectionRange(end, end);\n    }\n  }, [editing]);\n\n  return (\n    <>\n      <EditablePrimitive.Input\n        {...props}\n        className={mx(recipes.editableInput(), classNames)}\n        ref={(element) => {\n          localRef.current = element;\n          // Typed `unknown`: `ForwardedRef`'s callback is declared void, but React 19 may return a cleanup.\n          const cleanup: unknown = typeof forwardedRef === 'function' ? forwardedRef(element) : undefined;\n          if (forwardedRef && typeof forwardedRef !== 'function') {\n            forwardedRef.current = element;\n          }\n          return () => {\n            localRef.current = null;\n            if (typeof cleanup === 'function') {\n              cleanup();\n            }\n          };\n        }}\n      />\n      {/* Saves the edit, at the input's end in the same cell; the machine hides it while not editing. */}\n      <EditablePrimitive.SubmitTrigger\n        className={recipes.editableSubmit()}\n        aria-label='Save'\n        data-testid='editable.save'\n        onClick={() => commit()}\n      >\n        <Icon.Icon icon='ph--check--bold' />\n      </EditablePrimitive.SubmitTrigger>\n    </>\n  );\n});\n\nEditableInput.displayName = EDITABLE_INPUT_NAME;\n\nexport { EditableInput as Input, EditablePreview as Preview, EditableRoot as Root };\nexport type { EditableInputProps as InputProps, EditablePreviewProps as PreviewProps, EditableRootProps as RootProps };\nexport * from './useEditable.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAaA,iBAAe,EAC1B,OAAO,WACP,eAAe,IACf,eACA,aAAa,SACb,eAAe,UACf,WAAW,OACX,aACA,SAAS,aACT,sBAC2C;CAC3C,MAAM,CAAC,YAAY,iBAAiB,SAAS,YAAY;CACzD,MAAM,QAAQ,aAAa;CAI3B,MAAM,YAAY,OAAO,KAAK;CAC9B,UAAU,UAAU;CACpB,MAAM,SAAS,OAA2B,IAAI;CAC9C,MAAM,mBAAmB,OAAO,aAAa;CAC7C,iBAAiB,UAAU;;;;;;;;CAS3B,MAAM,UAAU,aAAa,SAAiB;EAC5C,IAAI,SAAS,UAAU,SACrB;EAEF,UAAU,UAAU;EACpB,cAAc,IAAI;EAClB,iBAAiB,UAAU,IAAI;CACjC,GAAG,CAAC,CAAC;CAEL,MAAM,MAAMC,YAAW;EACrB,cAAc;EACd;EACA,gBAAgB;EAChB,YAAY,iBAAiB,WAAW,SAAS;EAGjD,eAAe;EACf;EACA,MAAM;EACN,eAAe,EAAE,WAAW,kBAAkB,IAAI;EAClD,gBAAgB,EAAE,OAAO,WAAW,QAA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