# SelectionHandles

> 可拖动的移动端光标、选区端点及长按拖选手势。

网页来源：/components/selection-handles

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

SelectionHandles 显示和拖动光标或选区端点；SelectionGesture 识别正文表面的长按拖选。两者可独立使用，文字命中、选区和菜单由宿主持有。

## 默认光标与长按

`selection.type="caret"` 显示竖线及底部圆点。直接拖动圆点移动光标；长按圆点或正文 450ms 进入带括标的待选态，继续拖动形成范围，松手恢复两个端点手柄。示例也开启了鼠标长按，方便桌面试用。

### 示例：selection-handles/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import SelectionExample from './workbench.vue';
</script>
<template><SelectionExample /></template>
```

文件：`workbench.vue`

```vue
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { QuireButton, QuireCheckbox, QuireSelectionGesture, QuireSelectionHandles } from '@quirekit/ui/vue';
import type { QuireKitSelectionHandleDrag, QuireKitSelectionHandleDragEnd, QuireKitSelectionHandleNudge, QuireKitSelectionHandlesSelection, QuireKitSelectionGestureDetail } from '@quirekit/ui';
import { hitText, measureTextCaret, measureTextRange, snapTextOffset } from './geometry';
import type { TextSelectionRectangle } from './types';

const props = withDefaults(defineProps<{ initialRange?: boolean }>(), { initialRange: false });
const content = '认真记录每一个想法，让文字成为可以交流的内容。按住这里稍候，再拖动手指，选择你想分享的句子。选区跨行时也保持连续，可以从任意一端向前或向后调整。';
const paper = shallowRef<HTMLElement | null>(null);
const text = shallowRef<HTMLElement | null>(null);
const handles = shallowRef<InstanceType<typeof QuireSelectionHandles> | null>(null);
const gesture = shallowRef<InstanceType<typeof QuireSelectionGesture> | null>(null);
const model = shallowRef({ anchor: 17, focus: props.initialRange ? 37 : 17, range: props.initialRange });
const selection = shallowRef<QuireKitSelectionHandlesSelection | null>(null);
const rectangles = shallowRef<readonly TextSelectionRectangle[]>([]);
const selecting = ref(false);
const disabled = ref(false);
const zoomed = ref(false);
const status = ref('直接拖动圆点移动光标，长按圆点或正文后拖选');
const changes = ref(0);
const completions = ref(0);
const longPresses = ref(0);
const selectedText = computed(() => content.slice(Math.min(model.value.anchor, model.value.focus), Math.max(model.value.anchor, model.value.focus)));
let observer: ResizeObserver | undefined;
let pressAnchor = 0;

/** Projects the host's accepted text positions using native layout, not component internals. */
function project(): void {
  if (!paper.value || !text.value) return;
  const value = model.value;
  const focus = measureTextCaret(paper.value, text.value, value.focus);
  selection.value = value.range ? { type: 'range', anchor: measureTextCaret(paper.value, text.value, value.anchor), focus, backward: value.focus < value.anchor } : { type: 'caret', caret: focus };
  rectangles.value = measureTextRange(paper.value, text.value, value.anchor, value.focus);
}
/** @param anchor - Accepted anchor. @param focus - Accepted focus. @param range - Explicit presentation mode. */
function accept(anchor: number, focus: number, range: boolean): void { model.value = { anchor, focus, range }; project(); }
/** @param detail - Handle-owned client point after grab-offset compensation. */
function drag(detail: QuireKitSelectionHandleDrag): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.point);
  if (offset === null) return;
  if (detail.handle === 'caret') accept(selecting.value ? pressAnchor : offset, offset, selecting.value);
  else accept(detail.handle === 'anchor' ? offset : model.value.anchor, detail.handle === 'focus' ? offset : model.value.focus, true);
  changes.value++;
}
/** @param event - Ordinary text click, unaffected by unclaimed long-press candidates. */
function place(event: MouseEvent): void {
  if (disabled.value || !text.value) return;
  const offset = hitText(text.value, { x: event.clientX, y: event.clientY });
  if (offset !== null) accept(offset, offset, false);
}
/** @param detail - Hold accepted at the original text position. */
function hold(detail: QuireKitSelectionGestureDetail): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.origin);
  if (offset === null) { gesture.value?.cancel(); return; }
  pressAnchor = offset;
  selecting.value = true;
  accept(offset, offset, false);
  status.value = '已长按，继续拖动选择文字';
}
/** Uses the existing canonical caret as the anchor when its knob is held. */
function holdCaret(): void {
  pressAnchor = model.value.focus;
  selecting.value = true;
  status.value = '已长按，继续拖动选择文字';
}
/** @param detail - Handle completion; interrupted readiness must not remain visible. */
function finishHandle(detail: QuireKitSelectionHandleDragEnd): void {
  if (detail.reason !== 'release' && detail.reason !== 'long-press') cancel();
}
/** @param detail - Latest client point from the same hold. */
function extend(detail: QuireKitSelectionGestureDetail): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.point);
  if (offset !== null) { accept(pressAnchor, offset, true); changes.value++; }
}
/** Reports only the event, leaving menu content and lifetime to an editor consumer. */
function complete(): void { selecting.value = false; completions.value++; status.value = 'selectionComplete · 选择完成'; }
/** Keeps the simple-action request distinct from completing a range. */
function longPress(): void { selecting.value = false; longPresses.value++; status.value = 'longPress · 长按未拖动'; }
/** Clears provisional presentation without reverting accepted text positions. */
function cancel(): void { selecting.value = false; status.value = '交互已取消'; }
/** @param detail - Physical arrow intent, interpreted by this text host. */
function nudge(detail: QuireKitSelectionHandleNudge): void {
  const current = detail.handle === 'anchor' ? model.value.anchor : model.value.focus;
  const step = detail.accelerated ? 5 : 1;
  const delta = detail.direction === 'left' || detail.direction === 'up' ? -step : step;
  const next = snapTextOffset(content, Math.max(0, Math.min(content.length, current + delta)));
  if (detail.handle === 'caret') accept(next, next, false);
  else accept(detail.handle === 'anchor' ? next : model.value.anchor, detail.handle === 'focus' ? next : model.value.focus, true);
}
/** Restores a fresh insertion point without changing the example's text. */
function reset(): void { handles.value?.cancel(); gesture.value?.cancel(); selecting.value = false; accept(17, 17, false); status.value = '单光标'; }
/** Creates a range through the host model, allowing desktop handle testing without a hold. */
function selectSentence(): void { accept(0, 23, true); status.value = '拖动任意端点调整范围'; }
onMounted(() => {
  project();
  observer = new ResizeObserver(project);
  if (paper.value) observer.observe(paper.value);
  void document.fonts.ready.then(project);
});
watch(zoomed, async () => { await nextTick(); project(); });
onBeforeUnmount(() => observer?.disconnect());
</script>

<template>
  <div class="p-qk-surface grid gap-qk-surface" :data-selection-demo="initialRange ? 'range' : 'basic'" :data-changes="changes" :data-completions="completions" :data-long-presses="longPresses" :data-anchor="model.anchor" :data-focus="model.focus">
    <div class="flex flex-wrap items-center gap-qk-inline">
      <QuireButton variant="outline" :disabled="disabled" @click="selectSentence">选择一句</QuireButton>
      <QuireButton variant="ghost" :disabled="disabled" @click="reset">恢复光标</QuireButton>
      <template v-if="initialRange">
        <QuireCheckbox v-model:checked="disabled" label="禁用交互" />
        <QuireCheckbox v-model:checked="zoomed" label="放大 125%" />
      </template>
    </div>
    <div class="selection-example__viewport">
      <QuireSelectionGesture ref="gesture" :disabled="disabled" :pointer-types="['touch', 'pen', 'mouse']" @long-press-start="hold" @long-press="longPress" @selection-change="extend" @selection-complete="complete" @cancel="cancel">
        <article ref="paper" class="selection-example__paper" :style="zoomed ? { zoom: 1.25 } : undefined">
          <p class="selection-example__eyebrow">随手记 · 移动阅读</p>
          <h3>让想法停在纸上</h3>
          <div class="selection-example__highlights" aria-hidden="true">
            <span v-for="(rectangle, index) in rectangles" :key="index" :style="{ left: `${rectangle.x}px`, top: `${rectangle.y}px`, width: `${rectangle.width}px`, height: `${rectangle.height}px` }" />
          </div>
          <p ref="text" class="selection-example__text" @click="place">{{ content }}</p>
          <p class="selection-example__footnote">长按后直接松手，也可以继续拖动。</p>
          <QuireSelectionHandles ref="handles" :selection="selection" :selecting="selecting" :disabled="disabled" @long-press-start="holdCaret" @long-press="longPress" @drag="drag" @drag-end="finishHandle" @nudge="nudge" @selection-complete="complete" />
        </article>
      </QuireSelectionGesture>
    </div>
    <div class="text-qk-helper text-qk-text-secondary grid gap-1">
      <span role="status">{{ status }}</span>
      <span data-selected-text>{{ selectedText ? `已选：${selectedText}` : '当前为插入光标' }}</span>
    </div>
  </div>
</template>

<style scoped>
.selection-example__viewport { max-height: 340px; overflow: auto; background: var(--qk-color-surface-subtle); border-radius: var(--qk-radius-surface); }
.selection-example__paper { position: relative; max-width: 420px; min-height: 390px; margin: 0 auto; padding: 28px 26px 44px; background: var(--qk-color-surface-page); color: var(--qk-color-text-primary); }
.selection-example__eyebrow { margin: 0 0 14px; font-size: 12px; color: var(--qk-color-text-muted); }
.selection-example__paper h3 { margin: 0 0 22px; font-size: 22px; line-height: 1.4; font-weight: 600; }
.selection-example__text { position: relative; margin: 0; font-size: 17px; line-height: 2; overflow-wrap: anywhere; }
.selection-example__footnote { margin: 30px 0 0; font-size: 13px; color: var(--qk-color-text-secondary); }
.selection-example__highlights { position: absolute; inset: 0; pointer-events: none; }
.selection-example__highlights span { position: absolute; background: var(--qk-color-selection-document); }
</style>
```

文件：`geometry.ts`

```ts
import type { QuireKitSelectionHandleGeometry, QuireKitSelectionHandlePoint } from '@quirekit/ui';
import type { TextHitDocument, TextSelectionRectangle } from './types';

/** @param element - Single plain-text paragraph. @returns Its native Text node. */
function textNode(element: HTMLElement): Text { return element.firstChild as Text; }

/** @param content - Plain text. @param offset - Candidate UTF-16 position. @returns Nearest grapheme boundary. */
export function snapTextOffset(content: string, offset: number): number {
  const boundaries = [0, ...[...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(content)].map(part => part.index + part.segment.length)];
  return boundaries.reduce((nearest, value) => Math.abs(value - offset) < Math.abs(nearest - offset) ? value : nearest, 0);
}

/** @param text - Measured paragraph. @param point - Client point. @returns A native hit offset, or null outside its text. */
export function hitText(text: HTMLElement, point: QuireKitSelectionHandlePoint): number | null {
  const doc = text.ownerDocument as TextHitDocument;
  const position = doc.caretPositionFromPoint?.(point.x, point.y);
  const range = !position ? doc.caretRangeFromPoint?.(point.x, point.y) : null;
  const node = position?.offsetNode ?? range?.startContainer;
  const offset = position?.offset ?? range?.startOffset;
  if (node === textNode(text) && offset !== undefined) return snapTextOffset(text.textContent ?? '', offset);
  const rect = text.getBoundingClientRect();
  if (point.y < rect.top) return 0;
  if (point.y > rect.bottom) return text.textContent?.length ?? 0;
  return null;
}

/** @param host - Overlay coordinate owner. @param rect - Native viewport rectangle. @returns Local CSS pixel geometry. */
function localRect(host: HTMLElement, rect: DOMRect): TextSelectionRectangle {
  const owner = host.getBoundingClientRect();
  const scale = owner.width / host.offsetWidth;
  return { x: (rect.left - owner.left) / scale, y: (rect.top - owner.top) / scale, width: rect.width / scale, height: rect.height / scale };
}

/** @param host - Overlay owner. @param text - Plain-text paragraph. @param offset - Grapheme boundary. @returns Native measured caret. */
export function measureTextCaret(host: HTMLElement, text: HTMLElement, offset: number): QuireKitSelectionHandleGeometry {
  const node = textNode(text);
  const range = text.ownerDocument.createRange();
  range.setStart(node, offset);
  range.collapse(true);
  let rect = range.getBoundingClientRect();
  if (!rect.height) {
    range.setStart(node, Math.max(0, offset - 1));
    range.setEnd(node, Math.min(node.length, offset || 1));
    const fallback = range.getBoundingClientRect();
    rect = new DOMRect(offset ? fallback.right : fallback.left, fallback.top, 0, fallback.height);
  }
  const local = localRect(host, rect);
  return { x: local.x, y: local.y, height: local.height };
}

/** @param host - Overlay owner. @param text - Plain-text paragraph. @param anchor - Anchor offset. @param focus - Focus offset. @returns Local selection highlights. */
export function measureTextRange(host: HTMLElement, text: HTMLElement, anchor: number, focus: number): readonly TextSelectionRectangle[] {
  if (anchor === focus) return [];
  const range = text.ownerDocument.createRange();
  range.setStart(textNode(text), Math.min(anchor, focus));
  range.setEnd(textNode(text), Math.max(anchor, focus));
  return [...range.getClientRects()].map(rect => localRect(host, rect));
}
```

文件：`types.ts`

```ts
/** Local rectangle used only by the text measurement example. */
export interface TextSelectionRectangle {
  /** Local left edge. */
  readonly x: number;
  /** Local top edge. */
  readonly y: number;
  /** Rectangle width. */
  readonly width: number;
  /** Rectangle height. */
  readonly height: number;
}

/** Browser hit-test APIs, including the WebKit fallback. */
export interface TextHitDocument extends Document {
  /** @param x - Client x. @param y - Client y. @returns Native collapsed hit range. */
  caretRangeFromPoint(x: number, y: number): Range | null;
}
```

`longPressStart` 在达到默认 450ms 时触发；未拖动松手触发 `longPress`，拖选松手触发 `selectionComplete`。正文等待期间移动超过默认 8px 会让出手势，保持普通滚动；手柄直接拖动则调整光标或端点。

手柄会自行取消浏览器的原生触摸长按菜单与 callout，宿主无需额外拦截。光标转范围、热区暂时退出命中时仍保有这一触摸会话；松手或取消后释放拦截，其他位置的正常菜单保持可用。自定义长按、拖选与完成事件继续照常触发。

## 范围、反向与禁用

`selection.type="range"` 接收稳定的 `anchor` 和 `focus`。反向时设置 `backward`，组件交换圆点朝向；拖过另一端时保持端点身份。`disabled` 取消当前交互；某个端点为 `null` 时仅隐藏该端，整个 `selection` 为 `null` 时全部隐藏。

### 示例：selection-handles/range

文件：`range.vue`

```vue
<script setup lang="ts">
import SelectionExample from './workbench.vue';
</script>
<template><SelectionExample initial-range /></template>
```

文件：`workbench.vue`

```vue
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { QuireButton, QuireCheckbox, QuireSelectionGesture, QuireSelectionHandles } from '@quirekit/ui/vue';
import type { QuireKitSelectionHandleDrag, QuireKitSelectionHandleDragEnd, QuireKitSelectionHandleNudge, QuireKitSelectionHandlesSelection, QuireKitSelectionGestureDetail } from '@quirekit/ui';
import { hitText, measureTextCaret, measureTextRange, snapTextOffset } from './geometry';
import type { TextSelectionRectangle } from './types';

const props = withDefaults(defineProps<{ initialRange?: boolean }>(), { initialRange: false });
const content = '认真记录每一个想法，让文字成为可以交流的内容。按住这里稍候，再拖动手指，选择你想分享的句子。选区跨行时也保持连续，可以从任意一端向前或向后调整。';
const paper = shallowRef<HTMLElement | null>(null);
const text = shallowRef<HTMLElement | null>(null);
const handles = shallowRef<InstanceType<typeof QuireSelectionHandles> | null>(null);
const gesture = shallowRef<InstanceType<typeof QuireSelectionGesture> | null>(null);
const model = shallowRef({ anchor: 17, focus: props.initialRange ? 37 : 17, range: props.initialRange });
const selection = shallowRef<QuireKitSelectionHandlesSelection | null>(null);
const rectangles = shallowRef<readonly TextSelectionRectangle[]>([]);
const selecting = ref(false);
const disabled = ref(false);
const zoomed = ref(false);
const status = ref('直接拖动圆点移动光标，长按圆点或正文后拖选');
const changes = ref(0);
const completions = ref(0);
const longPresses = ref(0);
const selectedText = computed(() => content.slice(Math.min(model.value.anchor, model.value.focus), Math.max(model.value.anchor, model.value.focus)));
let observer: ResizeObserver | undefined;
let pressAnchor = 0;

