etc

Tiptap editor Custom Command(Code editor withSlash Commands)

gommmmm 2025. 4. 4. 16:41

 

tiptap 에디터 사용중 콜론(:)을 입력해서 커스텀 이모지를 등록해야할 일이 생겼다

공식문서의 Slash Commands를 참고했다

 

https://tiptap.dev/docs/examples/experiments/slash-commands

 

Slash Commands Extension | Tiptap Editor Docs

Use the Slash Commands extension in Tiptap to add a toolbar via / that pops up at the slash position. Learn more in our docs!

tiptap.dev

 

사용하는 extension에 Commands 추가!

CommangsSuggestion, Commands는 공식문서에 있는걸 우선 그대로 가져왔다.

Input.vue

import CommandsSuggestion from '...'
import Commands from '...'

const editor = new Editor({
  extensions: [
    OrderedList,
    BulletList,
    ...
    Commands.configure({
      suggestion: CommandsSuggestion,
    }),
  ],
})

 

공식문서랑 다른 부분만 적어왔다

commands.js

import { PluginKey } from '@tiptap/pm/state'
export const EmojiCommandPluginKey = new PluginKey('emojiCommand')
addOptions() {
    return {
      suggestion: {
        char: ':',
      },
    }
  },
addProseMirrorPlugins() {
    return [
      Suggestion({
        pluginKey: EmojiCommandPluginKey,
      }),
    ]
  },

나는 슬래쉬가 아닌 콜론으로 사용할거니까 char 바꿔주고, Suggestion 안에 pluginKey 추가했다. 

마우스로는 되는데 키보드로 고르고 엔터칠때 제어가 안돼서 추가했다. 아래에서 쓸 예정

 

다시 돌아와서

Input.vue

import { EmojiCommandPluginKey } from '...'

const keyboardShortcuts = {
  Enter: ({ editor }) => {
    const state = editor.state
    const colonsCommandActive = EmojiCommandPluginKey.getState(state)?.active
    if (colonsCommandActive) return false // 기본 Enter 이벤트 차단
    ...
  },
}

커맨드 창이 열려있을 경우 기본 엔터 로직(텍스트 전송)이 실행되지 않도록 막았다.

 

마지막으로 하나 더

command-suggestion.js

export default {
  render: () => {
    return {
      onUpdate(props) {
        if (props.items.length === 0) {
          popup[0].hide()
          return
        }
        if (props.items.length > 0) {
          popup[0].show()
        }
        component.updateProps(props)
        if (!props.clientRect) {
          return
        }
        popup[0].setProps({
          getReferenceClientRect: props.clientRect,
        })
      },
     ...
    }
  },
}

일치하는 아이템이 없으면 컴포넌트가 뜨지않도록 숨기는 코드를 추가했다

 

 

별거 아니지만 정보가 없어서 기록했다

누군가에게 도움이되길!