---
title: "EditorDragHandle"
description: "Ручка для перетаскивания, с помощью которой блоки редактора переупорядочивают и выделяют."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/editor-drag-handle"
---
# EditorDragHandle

> Ручка для перетаскивания, с помощью которой блоки редактора переупорядочивают и выделяют.

## Использование

Компонент EditorDragHandle добавляет перетаскивание для изменения порядка блоков редактора. Он использует пакет `@tiptap/extension-drag-handle-vue-3`.

> [!CAUTION]
> Компонент нужно использовать в слоте по умолчанию компонента [Editor](https://b24-ui.bx-shef.by/raw/docs/components/editor.md), чтобы получить доступ к экземпляру редактора.

Компонент расширяет [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md), поэтому ему можно передать любое свойство: `color`, `size` и другие.

```vue [EditorDragHandleExample.vue]
<script setup lang="ts">
const value = ref(`# Ручка перетаскивания

Наведите курсор на левую сторону блока, чтобы появилась ручка перетаскивания, и меняйте порядок блоков.`)
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    class="w-full min-h-21"
  >
    <B24EditorDragHandle :editor="editor" />
  </B24Editor>
</template>
```

> [!NOTE]
> See: https://tiptap.dev/docs/editor/extensions/functionality/drag-handle-vue
> Подробнее о расширении Drag Handle — в документации TipTap.

### Иконка

Пропс `icon` задаёт иконку ручки.

```vue
<script setup lang="ts">
import DragLIcon from '@bitrix24/b24icons-vue/outline/DragLIcon'
</script>

<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorDragHandle :editor="editor" :icon="DragLIcon" />
  </B24Editor>
</template>
```

### Параметры

Пропс `options` настраивает позиционирование с помощью [параметров Floating UI](https://floating-ui.com/docs/computeposition#options).

> [!NOTE]
> Смещение вычисляется автоматически: у небольших блоков ручка центрируется, у высоких — выравнивается по верхнему краю.

```vue
<template>
  <B24Editor v-slot="{ editor }">
    <B24EditorDragHandle
      :editor="editor"
      :options="{
        placement: 'left'
      }"
    />
  </B24Editor>
</template>
```

## Примеры

### С выпадающим меню

В слот по умолчанию можно добавить [DropdownMenu](https://b24-ui.bx-shef.by/raw/docs/components/dropdown-menu.md) с действиями над блоком: дублировать, удалить, переместить вверх или вниз, преобразовать в другой тип.

Событие `@node-change` отслеживает блок под курсором и его позицию, а `editor.chain().setMeta('lockDragHandle', open).run()` фиксирует положение ручки, пока меню открыто.

```vue [EditorDragHandleDropdownMenuExample.vue]
<script setup lang="ts">
import { upperFirst } from 'scule'
import type { DropdownMenuItem } from '@bxshefby/b24ui-nuxt'
import { mapEditorItems } from '@bxshefby/b24ui-nuxt/utils/editor'
import type { Editor, JSONContent } from '@tiptap/vue-3'
import DragLIcon from '@bitrix24/b24icons-vue/outline/DragLIcon'
import RepeatIcon from '@bitrix24/b24icons-vue/outline/RepeatIcon'
import ResumeIcon from '@bitrix24/b24icons-vue/outline/ResumeIcon'
import TextIcon from '@bitrix24/b24icons-vue/outline/TextIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import QuoteIcon from '@bitrix24/b24icons-vue/outline/QuoteIcon'
import CodeIcon from '@bitrix24/b24icons-vue/common-service/CodeIcon'
import CopyIcon from '@bitrix24/b24icons-vue/outline/CopyIcon'
import CopyFileIcon from '@bitrix24/b24icons-vue/crm/CopyFileIcon'
import ArrowTopLIcon from '@bitrix24/b24icons-vue/outline/ArrowTopLIcon'
import ArrowDownLIcon from '@bitrix24/b24icons-vue/outline/ArrowDownLIcon'
import TrashcanIcon from '@bitrix24/b24icons-vue/outline/TrashcanIcon'

const value = ref(`Наведите курсор на левую сторону, чтобы увидеть ручку перетаскивания и кнопку меню.

Нажмите на меню, чтобы увидеть действия с блоком. Попробуйте продублировать или удалить блок.`)

const selectedNode = ref<{ node: JSONContent, pos: number }>()

const items = (editor: Editor): DropdownMenuItem[][] => {
  if (!selectedNode.value?.node?.type) {
    return []
  }

  return mapEditorItems(editor, [
    [
      {
        type: 'label',
        label: upperFirst(selectedNode.value.node.type)
      },
      {
        label: 'Преобразовать в',
        icon: RepeatIcon,
        children: [
          { kind: 'paragraph', label: 'Абзац', icon: TextIcon },
          { kind: 'heading', level: 1, label: 'Заголовок 1' },
          { kind: 'heading', level: 2, label: 'Заголовок 2' },
          { kind: 'heading', level: 3, label: 'Заголовок 3' },
          { kind: 'heading', level: 4, label: 'Заголовок 4' },
          { kind: 'bulletList', label: 'Маркированный список', icon: BulletedListIcon },
          { kind: 'orderedList', label: 'Нумерованный список', icon: NumberedListIcon },
          { kind: 'blockquote', label: 'Цитата', icon: QuoteIcon },
          { kind: 'codeBlock', label: 'Блок кода', icon: CodeIcon }
        ]
      },
      {
        kind: 'clearFormatting',
        pos: selectedNode.value?.pos,
        label: 'Сбросить форматирование',
        icon: ResumeIcon
      }
    ],
    [
      {
        kind: 'duplicate',
        pos: selectedNode.value?.pos,
        label: 'Дублировать',
        icon: CopyIcon
      },
      {
        label: 'Копировать в буфер обмена',
        icon: CopyFileIcon,
        onSelect: async () => {
          if (!selectedNode.value) return

          const pos = selectedNode.value.pos
          const node = editor.state.doc.nodeAt(pos)
          if (node) {
            await navigator.clipboard.writeText(node.textContent)
          }
        }
      }
    ],
    [
      {
        kind: 'moveUp',
        pos: selectedNode.value?.pos,
        label: 'Переместить вверх',
        icon: ArrowTopLIcon
      },
      {
        kind: 'moveDown',
        pos: selectedNode.value?.pos,
        label: 'Переместить вниз',
        icon: ArrowDownLIcon
      }
    ],
    [
      {
        kind: 'delete',
        pos: selectedNode.value?.pos,
        label: 'Удалить',
        icon: TrashcanIcon
      }
    ]
  ]) as DropdownMenuItem[][]
}
</script>

<template>
  <B24Editor
    v-slot="{ editor }"
    v-model="value"
    content-type="markdown"
    class="w-full min-h-19"
  >
    <B24EditorDragHandle v-slot="{ b24ui }" :editor="editor" @node-change="selectedNode = $event">
      <B24DropdownMenu
        v-slot="{ open }"
        :modal="false"
        :items="items(editor)"
        :content="{ side: 'left' }"
        :b24ui="{ content: 'w-48', label: 'text-xs' }"
        @update:open="editor.chain().setMeta('lockDragHandle', $event).run()"
      >
        <B24Button
          :icon="DragLIcon"
          color="air-tertiary"
          active-color="air-secondary"
          size="sm"
          :active="open"
          :class="b24ui.handle()"
        />
      </B24DropdownMenu>
    </B24EditorDragHandle>
  </B24Editor>
</template>
```

> [!NOTE]
> В этом примере утилита `mapEditorItems` из `@bxshefby/b24ui-nuxt/utils/editor` сопоставляет виды обработчиков (`duplicate`, `delete`, `moveUp` и другие) с командами редактора и сама управляет состоянием.

### С меню подсказок

В слот по умолчанию можно добавить рядом с ручкой кнопку [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md), которая открывает [EditorSuggestionMenu](https://b24-ui.bx-shef.by/raw/docs/components/editor-suggestion-menu.md).

Функция слота `onClick` возвращает позицию текущего блока, а `handlers.suggestion?.execute(editor, { pos: node?.pos }).run()` вставляет новые блоки в эту позицию.

```vue [EditorDragHandleSuggestionMenuExample.vue]
<script setup lang="ts">
import type { EditorSuggestionMenuItem } from '@bxshefby/b24ui-nuxt'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import QuoteIcon from '@bitrix24/b24icons-vue/outline/QuoteIcon'
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import DragLIcon from '@bitrix24/b24icons-vue/outline/DragLIcon'

const value = ref(`Нажмите кнопку «плюс», чтобы открыть меню подсказок и добавить новые блоки.

Кнопка появляется при наведении на блоки.`)

const suggestionItems: EditorSuggestionMenuItem[][] = [
  [
    {
      kind: 'heading',
      level: 1,
      label: 'Заголовок 1'
    },
    {
      kind: 'heading',
      level: 2,
      label: 'Заголовок 2'
    },
    {
      kind: 'bulletList',
      label: 'Маркированный список',
      icon: BulletedListIcon
    },
    {
      kind: 'blockquote',
      label: 'Цитата',
      icon: QuoteIcon
    }
  ]
]
</script>

<template>
  <B24Editor
    v-slot="{ editor, handlers }"
    v-model="value"
    content-type="markdown"
    class="w-full min-h-35"
    :b24ui="{ base: 'p-8 sm:px-16' }"
  >
    <B24EditorSuggestionMenu :editor="editor" :items="suggestionItems" />

    <B24EditorDragHandle v-slot="{ b24ui, onClick }" :editor="editor">
      <B24Button
        :icon="PlusLIcon"
        color="air-tertiary"
        size="sm"
        :class="b24ui.handle()"
        @click="(e) => {
          e.stopPropagation()

          const selected = onClick()
          handlers.suggestion?.execute(editor, { pos: selected?.pos }).run()
        }"
      />

      <B24Button
        color="air-tertiary"
        size="sm"
        :icon="DragLIcon"
        :class="b24ui.handle()"
      />
    </B24EditorDragHandle>
  </B24Editor>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the EditorDragHandle component
 */
interface EditorDragHandleProps {
  editor?: Editor;
  /**
   * @default icons.drag
   */
  icon?: (props: HTMLAttributes & VNodeProps & {}, ctx: Omit<{ attrs: Attrs; slots: Readonly<InternalSlots>; emit: (event: string, ...args: any[]) => void; expose: <Exposed extends Record<string, any> = Record<...>>(exposed?: Exposed | undefined) => void; }, "expose">): any | undefined;
  /**
   * @default 'air-tertiary-no-accent'
   */
  color?: "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-tertiary-no-accent" | "air-selection" | "air-boost";
  /**
   * The options for positioning the drag handle. Those are passed to Floating UI and include options for the placement, offset, flip, shift, size, autoPlacement, hide, and inline middleware.
   * @default { strategy: 'absolute', placement: 'left-start' }
   */
  options?: FloatingUIOptions | undefined;
  b24ui?: { root?: SlotClass; handle?: SlotClass; } & { base?: SlotClass; baseLoading?: SlotClass; baseLoadingWaitIcon?: SlotClass; baseLoadingClockIcon?: SlotClass; baseLoadingSpinnerIcon?: SlotClass; baseLine?: SlotClass; label?: SlotClass; labelInner?: SlotClass; leadingIcon?: SlotClass; leadingAvatar?: SlotClass; leadingAvatarSize?: SlotClass; trailingIcon?: SlotClass; safeList?: SlotClass; } | undefined;
  pluginKey?: string | PluginKey<any> | undefined;
  nestedOptions?: NormalizedNestedOptions | undefined;
  onElementDragStart?: (e: DragEvent): void | undefined;
  onElementDragEnd?: (e: DragEvent): void | undefined;
  getReferencedVirtualElement?: (): VirtualElement | null | undefined;
  dragImageProperties?: string[] | undefined;
  /**
   * Enable drag handles for nested content (list items, blockquotes, etc.).
   * 
   * When enabled, the drag handle will appear for nested blocks, not just
   * top-level blocks. A rule-based scoring system determines which node
   * to target based on cursor position and configured rules.
   */
  nested?: boolean | NestedOptions | undefined;
  autofocus?: false | true | "false" | "true" | undefined;
  /**
   * The element or component this component should render as when not a link.
   * @default 'button'
   */
  as?: any;
  form?: string | undefined;
  label?: string | undefined;
  /**
   * The type of the button when not a link.
   * @default 'button'
   */
  type?: "reset" | "submit" | "button" | undefined;
  /**
   * @default 'sm'
   */
  size?: "md" | "sm" | "xs" | "xss" | "lg" | "xl" | undefined;
  name?: string | undefined;
  disabled?: boolean | undefined;
  /**
   * When `true`, the loading icon will be displayed.
   */
  loading?: boolean | undefined;
  /**
   * Render the button full width
   * @default false
   */
  block?: boolean | undefined;
  /**
   * Display an avatar on the left side.
   */
  avatar?: AvatarProps | undefined;
  /**
   * Class to apply when the link is exact active
   */
  exactActiveClass?: string | undefined;
  /**
   * Pass the returned promise of `router.push()` to `document.startViewTransition()` if supported.
   */
  viewTransition?: boolean | undefined;
  formaction?: string | undefined;
  formenctype?: string | undefined;
  formmethod?: string | undefined;
  formnovalidate?: false | true | "false" | "true" | undefined;
  formtarget?: string | undefined;
  onClick?: (event: MouseEvent): void | ((event: MouseEvent) => void)[] | undefined;
  activeColor?: "link" | "default" | "success" | "air-tertiary-no-accent" | "air-primary" | "air-primary-success" | "air-primary-alert" | "air-primary-copilot" | "air-secondary" | "air-secondary-alert" | "air-secondary-accent" | "air-secondary-accent-1" | "air-secondary-accent-2" | "air-secondary-no-accent" | "air-tertiary" | "air-tertiary-accent" | "air-selection" | "air-boost" | "danger" | "warning" | "primary" | "secondary" | "collab" | "ai" | undefined;
  /**
   * @default 'normal'
   * @deprecated Renders nothing on the `air-*` colours, the default among
   *   them: the `depth` compound variants are keyed on the legacy colour
   *   names only.
   * @removed 3.0.0
   */
  depth?: "normal" | "light" | "dark" | undefined;
  /**
   * @deprecated Same as `depth` — no effect on the `air-*` colours.
   * @removed 3.0.0
   */
  activeDepth?: "normal" | "light" | "dark" | undefined;
  /**
   * Rounds the corners of the button
   * @default false
   */
  rounded?: boolean | undefined;
  /**
   * Set loading state automatically based on the `@click` promise state
   * @default false
   */
  loadingAuto?: boolean | undefined;
  /**
   * Disable uppercase label
   * @default true
   */
  normalCase?: boolean | undefined;
  /**
   * Shows LoaderWaitIcon in loading mode
   * @default false
   */
  useWait?: boolean | undefined;
  /**
   * Shows LoaderClockIcon icon in loading mode
   * @default false
   */
  useClock?: boolean | undefined;
  /**
   * Shows a dropdown chevron on the right side, from the dictionary's
   * `chevronDown` role, so an `app.config` override reaches it.
   * @default false
   */
  useDropdown?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the EditorDragHandle component
 */
interface EditorDragHandleSlots {
  default(): any;
}
```

### События

```ts
/**
 * Emitted events for the EditorDragHandle component
 */
interface EditorDragHandleEmits {
  nodeChange: (payload: [{ node: JSONContent; pos: number; }]) => void;
  hover: (payload: [{ node: JSONContent; pos: number; }]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    editorDragHandle: {
      slots: {
        root: 'hidden sm:flex items-center justify-center transition-all duration-200 ease-out',
        handle: 'cursor-grab px-1'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
