mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
feat(reader): improve stylus annotation and finger navigation (#7213)
Detect stylus use so fingers navigate without leaving palm ink. Handle barrel-button erasing, cancel flushed palm strokes, preserve pressure samples, add two-/three-finger history gestures, and replace width swatches with a finer slider. Follow the active scroll axis for finger navigation. Verification before updating the branch onto current main: - Full unit suite: 14,305 passed; 16 skipped. - Focused handwriting tests: 161 passed; Chromium UI checks: 9 passed. - pnpm lint and pnpm build passed; Android debug APK/AAB built. - Android 15 emulator: native pen drawing, finger paging/scrolling without extra ink, dock navigation, palm overlap, erasing, history, and slider. Pressure and barrel-button events were injected; physical Samsung S Pen hardware was not tested. - Barrel-button, palm rejection, empty coalesced samples, and fine-width tests failed before implementation. The horizontal-scroll regression failed because goLeft was not called; it passes with axis-aware routing. Reported by 5thConsecutiveC on GitHub. Refs #7147
This commit is contained in:
parent
3c0cf2012e
commit
a1ea6a9cbf
12 changed files with 429 additions and 91 deletions
|
|
@ -128,15 +128,14 @@ describe('drawing bars', () => {
|
|||
expect(props.onTurnRight).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the pen options from the pen button and closes them on a choice', () => {
|
||||
it('keeps the width slider open while choosing a fine pen width', () => {
|
||||
const props = dockProps();
|
||||
render(<HandwritingDock {...props} />);
|
||||
expect(screen.queryAllByRole('button', { name: 'Pen Size' })).toHaveLength(0);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Pen' }));
|
||||
const sizes = screen.getAllByRole('button', { name: 'Pen Size' });
|
||||
expect(sizes).toHaveLength(4);
|
||||
fireEvent.click(sizes[3]!);
|
||||
expect(props.onSelectWidth).toHaveBeenCalled();
|
||||
expect(screen.queryAllByRole('button', { name: 'Pen Size' })).toHaveLength(0);
|
||||
const slider = screen.getByRole('slider', { name: 'Pen Size' });
|
||||
expect(Number(slider.getAttribute('min'))).toBeLessThan(0.004);
|
||||
fireEvent.change(slider, { target: { value: '0.001' } });
|
||||
expect(props.onSelectWidth).toHaveBeenCalledWith(0.001);
|
||||
expect(screen.getByRole('slider', { name: 'Pen Size' })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { page } from 'vitest/browser';
|
||||
import HandwritingOptions from '@/app/reader/components/handwriting/HandwritingOptions';
|
||||
import { useState } from 'react';
|
||||
|
||||
await import('@/styles/globals.css');
|
||||
|
||||
const h = vi.hoisted(() => ({ isEink: false }));
|
||||
vi.mock('@/hooks/useTranslation', () => ({ useTranslation: () => (key: string) => key }));
|
||||
vi.mock('@/hooks/useResponsiveSize', () => ({ useResponsiveSize: (size: number) => size }));
|
||||
vi.mock('@/store/settingsStore', () => ({
|
||||
useSettingsStore: () => ({ settings: { globalViewSettings: { isEink: h.isEink } } }),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
document.documentElement.removeAttribute('data-eink');
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
document.documentElement.removeAttribute('dir');
|
||||
});
|
||||
|
||||
const Options = ({ marker = false }) => {
|
||||
const [width, setWidth] = useState(marker ? 0.03 : 0.006);
|
||||
return (
|
||||
<div className='eink-bordered bg-base-100 text-base-content inline-flex rounded-2xl p-3'>
|
||||
<HandwritingOptions
|
||||
tool={marker ? 'marker' : 'pen'}
|
||||
color='#1a1a1a'
|
||||
width={width}
|
||||
onSelectWidth={setWidth}
|
||||
onSelectColor={() => {}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
describe('handwriting width slider in Chromium', () => {
|
||||
for (const theme of ['default-light', 'default-dark']) {
|
||||
for (const eink of [false, true]) {
|
||||
for (const direction of ['ltr', 'rtl']) {
|
||||
it(`fits on a phone in ${theme}, eink=${eink}, ${direction}`, async () => {
|
||||
await page.viewport(320, 640);
|
||||
h.isEink = eink;
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
document.documentElement.setAttribute('data-eink', String(eink));
|
||||
document.documentElement.setAttribute('dir', direction);
|
||||
render(<Options />);
|
||||
const slider = screen.getByRole('slider', { name: 'Pen Size' }) as HTMLInputElement;
|
||||
fireEvent.change(slider, { target: { value: '0.0005' } });
|
||||
expect(slider.value).toBe('0.0005');
|
||||
expect(slider.getBoundingClientRect().width).toBeGreaterThan(100);
|
||||
expect(slider.getBoundingClientRect().left).toBeGreaterThanOrEqual(0);
|
||||
expect(slider.getBoundingClientRect().right).toBeLessThanOrEqual(320);
|
||||
expect(getComputedStyle(slider).display).not.toBe('none');
|
||||
expect(screen.queryAllByRole('button', { name: 'Ink Color' })).toHaveLength(eink ? 0 : 5);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('keeps the marker broad on a tablet', async () => {
|
||||
await page.viewport(1024, 768);
|
||||
h.isEink = false;
|
||||
render(<Options marker />);
|
||||
const slider = screen.getByRole('slider', { name: 'Pen Size' }) as HTMLInputElement;
|
||||
expect(slider.min).toBe('0.02');
|
||||
fireEvent.change(slider, { target: { value: '0.04' } });
|
||||
expect(slider.value).toBe('0.04');
|
||||
});
|
||||
});
|
||||
|
|
@ -108,3 +108,65 @@ describe('useHandwriting after a page turn', () => {
|
|||
await waitFor(() => expect(result.current.pageRect.left).toBe(0));
|
||||
});
|
||||
});
|
||||
|
||||
describe('useHandwriting finger navigation', () => {
|
||||
it.each([
|
||||
false,
|
||||
true,
|
||||
])('routes a finger swipe through drawing mode (scrolled=%s)', async (scrolled) => {
|
||||
const { view } = mountView();
|
||||
const goRight = vi.fn();
|
||||
const next = vi.fn();
|
||||
Object.assign(view, { goRight, next });
|
||||
h.readerState.getView = () => view;
|
||||
h.readerState.getViewSettings = () => ({ scrolled });
|
||||
const { result } = renderHook(() => useHandwriting('book-1'));
|
||||
const canvas = document.createElement('div');
|
||||
canvas.setPointerCapture = vi.fn();
|
||||
await act(() => result.current.attach(canvas));
|
||||
const pointer = (type: string, pointerType: string, x: number, y: number) => {
|
||||
const event = new Event(type);
|
||||
Object.assign(event, { pointerId: 1, pointerType, clientX: x, clientY: y });
|
||||
canvas.dispatchEvent(event);
|
||||
};
|
||||
act(() => {
|
||||
pointer('pointerover', 'pen', 0, 0);
|
||||
pointer('pointerdown', 'touch', 200, 200);
|
||||
pointer('pointerup', 'touch', scrolled ? 200 : 100, scrolled ? 100 : 200);
|
||||
});
|
||||
expect(scrolled ? next : goRight).toHaveBeenCalledOnce();
|
||||
expect(result.current.layers.flatMap((layer) => layer.strokes)).toEqual([]);
|
||||
await act(() => result.current.detach());
|
||||
h.readerState.getViewSettings = () => ({ scrolled: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useHandwriting horizontal scrolling', () => {
|
||||
it('navigates by the physical side when swiping right', async () => {
|
||||
const { view } = mountView();
|
||||
const goLeft = vi.fn();
|
||||
const next = vi.fn();
|
||||
Object.assign(view, { goLeft, next });
|
||||
Object.assign(view.renderer, { scrollProp: 'scrollLeft' });
|
||||
h.readerState.getView = () => view;
|
||||
h.readerState.getViewSettings = () => ({ scrolled: true });
|
||||
const { result } = renderHook(() => useHandwriting('book-1'));
|
||||
const canvas = document.createElement('div');
|
||||
canvas.setPointerCapture = vi.fn();
|
||||
await act(() => result.current.attach(canvas));
|
||||
const pointer = (type: string, pointerType: string, clientX: number) => {
|
||||
const event = new Event(type);
|
||||
Object.assign(event, { pointerId: 1, pointerType, clientX, clientY: 200 });
|
||||
canvas.dispatchEvent(event);
|
||||
};
|
||||
act(() => {
|
||||
pointer('pointerover', 'pen', 0);
|
||||
pointer('pointerdown', 'touch', 100);
|
||||
pointer('pointerup', 'touch', 200);
|
||||
});
|
||||
expect(goLeft).toHaveBeenCalledOnce();
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
await act(() => result.current.detach());
|
||||
h.readerState.getViewSettings = () => ({ scrolled: false });
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ describe('handwriting pen options', () => {
|
|||
expect(DEFAULT_HANDWRITING_WIDTH).toBe(0.006);
|
||||
});
|
||||
|
||||
it('offers no hairline pen: the finest is still a solid line on a phone', () => {
|
||||
expect(Math.min(...HANDWRITING_WIDTHS)).toBeGreaterThanOrEqual(0.004);
|
||||
it('offers a fine pen for stylus handwriting', () => {
|
||||
expect(Math.min(...HANDWRITING_WIDTHS)).toBeLessThanOrEqual(0.001);
|
||||
});
|
||||
|
||||
it('exposes the default color as the first swatch, so a fresh install has a selected dot', () => {
|
||||
|
|
|
|||
|
|
@ -365,3 +365,19 @@ describe('HandwritingService pen width on a wide page (#7094)', () => {
|
|||
expect(editor.strokes('sec:1')[0]!.width).toBe(0.03);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HandwritingService cancelled input', () => {
|
||||
it('drops already-flushed palm points before committing the pen stroke', () => {
|
||||
const editor = new HandwritingEditor();
|
||||
const service = new HandwritingService(editor, 'pdf:1', rect);
|
||||
const input = service as unknown as {
|
||||
onBatch: (points: InkPoint[], kind: string, erase: boolean) => void;
|
||||
};
|
||||
input.onBatch([[0.8, 0.8]], 'move', false);
|
||||
expect(service.liveStrokes()).toHaveLength(1);
|
||||
input.onBatch([], 'cancel', false);
|
||||
expect(service.liveStrokes()).toEqual([]);
|
||||
input.onBatch([[0.1, 0.1, 0.8]], 'end', false);
|
||||
expect(editor.strokes('pdf:1')[0]!.points).toEqual([[0.1, 0.1, 0.8]]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ describe('PointerHandwritingBackend palm rejection', () => {
|
|||
expect(points.every((p) => p.length === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts a new touch stroke after the pen lifts', () => {
|
||||
it('reserves touch for navigation after the pen lifts', () => {
|
||||
const { el, points } = setup();
|
||||
|
||||
dispatch(el, 'pointerdown', { pointerId: 1, pointerType: 'pen' });
|
||||
|
|
@ -100,17 +100,17 @@ describe('PointerHandwritingBackend palm rejection', () => {
|
|||
dispatch(el, 'pointerdown', { pointerId: 3, pointerType: 'touch', clientX: 70, clientY: 80 });
|
||||
dispatch(el, 'pointerup', { pointerId: 3, pointerType: 'touch' });
|
||||
|
||||
expect(points).toHaveLength(2);
|
||||
expect(points).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not steal a second concurrent touch while the first is drawing', () => {
|
||||
it('cancels finger ink when a second contact starts a gesture', () => {
|
||||
const { el, points } = setup();
|
||||
|
||||
dispatch(el, 'pointerdown', { pointerId: 5, pointerType: 'touch', clientX: 10, clientY: 10 });
|
||||
dispatch(el, 'pointerdown', { pointerId: 6, pointerType: 'touch', clientX: 99, clientY: 99 });
|
||||
dispatch(el, 'pointerup', { pointerId: 5, pointerType: 'touch' });
|
||||
|
||||
expect(points).toHaveLength(1);
|
||||
expect(points).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -173,7 +173,7 @@ describe('PointerHandwritingBackend', () => {
|
|||
dispatch(el, 'pointermove', { clientX: 2, clientY: 2 });
|
||||
dispatch(el, 'pointercancel', {});
|
||||
await new Promise((r) => requestAnimationFrame(r));
|
||||
expect(onBatch).not.toHaveBeenCalled();
|
||||
expect(onBatch).toHaveBeenCalledExactlyOnceWith([], 'cancel', false);
|
||||
});
|
||||
|
||||
it('detects eraser via button 5 and omits pressure for mouse', async () => {
|
||||
|
|
@ -218,3 +218,127 @@ describe('PointerHandwritingBackend', () => {
|
|||
expect(onBatch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('stylus input regressions (#7147)', () => {
|
||||
it('uses the S Pen barrel button as a temporary eraser', () => {
|
||||
const el = new FakeElement();
|
||||
const backend = new PointerHandwritingBackend();
|
||||
const batch = vi.fn();
|
||||
backend.onBatch(batch);
|
||||
backend.attach(el as unknown as HTMLElement, identity);
|
||||
dispatch(el, 'pointerdown', { buttons: 3, button: 2 });
|
||||
dispatch(el, 'pointerup', {});
|
||||
expect(batch).toHaveBeenLastCalledWith(expect.any(Array), 'end', true);
|
||||
dispatch(el, 'pointerdown', { buttons: 1 });
|
||||
dispatch(el, 'pointerup', {});
|
||||
expect(batch).toHaveBeenLastCalledWith(expect.any(Array), 'end', false);
|
||||
});
|
||||
|
||||
it('does not draw a resting palm after a pen stroke', () => {
|
||||
const el = new FakeElement();
|
||||
const backend = new PointerHandwritingBackend();
|
||||
const batch = vi.fn();
|
||||
backend.onBatch(batch);
|
||||
backend.attach(el as unknown as HTMLElement, identity);
|
||||
dispatch(el, 'pointerdown', {});
|
||||
dispatch(el, 'pointerup', {});
|
||||
batch.mockClear();
|
||||
dispatch(el, 'pointerdown', { pointerType: 'touch', pointerId: 8 });
|
||||
dispatch(el, 'pointerup', { pointerType: 'touch', pointerId: 8 });
|
||||
expect(batch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps a sample when getCoalescedEvents returns an empty array', () => {
|
||||
const el = new FakeElement();
|
||||
const backend = new PointerHandwritingBackend();
|
||||
const batch = vi.fn();
|
||||
backend.onBatch(batch);
|
||||
backend.attach(el as unknown as HTMLElement, identity);
|
||||
dispatch(el, 'pointerdown', { pressure: 0.2 });
|
||||
dispatch(el, 'pointermove', { pressure: 0.9, clientX: 5, getCoalescedEvents: () => [] });
|
||||
dispatch(el, 'pointerup', {});
|
||||
expect(batch.mock.calls[0]![0]).toEqual([
|
||||
[0, 0, 0.2],
|
||||
[5, 0, 0.9],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('finger gestures while drawing', () => {
|
||||
const setup = () => {
|
||||
const el = new FakeElement();
|
||||
const backend = new PointerHandwritingBackend();
|
||||
const gesture = vi.fn();
|
||||
const batch = vi.fn();
|
||||
backend.onBatch(batch);
|
||||
backend.onGesture(gesture);
|
||||
backend.attach(el as unknown as HTMLElement, identity);
|
||||
dispatch(el, 'pointerover', {});
|
||||
return { el, backend, gesture, batch };
|
||||
};
|
||||
const touch = (el: FakeElement, type: string, id: number, x = id * 20, y = 10) =>
|
||||
dispatch(el, type, { pointerId: id, pointerType: 'touch', clientX: x, clientY: y });
|
||||
|
||||
it.each([2, 3])('uses a %i-finger tap for history without ink', (count) => {
|
||||
const { el, gesture, batch } = setup();
|
||||
for (let i = 1; i <= count; i++) touch(el, 'pointerdown', i);
|
||||
// Each finger can wobble without moving the gesture beyond its tap slop.
|
||||
for (let i = 1; i <= count; i++) touch(el, 'pointermove', i, i * 20 + 1);
|
||||
for (let i = 1; i <= count; i++) touch(el, 'pointerup', i);
|
||||
expect(gesture).toHaveBeenCalledExactlyOnceWith({ action: count === 2 ? 'undo' : 'redo' });
|
||||
expect(batch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('navigates with a finger swipe after detecting a pen', () => {
|
||||
const { el, gesture, batch } = setup();
|
||||
touch(el, 'pointerdown', 1, 100);
|
||||
touch(el, 'pointermove', 1, 40);
|
||||
touch(el, 'pointerup', 1, 40);
|
||||
expect(gesture).toHaveBeenCalledExactlyOnceWith({ action: 'swipe', dx: -60, dy: 0 });
|
||||
expect(batch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores a moving palm even if the pen lifts before the palm', () => {
|
||||
const { el, gesture } = setup();
|
||||
dispatch(el, 'pointerdown', { pointerId: 10 });
|
||||
touch(el, 'pointerdown', 1, 100);
|
||||
dispatch(el, 'pointerup', { pointerId: 10 });
|
||||
touch(el, 'pointermove', 1, 20);
|
||||
touch(el, 'pointerup', 1, 20);
|
||||
expect(gesture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects multi-finger drags and cancelled gestures', () => {
|
||||
const { el, gesture } = setup();
|
||||
touch(el, 'pointerdown', 1);
|
||||
touch(el, 'pointerdown', 2);
|
||||
touch(el, 'pointermove', 1, 150);
|
||||
touch(el, 'pointerup', 1, 150);
|
||||
touch(el, 'pointerup', 2);
|
||||
touch(el, 'pointerdown', 1);
|
||||
touch(el, 'pointerdown', 2);
|
||||
touch(el, 'pointercancel', 1);
|
||||
touch(el, 'pointerup', 2);
|
||||
expect(gesture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('splits strokes when the barrel button changes during contact', () => {
|
||||
const { el, batch } = setup();
|
||||
dispatch(el, 'pointerdown', { pointerId: 10, buttons: 1 });
|
||||
dispatch(el, 'pointermove', { pointerId: 10, buttons: 3, clientX: 5 });
|
||||
expect(batch).toHaveBeenLastCalledWith([[0, 0, 0.5]], 'end', false);
|
||||
dispatch(el, 'pointerup', { pointerId: 10 });
|
||||
expect(batch).toHaveBeenLastCalledWith([[5, 0, 0.5]], 'end', true);
|
||||
});
|
||||
|
||||
it('detach drops pending input before reattaching', () => {
|
||||
const { el, backend, batch } = setup();
|
||||
dispatch(el, 'pointerdown', {});
|
||||
backend.detach();
|
||||
expect(batch).toHaveBeenLastCalledWith([], 'cancel', false);
|
||||
backend.attach(el as unknown as HTMLElement, identity);
|
||||
dispatch(el, 'pointerdown', { clientX: 9 });
|
||||
dispatch(el, 'pointerup', {});
|
||||
expect(batch).toHaveBeenLastCalledWith([[9, 0, 0.5]], 'end', false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -87,7 +87,7 @@ export const HandwritingDock: React.FC<HandwritingDockProps> = ({
|
|||
color={penColor}
|
||||
width={penWidth}
|
||||
onSelectColor={choose(onSelectColor)}
|
||||
onSelectWidth={choose(onSelectWidth)}
|
||||
onSelectWidth={onSelectWidth}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import clsx from 'clsx';
|
||||
import React from 'react';
|
||||
import { FaCheck } from 'react-icons/fa';
|
||||
|
||||
|
|
@ -21,15 +20,6 @@ interface HandwritingOptionsProps {
|
|||
onSelectWidth: (width: number) => void;
|
||||
}
|
||||
|
||||
const MIN_DOT = 3;
|
||||
const MAX_DOT = 7;
|
||||
/** Width swatch radius, scaled so the row reads as increasing weight. */
|
||||
const dotFor = (width: number, widths: readonly number[]) => {
|
||||
const min = widths[0]!;
|
||||
const max = widths[widths.length - 1]!;
|
||||
return MIN_DOT + ((width - min) / (max - min)) * (MAX_DOT - MIN_DOT);
|
||||
};
|
||||
|
||||
/** The active tool's colors and widths. B&W e-ink has no colors to offer. */
|
||||
const HandwritingOptions: React.FC<HandwritingOptionsProps> = ({
|
||||
tool,
|
||||
|
|
@ -48,49 +38,34 @@ const HandwritingOptions: React.FC<HandwritingOptionsProps> = ({
|
|||
const widths = tool === 'marker' ? MARKER_WIDTHS : HANDWRITING_WIDTHS;
|
||||
|
||||
return (
|
||||
<div className='flex shrink-0 items-center gap-1.5'>
|
||||
{showColors &&
|
||||
colors.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type='button'
|
||||
aria-label={_('Ink Color')}
|
||||
aria-pressed={color === hex}
|
||||
onClick={() => onSelectColor(hex)}
|
||||
style={{ width: swatchSize, height: swatchSize, backgroundColor: hex }}
|
||||
className='flex shrink-0 items-center justify-center rounded-full p-0'
|
||||
>
|
||||
{color === hex && <FaCheck size={checkSize} className='text-white' />}
|
||||
</button>
|
||||
))}
|
||||
{showColors && <div className='bg-base-content/20 mx-0.5 h-5 w-px shrink-0' />}
|
||||
{widths.map((value) => {
|
||||
const dot = dotFor(value, widths);
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type='button'
|
||||
aria-label={_('Pen Size')}
|
||||
aria-pressed={width === value}
|
||||
onClick={() => onSelectWidth(value)}
|
||||
style={{ width: swatchSize, height: swatchSize }}
|
||||
className={clsx(
|
||||
'flex shrink-0 items-center justify-center rounded-full p-0',
|
||||
width === value ? 'border-base-content border-2' : 'border-base-content/20 border',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={clsx(!showColors && 'bg-base-content')}
|
||||
style={{
|
||||
width: dot * 2,
|
||||
height: dot * 2,
|
||||
borderRadius: dot,
|
||||
backgroundColor: showColors ? color : undefined,
|
||||
}}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<div className='flex flex-col gap-3'>
|
||||
{showColors && (
|
||||
<div className='flex items-center gap-1.5'>
|
||||
{colors.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type='button'
|
||||
aria-label={_('Ink Color')}
|
||||
aria-pressed={color === hex}
|
||||
onClick={() => onSelectColor(hex)}
|
||||
style={{ width: swatchSize, height: swatchSize, backgroundColor: hex }}
|
||||
className='flex shrink-0 items-center justify-center rounded-full p-0'
|
||||
>
|
||||
{color === hex && <FaCheck size={checkSize} className='text-white' />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type='range'
|
||||
aria-label={_('Pen Size')}
|
||||
min={widths[0]}
|
||||
max={widths[widths.length - 1]}
|
||||
step={0.0005}
|
||||
value={width}
|
||||
onChange={(event) => onSelectWidth(Number(event.target.value))}
|
||||
className='range range-xs eink-bordered w-40'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -321,6 +321,20 @@ export function useHandwriting(bookKey: string) {
|
|||
[getView, bookKey, scrolled],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
serviceRef.current?.onGesture((gesture) => {
|
||||
if (gesture.action !== 'swipe') return;
|
||||
const { dx, dy } = gesture;
|
||||
const view = getView(bookKey);
|
||||
if (scrolled && view?.renderer.scrollProp !== 'scrollLeft') {
|
||||
if (Math.abs(dy) > Math.abs(dx)) void (dy > 0 ? view?.prev() : view?.next());
|
||||
} else if (Math.abs(dx) > Math.abs(dy)) {
|
||||
if (dx > 0) view?.goLeft();
|
||||
else view?.goRight();
|
||||
}
|
||||
});
|
||||
}, [scrolled, getView, bookKey]);
|
||||
|
||||
// Scrolled views show several sections or pages at once: send each stroke
|
||||
// to the one it is drawn over, pinned to that section's text or page.
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,11 @@ export interface InkTarget {
|
|||
rect: PageRect;
|
||||
anchoring: InkAnchoring | null;
|
||||
}
|
||||
import { PointerHandwritingBackend } from './pointerBackend';
|
||||
import {
|
||||
PointerHandwritingBackend,
|
||||
type InkGesture,
|
||||
type PointerBatchKind,
|
||||
} from './pointerBackend';
|
||||
import { BooxHandwritingBackend, queryPenCapabilities } from './booxBackend';
|
||||
import { isTauriAppPlatform } from '@/services/environment';
|
||||
import { getOSPlatform } from '@/utils/misc';
|
||||
|
|
@ -278,6 +282,14 @@ export class HandwritingService {
|
|||
this.onRender?.();
|
||||
}
|
||||
|
||||
onGesture(listener: (gesture: InkGesture) => void) {
|
||||
this.pointer.onGesture((gesture) => {
|
||||
if (gesture.action === 'undo') this.undo();
|
||||
else if (gesture.action === 'redo') this.redo();
|
||||
else listener(gesture);
|
||||
});
|
||||
}
|
||||
|
||||
async attach(el: HTMLElement) {
|
||||
this.backend = await detectPenBackend({
|
||||
queryNative:
|
||||
|
|
@ -356,7 +368,13 @@ export class HandwritingService {
|
|||
return pinned;
|
||||
}
|
||||
|
||||
private onBatch(points: InkPoint[], kind: 'move' | 'end', erase: boolean) {
|
||||
private onBatch(points: InkPoint[], kind: PointerBatchKind, erase: boolean) {
|
||||
if (kind === 'cancel') {
|
||||
this.live = [];
|
||||
this.eraseTail = null;
|
||||
this.onRender?.();
|
||||
return;
|
||||
}
|
||||
if (erase || this.liveErase) {
|
||||
const path = this.eraseTail ? [this.eraseTail, ...points] : points;
|
||||
if (path.length) {
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export const HANDWRITING_COLORS = [
|
|||
* Pen widths as a fraction of page width. The stored value is normalized, so
|
||||
* the same setting reads the same relative thickness on any page size.
|
||||
*/
|
||||
export const HANDWRITING_WIDTHS = [0.004, DEFAULT_HANDWRITING_WIDTH, 0.01, 0.016] as const;
|
||||
export const HANDWRITING_WIDTHS = [0.0005, DEFAULT_HANDWRITING_WIDTH, 0.01, 0.016] as const;
|
||||
|
||||
/**
|
||||
* Widest page (CSS px) a pen width grows with. Text doesn't grow with the
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import type { InkPoint } from './model';
|
||||
|
||||
export type PointerBatchKind = 'move' | 'end';
|
||||
export type PointerBatchKind = 'move' | 'end' | 'cancel';
|
||||
export type PointerBatchListener = (
|
||||
points: InkPoint[],
|
||||
kind: PointerBatchKind,
|
||||
erase: boolean,
|
||||
) => void;
|
||||
|
||||
export type InkGesture = { action: 'undo' | 'redo' } | { action: 'swipe'; dx: number; dy: number };
|
||||
|
||||
/**
|
||||
* Generic pointer-event backend: the platform-neutral fallback used on
|
||||
* every device (web, desktop, iOS, non-BOOX Android). Listens on a single
|
||||
|
|
@ -24,6 +26,19 @@ export class PointerHandwritingBackend {
|
|||
private activePointerType: string | null = null;
|
||||
private erasing = false;
|
||||
|
||||
// Once a stylus is seen, fingers navigate instead of leaving palm marks.
|
||||
private penSeen = false;
|
||||
private gestureListener: ((gesture: InkGesture) => void) | null = null;
|
||||
private touches = new Map<number, { x: number; y: number }>();
|
||||
private touchStart = { x: 0, y: 0, at: 0 };
|
||||
private touchCount = 0;
|
||||
private touchMoved = false;
|
||||
private touchBlocked = false;
|
||||
|
||||
onGesture(listener: (gesture: InkGesture) => void) {
|
||||
this.gestureListener = listener;
|
||||
}
|
||||
|
||||
attach(el: HTMLElement, toPage: (x: number, y: number) => InkPoint) {
|
||||
this.detach();
|
||||
this.el = el;
|
||||
|
|
@ -32,6 +47,8 @@ export class PointerHandwritingBackend {
|
|||
el.addEventListener('pointermove', this.onMove);
|
||||
el.addEventListener('pointerup', this.onUp);
|
||||
el.addEventListener('pointercancel', this.onCancel);
|
||||
el.addEventListener('pointerover', this.onHover);
|
||||
el.addEventListener('lostpointercapture', this.onCancel);
|
||||
el.addEventListener('touchstart', this.claimTouch, { passive: false });
|
||||
el.addEventListener('touchmove', this.claimTouch, { passive: false });
|
||||
}
|
||||
|
|
@ -42,6 +59,10 @@ export class PointerHandwritingBackend {
|
|||
this.el.removeEventListener('pointermove', this.onMove);
|
||||
this.el.removeEventListener('pointerup', this.onUp);
|
||||
this.el.removeEventListener('pointercancel', this.onCancel);
|
||||
this.el.removeEventListener('pointerover', this.onHover);
|
||||
this.el.removeEventListener('lostpointercapture', this.onCancel);
|
||||
this.cancelStroke();
|
||||
this.touches.clear();
|
||||
this.el.removeEventListener('touchstart', this.claimTouch);
|
||||
this.el.removeEventListener('touchmove', this.claimTouch);
|
||||
this.el = null;
|
||||
|
|
@ -66,28 +87,27 @@ export class PointerHandwritingBackend {
|
|||
};
|
||||
|
||||
private isEraserEvent(e: PointerEvent) {
|
||||
// Stylus eraser tip; buttons bit 5 (32) covers the barrel-eraser button
|
||||
// some pens report while still using the drawing tip.
|
||||
return e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
|
||||
// Eraser tip (32), or barrel button (2), including the S Pen.
|
||||
return e.pointerType === 'pen' && (e.button === 5 || e.button === 2 || (e.buttons & 34) !== 0);
|
||||
}
|
||||
|
||||
private onDown = (e: PointerEvent) => {
|
||||
if (!this.toPage) return;
|
||||
const isTouch = e.pointerType === 'touch';
|
||||
|
||||
// Palm rejection. A resting hand reaches the digitizer before the pen
|
||||
// does, so the touch has to give way when a pen arrives — otherwise the
|
||||
// palm claims the one active-pointer slot and the intended stroke is
|
||||
// silently discarded, which is worse than a stray mark. The reverse order
|
||||
// (pen already down) needs no special case: the active-pointer guard below
|
||||
// already rejects the extra contact.
|
||||
if (isTouch && this.activePointerId !== null) return;
|
||||
if (!isTouch && this.activePointerType === 'touch') {
|
||||
// Hand the slot over: drop the palm's queued points without committing a
|
||||
// stroke for it, then claim it for the pen.
|
||||
this.pending = [];
|
||||
this.activePointerId = null;
|
||||
this.activePointerType = null;
|
||||
this.onHover(e);
|
||||
if (isTouch) {
|
||||
if (!this.touches.size) {
|
||||
this.touchStart = { x: e.clientX, y: e.clientY, at: Date.now() };
|
||||
this.touchCount = 0;
|
||||
this.touchMoved = false;
|
||||
this.touchBlocked = this.activePointerType === 'pen';
|
||||
}
|
||||
this.touches.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
this.touchCount = Math.max(this.touchCount, this.touches.size);
|
||||
if (this.touches.size > 1 && this.activePointerType === 'touch') this.cancelStroke();
|
||||
this.el?.setPointerCapture(e.pointerId);
|
||||
if (this.penSeen || this.touchCount > 1 || this.touchBlocked) return;
|
||||
}
|
||||
if (this.activePointerId !== null) return;
|
||||
|
||||
|
|
@ -99,14 +119,45 @@ export class PointerHandwritingBackend {
|
|||
this.schedule();
|
||||
};
|
||||
|
||||
private onHover = (e: PointerEvent) => {
|
||||
if (e.pointerType !== 'pen') return;
|
||||
this.penSeen = true;
|
||||
if (this.touches.size) this.touchBlocked = true;
|
||||
if (this.activePointerType === 'touch') this.cancelStroke();
|
||||
};
|
||||
|
||||
private onMove = (e: PointerEvent) => {
|
||||
this.onHover(e);
|
||||
const origin = this.touches.get(e.pointerId);
|
||||
if (origin && Math.hypot(e.clientX - origin.x, e.clientY - origin.y) > 12) {
|
||||
this.touchMoved = true;
|
||||
}
|
||||
if (e.pointerId !== this.activePointerId || !this.toPage) return;
|
||||
const events = e.getCoalescedEvents?.() ?? [e];
|
||||
const erasing = this.isEraserEvent(e);
|
||||
if (erasing !== this.erasing) {
|
||||
this.flush('end');
|
||||
this.erasing = erasing;
|
||||
}
|
||||
const coalesced = e.getCoalescedEvents?.();
|
||||
const events = coalesced?.length ? coalesced : [e];
|
||||
for (const ev of events) this.pending.push(this.samplePoint(ev));
|
||||
this.schedule();
|
||||
};
|
||||
|
||||
private onUp = (e: PointerEvent) => {
|
||||
const origin = this.touches.get(e.pointerId);
|
||||
if (origin && Math.hypot(e.clientX - origin.x, e.clientY - origin.y) > 12)
|
||||
this.touchMoved = true;
|
||||
if (this.touches.delete(e.pointerId) && !this.touches.size && !this.touchBlocked) {
|
||||
const dx = e.clientX - this.touchStart.x;
|
||||
const dy = e.clientY - this.touchStart.y;
|
||||
if (this.touchCount === 1 && this.penSeen && Math.hypot(dx, dy) >= 40) {
|
||||
this.gestureListener?.({ action: 'swipe', dx, dy });
|
||||
} else if (!this.touchMoved && Date.now() - this.touchStart.at < 300) {
|
||||
if (this.touchCount === 2) this.gestureListener?.({ action: 'undo' });
|
||||
if (this.touchCount === 3) this.gestureListener?.({ action: 'redo' });
|
||||
}
|
||||
}
|
||||
if (e.pointerId !== this.activePointerId) return;
|
||||
this.flush('end');
|
||||
this.activePointerId = null;
|
||||
|
|
@ -114,11 +165,19 @@ export class PointerHandwritingBackend {
|
|||
};
|
||||
|
||||
private onCancel = (e: PointerEvent) => {
|
||||
if (e.pointerId !== this.activePointerId) return;
|
||||
if (this.touches.delete(e.pointerId)) this.touchBlocked = true;
|
||||
if (e.pointerId === this.activePointerId) this.cancelStroke();
|
||||
};
|
||||
|
||||
private cancelStroke() {
|
||||
const active = this.activePointerId;
|
||||
this.pending = [];
|
||||
this.activePointerId = null;
|
||||
this.activePointerType = null;
|
||||
};
|
||||
if (active !== null) {
|
||||
this.listener?.([], 'cancel', this.erasing);
|
||||
}
|
||||
}
|
||||
|
||||
private samplePoint(e: PointerEvent): InkPoint {
|
||||
const p = this.toPage!(e.clientX, e.clientY);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue