| 1 | import type { SlidePatch } from '@slidev/types' |
| 2 | import type { CSSProperties, DirectiveBinding, InjectionKey, WatchStopHandle } from 'vue' |
| 3 | import { debounce, ensureSuffix } from '@antfu/utils' |
| 4 | import { injectLocal, onClickOutside, useWindowFocus } from '@vueuse/core' |
| 5 | import { computed, ref, watch } from 'vue' |
| 6 | import { injectionCurrentPage, injectionFrontmatter, injectionRenderContext, injectionSlideElement, injectionSlideScale, injectionSlideZoom } from '../constants' |
| 7 | import { makeId } from '../logic/utils' |
| 8 | import { activeDragElement } from '../state' |
| 9 | import { directiveInject } from '../utils' |
| 10 | import { useNav } from './useNav' |
| 11 | import { useSlideBounds } from './useSlideBounds' |
| 12 | import { useDynamicSlideInfo } from './useSlideInfo' |
| 13 | |
| 14 | const RE_NEWLINE = /\r?\n/g |
| 15 | const RE_POS_ATTR = /pos=".*?"/ |
| 16 | |
| 17 | /** |
| 18 | * The effective `zoom` of the element itself (e.g. from a UnoCSS class). |
| 19 | * CSS zoom scales the element's box, which would otherwise offset the drag box. |
| 20 | */ |
| 21 | function getElementZoom(el: HTMLElement): number { |
| 22 | const raw = getComputedStyle(el).getPropertyValue('zoom') |
| 23 | const zoom = Number.parseFloat(raw) / (raw.endsWith('%') |
| 24 | ? 100 |
| 25 | : 1) |
| 26 | if (!Number.isFinite(zoom) || zoom <= 0) |
| 27 | return 1 |
| 28 | return zoom |
| 29 | } |
| 30 | |
| 31 | export type DragElementDataSource = 'frontmatter' | 'prop' | 'directive' |
| 32 | /** |
| 33 | * Markdown source position, injected by markdown-it plugin |
| 34 | */ |
| 35 | export type DragElementMarkdownSource = [startLine: number, endLine: number, index: number] |
| 36 | |
| 37 | export type DragElementsUpdater = (id: string, posStr: string, type: DragElementDataSource, markdownSource?: DragElementMarkdownSource) => void |
| 38 | |
| 39 | const map: Record<number, DragElementsUpdater> = {} |
| 40 | |
| 41 | export function useDragElementsUpdater(no: number) { |
| 42 | if (!(__DEV__ && __SLIDEV_FEATURE_EDITOR__)) |
| 43 | return () => {} |
| 44 | |
| 45 | if (map[no]) |
| 46 | return map[no] |
| 47 | |
| 48 | const { info, update } = useDynamicSlideInfo(no) |
| 49 | |
| 50 | let newPatch: SlidePatch | null = null |
| 51 | async function save() { |
| 52 | if (newPatch) { |
| 53 | await update({ |
| 54 | ...newPatch, |
| 55 | skipHmr: true, |
| 56 | }) |
| 57 | newPatch = null |
| 58 | } |
| 59 | } |
| 60 | const debouncedSave = debounce(500, save) |
| 61 | |
| 62 | return map[no] = (id, posStr, type, markdownSource) => { |
| 63 | if (!info.value) |
| 64 | return |
| 65 | |
| 66 | if (type === 'frontmatter') { |
| 67 | const frontmatter = info.value.frontmatter |
| 68 | frontmatter.dragPos ||= {} |
| 69 | if (frontmatter.dragPos[id] === posStr) |
| 70 | return |
| 71 | frontmatter.dragPos[id] = posStr |
| 72 | newPatch = { |
| 73 | frontmatter: { |
| 74 | dragPos: frontmatter.dragPos, |
| 75 | }, |
| 76 | } |
| 77 | } |
| 78 | else { |
| 79 | if (!markdownSource) |
| 80 | throw new Error(`[Slidev] VDrag Element ${id} is missing markdown source`) |
| 81 | |
| 82 | const [startLine, endLine, idx] = markdownSource |
| 83 | const lines = info.value.content.split(RE_NEWLINE) |
| 84 | |
| 85 | let section = lines.slice(startLine, endLine).join('\n') |
| 86 | let replaced = false |
| 87 | |
| 88 | section = type === 'prop' |
| 89 | // eslint-disable-next-line regexp/no-super-linear-backtracking |
| 90 | ? section.replace(/<(v-?drag-?\w*)(.*?)(\/)?>/gi, (full, tag, attrs, selfClose = '', index) => { |
| 91 | if (index === idx) { |
| 92 | replaced = true |
| 93 | const posMatch = attrs.match(RE_POS_ATTR) |
| 94 | if (!posMatch) |
| 95 | return `<${tag}${ensureSuffix(' ', attrs)}pos="${posStr}"${selfClose}>` |
| 96 | const start = posMatch.index |
| 97 | const end = start + posMatch[0].length |
| 98 | return `<${tag}${attrs.slice(0, start)}pos="${posStr}"${attrs.slice(end)}${selfClose}>` |
| 99 | } |
| 100 | return full |
| 101 | }) |
| 102 | : section.replace(/(?<![</\w])v-drag(?:=".*?")?/gi, (full, index) => { |
| 103 | if (index === idx) { |
| 104 | replaced = true |
| 105 | return `v-drag="${posStr}"` |
| 106 | } |
| 107 | return full |
| 108 | }) |
| 109 | |
| 110 | if (!replaced) |
| 111 | throw new Error(`[Slidev] VDrag Element ${id} is not found in the markdown source`) |
| 112 | |
| 113 | lines.splice( |
| 114 | startLine, |
| 115 | endLine - startLine, |
| 116 | section, |
| 117 | ) |
| 118 | |
| 119 | const newContent = lines.join('\n') |
| 120 | if (info.value.content === newContent) |
| 121 | return |
| 122 | newPatch = { |
| 123 | content: newContent, |
| 124 | } |
| 125 | info.value = { |
| 126 | ...info.value, |
| 127 | content: newContent, |
| 128 | } |
| 129 | } |
| 130 | debouncedSave() |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | export function useDragElement(directive: DirectiveBinding | null, posRaw?: string | number | number[], markdownSource?: DragElementMarkdownSource, isArrow = false) { |
| 135 | function inject<T>(key: InjectionKey<T> | string): T | undefined { |
| 136 | return directive |
| 137 | ? directiveInject(directive, key) |
| 138 | : injectLocal(key) |
| 139 | } |
| 140 | |
| 141 | const renderContext = inject(injectionRenderContext)! |
| 142 | const frontmatter = inject(injectionFrontmatter) ?? {} |
| 143 | const page = inject(injectionCurrentPage)! |
| 144 | const updater = computed(() => useDragElementsUpdater(page.value)) |
| 145 | const scale = inject(injectionSlideScale) ?? ref(1) |
| 146 | const zoom = inject(injectionSlideZoom) ?? ref(1) |
| 147 | const { left: slideLeft, top: slideTop, stop: stopWatchBounds } = useSlideBounds(inject(injectionSlideElement) ?? ref()) |
| 148 | const { isPrintMode } = useNav() |
| 149 | const enabled = ['slide', 'presenter'].includes(renderContext.value) && !isPrintMode.value |
| 150 | |
| 151 | let dataSource: DragElementDataSource = directive ? 'directive' : 'prop' |
| 152 | let dragId: string = makeId() |
| 153 | let pos: number[] | undefined |
| 154 | if (Array.isArray(posRaw)) { |
| 155 | pos = posRaw |
| 156 | } |
| 157 | else if (typeof posRaw === 'string' && posRaw.includes(',')) { |
| 158 | pos = posRaw.split(',').map(Number) |
| 159 | } |
| 160 | else if (posRaw != null) { |
| 161 | dataSource = 'frontmatter' |
| 162 | dragId = `${posRaw}` |
| 163 | posRaw = frontmatter?.dragPos?.[dragId] |
| 164 | pos = (posRaw as string)?.split(',').map(Number) |
| 165 | } |
| 166 | |
| 167 | if (dataSource !== 'frontmatter' && !markdownSource) |
| 168 | throw new Error('[Slidev] Can not identify the source position of the v-drag element, please provide an explicit `id` prop.') |
| 169 | |
| 170 | const watchStopHandles: WatchStopHandle[] = [stopWatchBounds] |
| 171 | |
| 172 | const autoHeight = !isArrow && posRaw != null && !Number.isFinite(pos?.[3]) |
| 173 | pos ??= [Number.NaN, Number.NaN, 0] |
| 174 | const width = ref(pos[2]) |
| 175 | const x0 = ref(pos[0] + pos[2] / 2) |
| 176 | |
| 177 | const rotate = ref(isArrow |
| 178 | ? 0 |
| 179 | : (pos[4] ?? 0)) |
| 180 | const rotateRad = computed(() => rotate.value * Math.PI / 180) |
| 181 | const rotateSin = computed(() => Math.sin(rotateRad.value)) |
| 182 | const rotateCos = computed(() => Math.cos(rotateRad.value)) |
| 183 | |
| 184 | const container = ref<HTMLElement>() |
| 185 | const elementZoom = ref(1) |
| 186 | const bounds = ref({ left: 0, top: 0, width: 0, height: 0 }) |
| 187 | const actualHeight = ref(0) |
| 188 | function updateBounds() { |
| 189 | if (!container.value) |
| 190 | return |
| 191 | elementZoom.value = getElementZoom(container.value) |
| 192 | const rect = container.value.getBoundingClientRect() |
| 193 | bounds.value = { |
| 194 | left: rect.left / zoom.value, |
| 195 | top: rect.top / zoom.value, |
| 196 | width: rect.width / zoom.value, |
| 197 | height: rect.height / zoom.value, |
| 198 | } |
| 199 | actualHeight.value = ((bounds.value.width + bounds.value.height) / scale.value / (Math.abs(rotateSin.value) + Math.abs(rotateCos.value)) - width.value) |
| 200 | } |
| 201 | watchStopHandles.push(watch(width, updateBounds, { flush: 'post' })) |
| 202 | |
| 203 | const configuredHeight = ref(pos[3] ?? 0) |
| 204 | const height = autoHeight |
| 205 | ? computed({ |
| 206 | get: () => (autoHeight ? actualHeight.value : configuredHeight.value) || 0, |
| 207 | set: v => !autoHeight && (configuredHeight.value = v), |
| 208 | }) |
| 209 | : configuredHeight |
| 210 | const configuredY0 = autoHeight |
| 211 | ? ref(pos[1]) |
| 212 | : ref(pos[1] + pos[3] / 2) |
| 213 | const y0 = autoHeight |
| 214 | ? computed({ |
| 215 | get: () => configuredY0.value + height.value / 2, |
| 216 | set: v => configuredY0.value = v - height.value / 2, |
| 217 | }) |
| 218 | : configuredY0 |
| 219 | |
| 220 | const containerStyle = computed(() => { |
| 221 | // x0/y0/width/height are in slide coordinates, while a `zoom` on the |
| 222 | // element scales its box in the slide coordinate space as well |
| 223 | const zoomScale = elementZoom.value |
| 224 | return Number.isFinite(x0.value) |
| 225 | ? { |
| 226 | position: 'absolute', |
| 227 | zIndex: 100, |
| 228 | left: `${(x0.value - width.value / 2) / zoomScale}px`, |
| 229 | top: `${(y0.value - height.value / 2) / zoomScale}px`, |
| 230 | width: `${width.value / zoomScale}px`, |
| 231 | height: autoHeight |
| 232 | ? undefined |
| 233 | : `${height.value / zoomScale}px`, |
| 234 | transformOrigin: 'center center', |
| 235 | transform: `rotate(${rotate.value}deg)`, |
| 236 | } satisfies CSSProperties |
| 237 | : { |
| 238 | position: 'absolute', |
| 239 | zIndex: 100, |
| 240 | } satisfies CSSProperties |
| 241 | }) |
| 242 | |
| 243 | watchStopHandles.push( |
| 244 | watch( |
| 245 | [x0, y0, width, height, rotate], |
| 246 | ([x0, y0, w, h, r]) => { |
| 247 | let posStr = [x0 - w / 2, y0 - h / 2, w].map(Math.round).join() |
| 248 | if (autoHeight) { |
| 249 | posStr += dataSource === 'directive' |
| 250 | ? ',NaN' |
| 251 | : ',_' |
| 252 | } |
| 253 | else { |
| 254 | posStr += `,${Math.round(h)}` |
| 255 | } |
| 256 | if (Math.round(r) !== 0) |
| 257 | posStr += `,${Math.round(r)}` |
| 258 | |
| 259 | if (dataSource === 'directive') |
| 260 | posStr = `[${posStr}]` |
| 261 | |
| 262 | updater.value(dragId, posStr, dataSource, markdownSource) |
| 263 | }, |
| 264 | ), |
| 265 | ) |
| 266 | |
| 267 | const state = { |
| 268 | dragId, |
| 269 | dataSource, |
| 270 | markdownSource, |
| 271 | isArrow, |
| 272 | zoom, |
| 273 | autoHeight, |
| 274 | x0, |
| 275 | y0, |
| 276 | width, |
| 277 | height, |
| 278 | rotate, |
| 279 | container, |
| 280 | containerStyle, |
| 281 | watchStopHandles, |
| 282 | dragging: computed((): boolean => activeDragElement.value === state), |
| 283 | mounted() { |
| 284 | if (!enabled) |
| 285 | return |
| 286 | updateBounds() |
| 287 | if (!posRaw) { |
| 288 | setTimeout(() => { |
| 289 | updateBounds() |
| 290 | x0.value = (bounds.value.left + bounds.value.width / 2 - slideLeft.value) / scale.value |
| 291 | y0.value = (bounds.value.top - slideTop.value) / scale.value |
| 292 | width.value = bounds.value.width / scale.value |
| 293 | height.value = bounds.value.height / scale.value |
| 294 | }, 100) |
| 295 | } |
| 296 | }, |
| 297 | unmounted() { |
| 298 | if (!enabled) |
| 299 | return |
| 300 | state.stopDragging() |
| 301 | }, |
| 302 | startDragging(): void { |
| 303 | // Positions are only saved by the dev editor; elsewhere (static builds) |
| 304 | // a stray double-click or double-tap would move an element on screen. |
| 305 | if (!enabled || !(__DEV__ && __SLIDEV_FEATURE_EDITOR__)) |
| 306 | return |
| 307 | updateBounds() |
| 308 | activeDragElement.value = state |
| 309 | }, |
| 310 | stopDragging(): void { |
| 311 | if (!enabled) |
| 312 | return |
| 313 | if (activeDragElement.value === state) |
| 314 | activeDragElement.value = null |
| 315 | }, |
| 316 | } |
| 317 | |
| 318 | watchStopHandles.push( |
| 319 | onClickOutside(container, (ev) => { |
| 320 | const container = document.querySelector('#drag-control-container') |
| 321 | if (container && ev.target && container.contains(ev.target as HTMLElement)) |
| 322 | return |
| 323 | state.stopDragging() |
| 324 | }), |
| 325 | watch(useWindowFocus(), (focused) => { |
| 326 | if (!focused) |
| 327 | state.stopDragging() |
| 328 | }), |
| 329 | ) |
| 330 | |
| 331 | return state |
| 332 | } |
| 333 | |
| 334 | export type DragElementState = ReturnType<typeof useDragElement> |
| 335 |