/** Projects the host's accepted text positions using native layout, not component internals. */
function project(): void {
  if (!paper.value || !text.value) return;
  const value = model.value;
  const focus = measureTextCaret(paper.value, text.value, value.focus);
  selection.value = value.range ? { type: 'range', anchor: measureTextCaret(paper.value, text.value, value.anchor), focus, backward: value.focus < value.anchor } : { type: 'caret', caret: focus };
  rectangles.value = measureTextRange(paper.value, text.value, value.anchor, value.focus);
}
/** @param anchor - Accepted anchor. @param focus - Accepted focus. @param range - Explicit presentation mode. */
function accept(anchor: number, focus: number, range: boolean): void { model.value = { anchor, focus, range }; project(); }
/** @param detail - Handle-owned client point after grab-offset compensation. */
function drag(detail: QuireKitSelectionHandleDrag): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.point);
  if (offset === null) return;
  if (detail.handle === 'caret') accept(selecting.value ? pressAnchor : offset, offset, selecting.value);
  else accept(detail.handle === 'anchor' ? offset : model.value.anchor, detail.handle === 'focus' ? offset : model.value.focus, true);
  changes.value++;
}
/** @param event - Ordinary text click, unaffected by unclaimed long-press candidates. */
function place(event: MouseEvent): void {
  if (disabled.value || !text.value) return;
  const offset = hitText(text.value, { x: event.clientX, y: event.clientY });
  if (offset !== null) accept(offset, offset, false);
}
/** @param detail - Hold accepted at the original text position. */
function hold(detail: QuireKitSelectionGestureDetail): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.origin);
  if (offset === null) { gesture.value?.cancel(); return; }
  pressAnchor = offset;
  selecting.value = true;
  accept(offset, offset, false);
  status.value = '已长按，继续拖动选择文字';
}
/** Uses the existing canonical caret as the anchor when its knob is held. */
function holdCaret(): void {
  pressAnchor = model.value.focus;
  selecting.value = true;
  status.value = '已长按，继续拖动选择文字';
}
/** @param detail - Handle completion; interrupted readiness must not remain visible. */
function finishHandle(detail: QuireKitSelectionHandleDragEnd): void {
  if (detail.reason !== 'release' && detail.reason !== 'long-press') cancel();
}
/** @param detail - Latest client point from the same hold. */
function extend(detail: QuireKitSelectionGestureDetail): void {
  if (!text.value) return;
  const offset = hitText(text.value, detail.point);
  if (offset !== null) { accept(pressAnchor, offset, true); changes.value++; }
}
/** Reports only the event, leaving menu content and lifetime to an editor consumer. */
function complete(): void { selecting.value = false; completions.value++; status.value = 'selectionComplete · 选择完成'; }
/** Keeps the simple-action request distinct from completing a range. */
function longPress(): void { selecting.value = false; longPresses.value++; status.value = 'longPress · 长按未拖动'; }
/** Clears provisional presentation without reverting accepted text positions. */
function cancel(): void { selecting.value = false; status.value = '交互已取消'; }
/** @param detail - Physical arrow intent, interpreted by this text host. */
function nudge(detail: QuireKitSelectionHandleNudge): void {
  const current = detail.handle === 'anchor' ? model.value.anchor : model.value.focus;
  const step = detail.accelerated ? 5 : 1;
  const delta = detail.direction === 'left' || detail.direction === 'up' ? -step : step;
  const next = snapTextOffset(content, Math.max(0, Math.min(content.length, current + delta)));
  if (detail.handle === 'caret') accept(next, next, false);
  else accept(detail.handle === 'anchor' ? next : model.value.anchor, detail.handle === 'focus' ? next : model.value.focus, true);
}
/** Restores a fresh insertion point without changing the example's text. */
function reset(): void { handles.value?.cancel(); gesture.value?.cancel(); selecting.value = false; accept(17, 17, false); status.value = '单光标'; }
/** Creates a range through the host model, allowing desktop handle testing without a hold. */
function selectSentence(): void { accept(0, 23, true); status.value = '拖动任意端点调整范围'; }
onMounted(() => {
  project();
  observer = new ResizeObserver(project);
  if (paper.value) observer.observe(paper.value);
  void document.fonts.ready.then(project);
});
watch(zoomed, async () => { await nextTick(); project(); });
onBeforeUnmount(() => observer?.disconnect());
</script>

<template>
  <div class="p-qk-surface grid gap-qk-surface" :data-selection-demo="initialRange ? 'range' : 'basic'" :data-changes="changes" :data-completions="completions" :data-long-presses="longPresses" :data-anchor="model.anchor" :data-focus="model.focus">
    <div class="flex flex-wrap items-center gap-qk-inline">
      <QuireButton variant="outline" :disabled="disabled" @click="selectSentence">选择一句</QuireButton>
      <QuireButton variant="ghost" :disabled="disabled" @click="reset">恢复光标</QuireButton>
      <template v-if="initialRange">
        <QuireCheckbox v-model:checked="disabled" label="禁用交互" />
        <QuireCheckbox v-model:checked="zoomed" label="放大 125%" />
      </template>
    </div>
    <div class="selection-example__viewport">
      <QuireSelectionGesture ref="gesture" :disabled="disabled" :pointer-types="['touch', 'pen', 'mouse']" @long-press-start="hold" @long-press="longPress" @selection-change="extend" @selection-complete="complete" @cancel="cancel">
        <article ref="paper" class="selection-example__paper" :style="zoomed ? { zoom: 1.25 } : undefined">
          <p class="selection-example__eyebrow">随手记 · 移动阅读</p>
          <h3>让想法停在纸上</h3>
          <div class="selection-example__highlights" aria-hidden="true">
            <span v-for="(rectangle, index) in rectangles" :key="index" :style="{ left: `${rectangle.x}px`, top: `${rectangle.y}px`, width: `${rectangle.width}px`, height: `${rectangle.height}px` }" />
          </div>
          <p ref="text" class="selection-example__text" @click="place">{{ content }}</p>
          <p class="selection-example__footnote">长按后直接松手，也可以继续拖动。</p>
          <QuireSelectionHandles ref="handles" :selection="selection" :selecting="selecting" :disabled="disabled" @long-press-start="holdCaret" @long-press="longPress" @drag="drag" @drag-end="finishHandle" @nudge="nudge" @selection-complete="complete" />
        </article>
      </QuireSelectionGesture>
    </div>
    <div class="text-qk-helper text-qk-text-secondary grid gap-1">
      <span role="status">{{ status }}</span>
      <span data-selected-text>{{ selectedText ? `已选：${selectedText}` : '当前为插入光标' }}</span>
    </div>
  </div>
