Skip to content

AI-native design editor. Open-source Figma alternative.

1.8 KB
Raw Blame
import { watch } from 'vue'
import type { ShallowRef } from 'vue'

import type { Editor } from '@open-pencil/core'

const CANVAS_TEXT_INPUT = 'data-canvas-text-input'

/**
 * Whether `element` is the hidden textarea the canvas text editor types through. Focus can leave
 * it for a page field while the text edit stays open, so callers ask this rather than whether a
 * text edit is active.
 */
export function isCanvasTextInput(element: Element | null): boolean {
  return element?.hasAttribute(CANVAS_TEXT_INPUT) ?? false
}

export function createHiddenTextArea() {
  const textarea = document.createElement('textarea')
  textarea.setAttribute(CANVAS_TEXT_INPUT, '')
  textarea.setAttribute('aria-hidden', 'true')
  textarea.tabIndex = -1
  textarea.className = 'fixed left-0 top-0 h-px w-px opacity-0'
  document.body.appendChild(textarea)
  return textarea
}

export function focusTextAreaOnCanvasPointerDown(
  textareaRef: ShallowRef<HTMLTextAreaElement | null>,
  store: Editor
) {
  if (store.state.editingTextId && textareaRef.value) {
    requestAnimationFrame(() => textareaRef.value?.focus())
  }
}

export function useTextEditingSession({
  store,
  textareaRef,
  resetBlink,
  stopBlink,
  resetComposition,
  isEnabled
}: {
  store: Editor
  textareaRef: ShallowRef<HTMLTextAreaElement | null>
  resetBlink: () => void
  stopBlink: () => void
  resetComposition: () => void
  isEnabled?: () => boolean
}) {
  watch(
    () => [store.state.editingTextId, isEnabled?.() ?? true] as const,
    ([id, enabled], _, onCleanup) => {
      if (!enabled) return
      if (id) {
        const el = createHiddenTextArea()
        textareaRef.value = el
        el.focus()
        resetBlink()

        onCleanup(() => {
          stopBlink()
          el.remove()
          textareaRef.value = null
          resetComposition()
        })
      }
    }
  )
}