File size: 12,617 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | import { DOUBLE_CLICK_INTERVAL_THRESHOLD_MS, LONG_HOLD_THRESHOLD } from '@/services/constants';
import { eventDispatcher } from '@/utils/event';
let lastClickTime = 0;
let longHoldTimeout: ReturnType<typeof setTimeout> | null = null;
let keyboardState = {
key: '',
code: '',
ctrlKey: false,
shiftKey: false,
altKey: false,
metaKey: false,
};
const getKeyStatus = (event?: MouseEvent | WheelEvent | TouchEvent) => {
if (event && 'ctrlKey' in event) {
return {
key: keyboardState.key,
code: keyboardState.code,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
};
}
return {
...keyboardState,
};
};
export const handleKeydown = (bookKey: string, event: KeyboardEvent) => {
keyboardState = {
key: event.key,
code: event.code,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
};
if (['Backspace'].includes(event.key)) {
event.preventDefault();
}
if (event.ctrlKey && event.key.toLowerCase() === 'f') {
event.preventDefault();
}
window.postMessage(
{
type: 'iframe-keydown',
bookKey,
key: event.key,
code: event.code,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
},
'*',
);
};
export const handleKeyup = (bookKey: string, event: KeyboardEvent) => {
keyboardState = {
key: '',
code: '',
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
};
window.postMessage(
{
type: 'iframe-keyup',
bookKey,
key: event.key,
code: event.code,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
},
'*',
);
};
export const handleMousedown = (bookKey: string, event: MouseEvent) => {
longHoldTimeout = setTimeout(() => {
longHoldTimeout = null;
}, LONG_HOLD_THRESHOLD);
window.postMessage(
{
type: 'iframe-mousedown',
bookKey,
button: event.button,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
offsetX: event.offsetX,
offsetY: event.offsetY,
...getKeyStatus(event),
},
'*',
);
};
export const handleMouseup = (bookKey: string, event: MouseEvent) => {
// we will handle mouse back and forward buttons ourselves
if ([3, 4].includes(event.button)) {
event.preventDefault();
}
window.postMessage(
{
type: 'iframe-mouseup',
bookKey,
button: event.button,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
offsetX: event.offsetX,
offsetY: event.offsetY,
...getKeyStatus(event),
},
'*',
);
};
export const handleWheel = (bookKey: string, event: WheelEvent) => {
window.postMessage(
{
type: 'iframe-wheel',
bookKey,
deltaMode: event.deltaMode,
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaZ: event.deltaZ,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
offsetX: event.offsetX,
offsetY: event.offsetY,
...getKeyStatus(event),
},
'*',
);
};
export const handleClick = (
bookKey: string,
doubleClickDisabled: React.MutableRefObject<boolean>,
event: MouseEvent,
) => {
const now = Date.now();
if (!doubleClickDisabled.current && now - lastClickTime < DOUBLE_CLICK_INTERVAL_THRESHOLD_MS) {
lastClickTime = now;
window.postMessage(
{
type: 'iframe-double-click',
bookKey,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
offsetX: event.offsetX,
offsetY: event.offsetY,
...getKeyStatus(event),
},
'*',
);
return;
}
lastClickTime = now;
const postSingleClick = () => {
const element = event.target as HTMLElement | null;
if (
element?.closest('sup, a, audio, video') &&
!element?.closest('a.duokan-footnote:not([href])')
) {
return;
}
const footnote = element?.closest('.js_readerFooterNote, .zhangyue-footnote, .duokan-footnote');
if (footnote) {
eventDispatcher.dispatch('footnote-popup', {
bookKey,
element: footnote,
footnote:
footnote.getAttribute('data-wr-footernote') ||
footnote.getAttribute('zy-footnote') ||
footnote.getAttribute('alt') ||
element?.getAttribute('alt') ||
'',
});
return;
}
// if long hold is detected, we don't want to send single click event
if (!longHoldTimeout) {
return;
}
window.postMessage(
{
type: 'iframe-single-click',
bookKey,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
offsetX: event.offsetX,
offsetY: event.offsetY,
...getKeyStatus(event),
},
'*',
);
};
if (!doubleClickDisabled.current) {
setTimeout(() => {
if (Date.now() - lastClickTime >= DOUBLE_CLICK_INTERVAL_THRESHOLD_MS) {
postSingleClick();
}
}, DOUBLE_CLICK_INTERVAL_THRESHOLD_MS);
} else {
postSingleClick();
}
};
const handleTouchEv = (bookKey: string, event: TouchEvent, type: string) => {
const touch = event.targetTouches[0];
const touches = [];
if (touch) {
touches.push({
clientX: touch.clientX,
clientY: touch.clientY,
screenX: touch.screenX,
screenY: touch.screenY,
});
}
window.postMessage(
{
type: type,
bookKey,
timeStamp: Date.now(),
targetTouches: touches,
...getKeyStatus(event),
},
'*',
);
};
export const handleTouchStart = (bookKey: string, event: TouchEvent) => {
handleTouchEv(bookKey, event, 'iframe-touchstart');
};
export const handleTouchMove = (bookKey: string, event: TouchEvent) => {
handleTouchEv(bookKey, event, 'iframe-touchmove');
};
export const handleTouchEnd = (bookKey: string, event: TouchEvent) => {
handleTouchEv(bookKey, event, 'iframe-touchend');
};
export const addLongPressListeners = (bookKey: string, doc: Document) => {
const longPressDuration = 500;
const moveThreshold = 10; // pixels - movement threshold to detect dragging/selection
const pressTimers = new Map<Element, ReturnType<typeof setTimeout>>();
const pressStartPositions = new Map<Element, { x: number; y: number }>();
const handleLongPress = (event: Event, target: HTMLElement) => {
event.preventDefault?.();
// Check if there's an active text selection - if so, don't trigger long-press
const selection = doc.getSelection();
if (selection && selection.toString().length > 0) {
return;
}
if (target.localName === 'img') {
const imgTarget = target as HTMLImageElement;
window.postMessage(
{
type: 'iframe-long-press',
bookKey,
elementType: 'image',
src: imgTarget.src,
},
'*',
);
} else if (target.localName === 'table' || target.closest('table')) {
const tableTarget = (
target.localName === 'table' ? target : target.closest('table')
) as HTMLTableElement;
window.postMessage(
{
type: 'iframe-long-press',
bookKey,
elementType: 'table',
html: tableTarget.outerHTML,
},
'*',
);
}
};
const startPress = (event: Event) => {
const target = event.target as HTMLElement;
const isImage = target.localName === 'img';
const isTableOrInTable = target.localName === 'table' || target.closest('table');
if (!isImage && !isTableOrInTable) return;
const elementToTrack = isImage
? target
: ((target.localName === 'table' ? target : target.closest('table')) as HTMLElement);
// Store initial position for movement detection
if ('clientX' in event && 'clientY' in event) {
const mouseEvent = event as MouseEvent;
pressStartPositions.set(elementToTrack, { x: mouseEvent.clientX, y: mouseEvent.clientY });
} else if ('touches' in event) {
const touchEvent = event as TouchEvent;
const touch = touchEvent.touches[0];
if (touch) {
pressStartPositions.set(elementToTrack, { x: touch.clientX, y: touch.clientY });
}
}
clearTimeout(pressTimers.get(elementToTrack));
const timer = setTimeout(() => handleLongPress(event, elementToTrack), longPressDuration);
pressTimers.set(elementToTrack, timer);
};
const handleMove = (event: Event) => {
const target = event.target as HTMLElement;
const isImage = target.localName === 'img';
const isTableOrInTable = target.localName === 'table' || target.closest('table');
if (!isImage && !isTableOrInTable) return;
const elementToTrack = isImage
? target
: ((target.localName === 'table' ? target : target.closest('table')) as HTMLElement);
// Check if mouse/touch moved beyond threshold - if so, user is probably selecting text or dragging
const startPos = pressStartPositions.get(elementToTrack);
if (startPos) {
let currentX = 0;
let currentY = 0;
if ('clientX' in event && 'clientY' in event) {
const mouseEvent = event as MouseEvent;
currentX = mouseEvent.clientX;
currentY = mouseEvent.clientY;
} else if ('touches' in event) {
const touchEvent = event as TouchEvent;
const touch = touchEvent.touches[0];
if (touch) {
currentX = touch.clientX;
currentY = touch.clientY;
}
}
const distance = Math.sqrt(
Math.pow(currentX - startPos.x, 2) + Math.pow(currentY - startPos.y, 2),
);
// If moved beyond threshold, cancel the long-press
if (distance > moveThreshold) {
clearTimeout(pressTimers.get(elementToTrack));
pressTimers.delete(elementToTrack);
pressStartPositions.delete(elementToTrack);
}
}
};
const cancelPress = (event: Event) => {
const target = event.target as HTMLElement;
const isImage = target.localName === 'img';
const isTableOrInTable = target.localName === 'table' || target.closest('table');
if (!isImage && !isTableOrInTable) return;
const elementToTrack = isImage
? target
: ((target.localName === 'table' ? target : target.closest('table')) as HTMLElement);
clearTimeout(pressTimers.get(elementToTrack));
pressTimers.delete(elementToTrack);
pressStartPositions.delete(elementToTrack);
};
const processElements = () => {
const images = doc.querySelectorAll('img');
const tables = doc.querySelectorAll('table');
images.forEach((img) => {
if (!img.hasAttribute('data-long-press-added')) {
img.setAttribute('data-long-press-added', 'true');
img.addEventListener('mousedown', startPress);
img.addEventListener('mousemove', handleMove);
img.addEventListener('mouseup', cancelPress);
img.addEventListener('mouseleave', cancelPress);
img.addEventListener('touchstart', startPress, { passive: true });
img.addEventListener('touchmove', handleMove, { passive: true });
img.addEventListener('touchend', cancelPress);
}
});
tables.forEach((table) => {
if (!table.hasAttribute('data-long-press-added')) {
table.setAttribute('data-long-press-added', 'true');
table.addEventListener('mousedown', startPress);
table.addEventListener('mousemove', handleMove);
table.addEventListener('mouseup', cancelPress);
table.addEventListener('mouseleave', cancelPress);
table.addEventListener('touchstart', startPress, { passive: true });
table.addEventListener('touchmove', handleMove, { passive: true });
table.addEventListener('touchend', cancelPress);
}
});
};
processElements();
const observer = new MutationObserver((mutations) => {
const hasNewElements = mutations.some((m) => m.type === 'childList' && m.addedNodes.length > 0);
if (hasNewElements) {
processElements();
}
});
observer.observe(doc.body, { childList: true, subtree: true });
return () => {
observer.disconnect();
pressTimers.forEach((timer) => clearTimeout(timer));
};
};
|