</template>

<style scoped>
.selection-example__viewport { max-height: 340px; overflow: auto; background: var(--qk-color-surface-subtle); border-radius: var(--qk-radius-surface); }
.selection-example__paper { position: relative; max-width: 420px; min-height: 390px; margin: 0 auto; padding: 28px 26px 44px; background: var(--qk-color-surface-page); color: var(--qk-color-text-primary); }
.selection-example__eyebrow { margin: 0 0 14px; font-size: 12px; color: var(--qk-color-text-muted); }
.selection-example__paper h3 { margin: 0 0 22px; font-size: 22px; line-height: 1.4; font-weight: 600; }
.selection-example__text { position: relative; margin: 0; font-size: 17px; line-height: 2; overflow-wrap: anywhere; }
.selection-example__footnote { margin: 30px 0 0; font-size: 13px; color: var(--qk-color-text-secondary); }
.selection-example__highlights { position: absolute; inset: 0; pointer-events: none; }
.selection-example__highlights span { position: absolute; background: var(--qk-color-selection-document); }
</style>
```

文件：`geometry.ts`

```ts
import type { QuireKitSelectionHandleGeometry, QuireKitSelectionHandlePoint } from '@quirekit/ui';
import type { TextHitDocument, TextSelectionRectangle } from './types';

/** @param element - Single plain-text paragraph. @returns Its native Text node. */
function textNode(element: HTMLElement): Text { return element.firstChild as Text; }

/** @param content - Plain text. @param offset - Candidate UTF-16 position. @returns Nearest grapheme boundary. */
export function snapTextOffset(content: string, offset: number): number {
  const boundaries = [0, ...[...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(content)].map(part => part.index + part.segment.length)];
  return boundaries.reduce((nearest, value) => Math.abs(value - offset) < Math.abs(nearest - offset) ? value : nearest, 0);
}

/** @param text - Measured paragraph. @param point - Client point. @returns A native hit offset, or null outside its text. */
export function hitText(text: HTMLElement, point: QuireKitSelectionHandlePoint): number | null {
  const doc = text.ownerDocument as TextHitDocument;
  const position = doc.caretPositionFromPoint?.(point.x, point.y);
  const range = !position ? doc.caretRangeFromPoint?.(point.x, point.y) : null;
  const node = position?.offsetNode ?? range?.startContainer;
  const offset = position?.offset ?? range?.startOffset;
  if (node === textNode(text) && offset !== undefined) return snapTextOffset(text.textContent ?? '', offset);
  const rect = text.getBoundingClientRect();
  if (point.y < rect.top) return 0;
  if (point.y > rect.bottom) return text.textContent?.length ?? 0;
  return null;
}

/** @param host - Overlay coordinate owner. @param rect - Native viewport rectangle. @returns Local CSS pixel geometry. */
function localRect(host: HTMLElement, rect: DOMRect): TextSelectionRectangle {
  const owner = host.getBoundingClientRect();
  const scale = owner.width / host.offsetWidth;
  return { x: (rect.left - owner.left) / scale, y: (rect.top - owner.top) / scale, width: rect.width / scale, height: rect.height / scale };
}

/** @param host - Overlay owner. @param text - Plain-text paragraph. @param offset - Grapheme boundary. @returns Native measured caret. */
export function measureTextCaret(host: HTMLElement, text: HTMLElement, offset: number): QuireKitSelectionHandleGeometry {
  const node = textNode(text);
  const range = text.ownerDocument.createRange();
  range.setStart(node, offset);
  range.collapse(true);
  let rect = range.getBoundingClientRect();
  if (!rect.height) {
    range.setStart(node, Math.max(0, offset - 1));
    range.setEnd(node, Math.min(node.length, offset || 1));
    const fallback = range.getBoundingClientRect();
    rect = new DOMRect(offset ? fallback.right : fallback.left, fallback.top, 0, fallback.height);
  }
  const local = localRect(host, rect);
  return { x: local.x, y: local.y, height: local.height };
}

/** @param host - Overlay owner. @param text - Plain-text paragraph. @param anchor - Anchor offset. @param focus - Focus offset. @returns Local selection highlights. */
export function measureTextRange(host: HTMLElement, text: HTMLElement, anchor: number, focus: number): readonly TextSelectionRectangle[] {
  if (anchor === focus) return [];
  const range = text.ownerDocument.createRange();
  range.setStart(textNode(text), Math.min(anchor, focus));
  range.setEnd(textNode(text), Math.max(anchor, focus));
  return [...range.getClientRects()].map(rect => localRect(host, rect));
}
```

文件：`types.ts`

```ts
/** Local rectangle used only by the text measurement example. */
export interface TextSelectionRectangle {
  /** Local left edge. */
  readonly x: number;
  /** Local top edge. */
  readonly y: number;
  /** Rectangle width. */
  readonly width: number;
  /** Rectangle height. */
  readonly height: number;
}

/** Browser hit-test APIs, including the WebKit fallback. */
export interface TextHitDocument extends Document {
  /** @param x - Client x. @param y - Client y. @returns Native collapsed hit range. */
  caretRangeFromPoint(x: number, y: number): Range | null;
}
```

手柄可用 Tab 聚焦，方向键触发 `nudge`，Shift 请求更大步长；字符、行和双向文字移动由宿主解释。Escape 取消拖动，取消不会回滚已接受的选区。

## 连接编辑器

`x/y/height` 是定位祖先内的 CSS 像素，`y` 表示光标顶端。把组件放在与这些坐标一致的 `position: relative` 容器中；`drag.point` 是扣除抓取偏移后的 viewport client 点，可直接交给编辑器的坐标命中接口。宿主更新选区后，再反馈两个端点几何。

示例中的 `geometry.ts` 用浏览器 Range 完成文本测量；正式接入时应替换为编辑器已有的几何和命中接口。组件不扫描文档、不计算字素边界或自动滚动；文档目标失效时调用公开的 `cancel()`。

手柄长按会自行显示待选括标；`selecting` 用于投影由正文等其他入口建立的待选态。期间手柄热区暂时退出命中，避免遮住正文。SelectionGesture 的 `selectionChange` 与手柄的 `drag` 每帧最多一次；释放会先发送最终位置，再报告完成。取消不报告完成。

| 事件 | 触发时机 | 宿主可执行的动作 |
| --- | --- | --- |
| `longPressStart` | 光标圆点或正文长按达到阈值 | 显示待选光标、收起已有菜单 |
| `longPress` | 长按未拖动并松手 | 显示简单操作菜单 |
| `selectionStart` / `selectionChange` | 长按后拖选 | 从原始位置建立并更新选区 |
| `selectionComplete` | 正文拖选或手柄调整正常释放 | 按最终选区显示操作菜单 |
| `cancel` / `dragEnd` | 中断或结束 | 清理临时交互状态 |

手柄的 `longPressStart` 到达时，宿主记录当前光标作为 anchor；后续 `drag` 的 `handle` 仍为 `caret`，把命中结果作为 focus 并反馈 `selection.type="range"`。组件在这次切换中保留指针捕获；未拖动释放只触发 `longPress`，`dragEnd.reason` 为 `long-press`。

菜单内容、显示/关闭，以及点击已有选区后重新打开菜单由产品实现。公共组件不安装全局 `selectionchange`，不调用编辑器命令，也不主动改变输入焦点。触控模拟不能替代真机的软键盘与系统手势验收。

## 无框架接入

从 `@quirekit/ui` 导入 `createQuireSelectionHandles` 和 `createQuireSelectionGesture`。前者返回 `element/update/cancel/destroy`；后者接收已有 `target` 并返回 `update/cancel/destroy`。加载 QuireKit UnoCSS preset，挂卸时对应销毁两个实例。

DOM binding 的 `ignore(event)` 可排除额外交互区域；默认跳过手柄和按钮、输入框等子控件。SelectionGesture 会关闭绑定面的浏览器原生文本选择；DOM 编辑器仅在自定义移动端选区模式挂载，桌面继续使用自身选区机制。

## API

### QuireSelectionHandles

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| selection | 是 | — | Current geometry, or null to hide all handles. The host owns selection. |
| disabled | 否 | false | Disables interaction and cancels the active drag. Defaults to false. |
| selecting | 否 | false | Shows provisional boundary markers and the active bottom grip during long-press selection. |
| longPressDelay | 否 | — | Caret hold delay before entering selection readiness. Defaults to 450ms. |
| movementThreshold | 否 | — | Caret hold jitter tolerance in client CSS pixels. Defaults to 8px. |

**selection**

```ts
QuireKitSelectionHandlesSelection | null
```

```ts
null | {
  /** Displays one bottom handle for an insertion point. */
  type: "caret";
  /** Insertion point geometry. */
  caret: null | {
    /** Positive line height; y denotes the top of this line. */
    height: number;
    /** Horizontal coordinate. */
    x: number;
    /** Vertical coordinate. */
    y: number;
  };
} | {
  /** Displays independently draggable range endpoints. */
  type: "range";
  /** Stable anchor geometry, not necessarily the earlier document position. */
  anchor: QuireKitSelectionHandleGeometry | null;
  /** Stable focus geometry, not necessarily the later document position. */
  focus: QuireKitSelectionHandleGeometry | null;
  /** Places focus above and anchor below when focus precedes anchor. */
  backward?: boolean | undefined;
}
```

**disabled**

```ts
boolean | undefined
```

**selecting**

```ts
boolean | undefined
```

**longPressDelay**

```ts
number | undefined
```

```ts
undefined | number
```

**movementThreshold**

```ts
number | undefined
```

```ts
undefined | number
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| dragStart | 否 | — |  |
| longPressStart | 否 | — |  |
| longPress | 否 | — |  |
| drag | 否 | — |  |
| dragEnd | 否 | — |  |
| selectionComplete | 否 | — |  |
| nudge | 否 | — |  |

**dragStart**

```ts
[detail: QuireKitSelectionHandleDrag]
```

**longPressStart**

```ts
[detail: QuireKitSelectionHandleDrag]
```

**longPress**

```ts
[detail: QuireKitSelectionHandleDrag]
```

**drag**

```ts
[detail: QuireKitSelectionHandleDrag]
```

**dragEnd**

```ts
[detail: QuireKitSelectionHandleDragEnd]
```

**selectionComplete**

```ts
[detail: QuireKitSelectionHandleDrag]
```

**nudge**

```ts
[detail: QuireKitSelectionHandleNudge]
```

#### Slots

无。

#### 公开实例成员

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| cancel | 否 | — |  |

**cancel**

```ts
() => void
```

```ts
{ (): void; }
```

#### 相关类型

```ts
type QuireKitSelectionHandleGeometry = {
  /** Positive line height; y denotes the top of this line. */
  height: number;
  /** Horizontal coordinate. */
  x: number;
  /** Vertical coordinate. */
  y: number;
};
```

### QuireSelectionGesture

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| disabled | 否 | — | Suspends recognition and cancels an accepted gesture. |
| longPressDelay | 否 | — | Hold delay in milliseconds. Defaults to 450; must be nonnegative. |
| movementThreshold | 否 | — | Allowed jitter in client CSS pixels. Defaults to 8; must be nonnegative. |
| pointerTypes | 否 | — | Accepted devices. Defaults to touch and pen; unaccepted devices are left to the host. |

**disabled**

```ts
boolean | undefined
```

**longPressDelay**

```ts
number | undefined
```

```ts
undefined | number
```

**movementThreshold**

```ts
number | undefined
```

```ts
undefined | number
```

**pointerTypes**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| longPressStart | 否 | — |  |
| longPress | 否 | — |  |
| selectionComplete | 否 | — |  |
| cancel | 否 | — |  |
| selectionStart | 否 | — |  |
| selectionChange | 否 | — |  |

**longPressStart**

```ts
[detail: QuireKitSelectionGestureDetail]
```

**longPress**

```ts
[detail: QuireKitSelectionGestureDetail]
```

**selectionComplete**

```ts
[detail: QuireKitSelectionGestureDetail]
```

**cancel**

```ts
[detail: QuireKitSelectionGestureCancel]
```

**selectionStart**

```ts
[detail: QuireKitSelectionGestureDetail]
```

**selectionChange**

```ts
[detail: QuireKitSelectionGestureDetail]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| default | 否 | — |  |

**default**

```ts
any
```

#### 公开实例成员

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| cancel | 否 | — |  |

**cancel**

```ts
() => void
```

```ts
{ (): void; }
```
