@papyrus-sdk/ui-react-native 0.2.35-beta.1 → 0.2.35-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/index.d.mts +31 -3
- package/dist/index.d.ts +31 -3
- package/dist/index.js +2881 -1734
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2639 -1484
- package/dist/index.mjs.map +1 -1
- package/package.json +10 -7
- package/runtime/epubAnnotations.js +118 -0
- package/runtime/epubAnnotations.test.ts +31 -0
- package/runtime/epubSelectionMenu.test.ts +39 -0
- package/runtime/index.html +310 -15
- package/runtime/runtime.js +310 -15
- package/runtime/syncComicRuntime.mjs +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@papyrus-sdk/ui-react-native",
|
|
3
|
-
"version": "0.2.35-beta.
|
|
3
|
+
"version": "0.2.35-beta.11",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"papyrus",
|
|
@@ -39,21 +39,23 @@
|
|
|
39
39
|
"url": "https://github.com/solrachix/Papyrus/issues"
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|
|
42
|
-
"build": "node runtime/syncComicRuntime.mjs && tsup"
|
|
42
|
+
"build": "node runtime/syncComicRuntime.mjs && tsup",
|
|
43
|
+
"check:ink-worklets": "pnpm run build && node ../../scripts/ci/check-native-ink-worklets.cjs"
|
|
43
44
|
},
|
|
44
45
|
"dependencies": {
|
|
45
46
|
"react-native-svg": "^15.5.0"
|
|
46
47
|
},
|
|
47
48
|
"peerDependencies": {
|
|
48
|
-
"@papyrus-sdk/core": "
|
|
49
|
-
"@papyrus-sdk/engine-native": "
|
|
50
|
-
"@papyrus-sdk/types": "
|
|
49
|
+
"@papyrus-sdk/core": "0.2.23-beta.3",
|
|
50
|
+
"@papyrus-sdk/engine-native": "0.2.22-beta.9",
|
|
51
|
+
"@papyrus-sdk/types": "0.2.16-beta.3",
|
|
51
52
|
"@react-native-clipboard/clipboard": "^1.16.3",
|
|
52
53
|
"react": ">=18.2.0 <20",
|
|
53
54
|
"react-native": ">=0.81.0",
|
|
54
55
|
"react-native-gesture-handler": ">=2.28.0",
|
|
55
56
|
"react-native-safe-area-context": "^5.6.2",
|
|
56
|
-
"react-native-webview": ">=13"
|
|
57
|
+
"react-native-webview": ">=13",
|
|
58
|
+
"react-native-reanimated": "^3.19.5"
|
|
57
59
|
},
|
|
58
60
|
"peerDependenciesMeta": {
|
|
59
61
|
"react-native-webview": {
|
|
@@ -69,6 +71,7 @@
|
|
|
69
71
|
"react": "^19.1.0",
|
|
70
72
|
"react-native": "^0.81.0",
|
|
71
73
|
"react-native-gesture-handler": "~2.28.0",
|
|
72
|
-
"react-native-safe-area-context": "^5.6.2"
|
|
74
|
+
"react-native-safe-area-context": "^5.6.2",
|
|
75
|
+
"react-native-reanimated": "3.19.5"
|
|
73
76
|
}
|
|
74
77
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
(function (root, factory) {
|
|
2
|
+
if (typeof module === 'object' && module.exports) module.exports = factory();
|
|
3
|
+
else root.PapyrusEpubAnnotations = factory();
|
|
4
|
+
})(typeof window !== 'undefined' ? window : globalThis, function () {
|
|
5
|
+
function validAnchor(anchor) {
|
|
6
|
+
return anchor && anchor.version === 1 && anchor.kind === 'epub-cfi' &&
|
|
7
|
+
typeof anchor.cfiRange === 'string' && anchor.cfiRange.length <= 4096 && /^epubcfi\([^\n<>]+\)$/.test(anchor.cfiRange) &&
|
|
8
|
+
typeof anchor.href === 'string' && !/^(javascript|data):/i.test(anchor.href) &&
|
|
9
|
+
typeof anchor.quote === 'string' && anchor.quote.length > 0 && anchor.quote.length <= 100000;
|
|
10
|
+
}
|
|
11
|
+
function textNodes(document) {
|
|
12
|
+
var walker = document.createTreeWalker(document.body, 4);
|
|
13
|
+
var nodes = [], text = '', node;
|
|
14
|
+
while ((node = walker.nextNode())) {
|
|
15
|
+
if (node.parentElement.closest('script,style,[data-papyrus-overlay]')) continue;
|
|
16
|
+
nodes.push({node:node, start:text.length}); text += node.textContent;
|
|
17
|
+
}
|
|
18
|
+
return {nodes:nodes,text:text};
|
|
19
|
+
}
|
|
20
|
+
function recoverRange(document, anchor) {
|
|
21
|
+
var source = textNodes(document), match = null, start = source.text.indexOf(anchor.quote);
|
|
22
|
+
while (start >= 0) {
|
|
23
|
+
var end = start + anchor.quote.length;
|
|
24
|
+
if ((!anchor.prefix || source.text.slice(Math.max(0,start-anchor.prefix.length),start) === anchor.prefix) &&
|
|
25
|
+
(!anchor.suffix || source.text.slice(end,end+anchor.suffix.length) === anchor.suffix)) {
|
|
26
|
+
if (match) return null; match = {start:start,end:end};
|
|
27
|
+
}
|
|
28
|
+
start = source.text.indexOf(anchor.quote,start+1);
|
|
29
|
+
}
|
|
30
|
+
if (!match) return null;
|
|
31
|
+
var range = document.createRange();
|
|
32
|
+
var first = source.nodes.find(function(n){return n.start+n.node.length > match.start;});
|
|
33
|
+
var last = source.nodes.find(function(n){return n.start+n.node.length >= match.end;});
|
|
34
|
+
if (!first || !last) return null;
|
|
35
|
+
range.setStart(first.node,match.start-first.start); range.setEnd(last.node,match.end-last.start);
|
|
36
|
+
return range;
|
|
37
|
+
}
|
|
38
|
+
function resolveRange(contents, anchor) {
|
|
39
|
+
if (!validAnchor(anchor)) return null;
|
|
40
|
+
try { var range = contents.range(anchor.cfiRange); if (range && range.toString() === anchor.quote) return range; } catch (_) {}
|
|
41
|
+
return recoverRange(contents.document,anchor);
|
|
42
|
+
}
|
|
43
|
+
function selection(contents, cfiRange, href, documentId) {
|
|
44
|
+
var range;
|
|
45
|
+
try { range = contents.range(cfiRange); } catch (_) { return null; }
|
|
46
|
+
if (!range || !range.toString()) return null;
|
|
47
|
+
var before = contents.document.createRange(); before.selectNodeContents(contents.document.body); before.setEnd(range.startContainer,range.startOffset);
|
|
48
|
+
var after = contents.document.createRange(); after.selectNodeContents(contents.document.body); after.setStart(range.endContainer,range.endOffset);
|
|
49
|
+
var anchor = {version:1,kind:'epub-cfi',cfiRange:cfiRange,href:href,spineIndex:contents.sectionIndex,documentId:documentId,quote:range.toString(),prefix:before.toString().slice(-48),suffix:after.toString().slice(0,48)};
|
|
50
|
+
return validAnchor(anchor) ? anchor : null;
|
|
51
|
+
}
|
|
52
|
+
function install(contents, options) {
|
|
53
|
+
var doc = contents.document, win = contents.window, alive = true, frame = 0;
|
|
54
|
+
var overlay = doc.createElement('div'); overlay.dataset.papyrusOverlay = 'annotations';
|
|
55
|
+
overlay.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:0;pointer-events:none;z-index:3';
|
|
56
|
+
var originalPosition=doc.body.style.position;
|
|
57
|
+
if(win.getComputedStyle(doc.body).position==='static')doc.body.style.position='relative';
|
|
58
|
+
doc.body.appendChild(overlay);
|
|
59
|
+
var registry = new Map(), hitRegions = [];
|
|
60
|
+
function render() {
|
|
61
|
+
frame = 0; if (!alive || !options.isCurrent()) return;
|
|
62
|
+
var keep = new Set(), noteGroups = new Map();
|
|
63
|
+
hitRegions = [];
|
|
64
|
+
options.annotations().forEach(function(annotation) {
|
|
65
|
+
var anchor = annotation.anchor;
|
|
66
|
+
if (!validAnchor(anchor) || anchor.href !== options.href || anchor.documentId && options.documentId && anchor.documentId !== options.documentId) return;
|
|
67
|
+
var range = resolveRange(contents,anchor); if (!range) return;
|
|
68
|
+
var rects = Array.from(range.getClientRects()).filter(function(r){return r.width>0 && r.height>0;});
|
|
69
|
+
if (!rects.length) return;
|
|
70
|
+
keep.add(annotation.id);
|
|
71
|
+
var group = registry.get(annotation.id);
|
|
72
|
+
if (!group) { group = doc.createElement('div'); group.dataset.annotationId = annotation.id; overlay.appendChild(group); registry.set(annotation.id,group); if (!doc.defaultView.matchMedia || !doc.defaultView.matchMedia('(prefers-reduced-motion: reduce)').matches) { if (typeof group.animate === 'function') group.animate([{opacity:0},{opacity:1}],{duration:180,easing:'ease-out'}); } }
|
|
73
|
+
group.replaceChildren();
|
|
74
|
+
hitRegions.push({id:annotation.id,rects:rects});
|
|
75
|
+
var color = /^#[0-9a-f]{6}$/i.test(annotation.color) ? annotation.color : '#FFC928';
|
|
76
|
+
var style = annotation.markupStyle || annotation.type;
|
|
77
|
+
var opacity = Number.isFinite(annotation.opacity) ? Math.max(0,Math.min(1,annotation.opacity)) : 0.35;
|
|
78
|
+
rects.forEach(function(rect) {
|
|
79
|
+
var mark = doc.createElement('div');
|
|
80
|
+
var bodyRect=doc.body.getBoundingClientRect();
|
|
81
|
+
var height = style === 'highlight' ? rect.height : 2;
|
|
82
|
+
var y = style === 'strikeout' ? rect.top+rect.height/2 : style === 'underline' ? rect.bottom-2 : rect.top;
|
|
83
|
+
mark.style.cssText = 'position:absolute;pointer-events:none;left:'+(rect.left-bodyRect.left)+'px;top:'+(y-bodyRect.top)+'px;width:'+rect.width+'px;height:'+height+'px;background:'+color+';opacity:'+opacity;
|
|
84
|
+
if (['highlight','underline','strikeout'].includes(style)) group.appendChild(mark);
|
|
85
|
+
});
|
|
86
|
+
var hasNote = annotation.noteContent !== undefined || annotation.type === 'comment' || annotation.type === 'text';
|
|
87
|
+
if (hasNote) {
|
|
88
|
+
var last = rects[rects.length-1], button = doc.createElement('button');
|
|
89
|
+
button.textContent = '●'; button.setAttribute('aria-label',options.labels().comment || '');
|
|
90
|
+
button.style.cssText = 'position:absolute;pointer-events:auto;border:0;background:transparent;color:'+color+';width:44px;height:44px;left:'+Math.max(0,Math.min(doc.documentElement.clientWidth-44,last.right-doc.body.getBoundingClientRect().left))+'px;top:'+(Math.floor(last.top/44)*44-doc.body.getBoundingClientRect().top)+'px';
|
|
91
|
+
var key = Math.floor(last.top/44);
|
|
92
|
+
var neighbors=noteGroups.get(key);
|
|
93
|
+
if(!neighbors){neighbors={button:button,ids:[]};noteGroups.set(key,neighbors);group.appendChild(button);}
|
|
94
|
+
neighbors.ids.push(annotation.id);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
noteGroups.forEach(function(group){
|
|
98
|
+
group.button.textContent=group.ids.length>1?String(group.ids.length):'●';
|
|
99
|
+
group.button.addEventListener('click',function(e){e.stopPropagation();if(options.isCurrent())options.onTap(group.ids[0],group.ids);});
|
|
100
|
+
});
|
|
101
|
+
registry.forEach(function(group,id){if (!keep.has(id)) {group.remove();registry.delete(id);}});
|
|
102
|
+
}
|
|
103
|
+
function schedule() { if (alive && !frame) frame = win.requestAnimationFrame(render); }
|
|
104
|
+
function tapMarkup(event) {
|
|
105
|
+
if(!alive || !options.isCurrent() || String(win.getSelection() || '').length || event.target.closest('[data-papyrus-overlay]'))return;
|
|
106
|
+
var hit=hitRegions.find(function(item){return item.rects.some(function(r){return event.clientX>=r.left && event.clientX<=r.right && event.clientY>=r.top && event.clientY<=r.bottom;});});
|
|
107
|
+
if(hit) {event.stopPropagation();options.onTap(hit.id);}
|
|
108
|
+
}
|
|
109
|
+
doc.addEventListener('click',tapMarkup);
|
|
110
|
+
var observer = typeof win.ResizeObserver === 'function' ? new win.ResizeObserver(schedule) : null;
|
|
111
|
+
if (observer) observer.observe(doc.body);
|
|
112
|
+
win.addEventListener('resize',schedule); doc.addEventListener('load',schedule,true);
|
|
113
|
+
if (doc.fonts && doc.fonts.ready) doc.fonts.ready.then(schedule);
|
|
114
|
+
schedule();
|
|
115
|
+
return {schedule:schedule, range:function(anchor){return resolveRange(contents,anchor);}, destroy:function(){alive=false;if(frame)win.cancelAnimationFrame(frame);if(observer)observer.disconnect();win.removeEventListener('resize',schedule);doc.removeEventListener('load',schedule,true);doc.removeEventListener('click',tapMarkup);overlay.remove();doc.body.style.position=originalPosition;registry.clear();}};
|
|
116
|
+
}
|
|
117
|
+
return {validAnchor:validAnchor,recoverRange:recoverRange,resolveRange:resolveRange,selection:selection,install:install};
|
|
118
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {createRequire} from 'node:module';
|
|
2
|
+
import {describe,it,expect} from 'vitest';
|
|
3
|
+
const annotations = createRequire(import.meta.url)('./epubAnnotations.js');
|
|
4
|
+
const anchor = {version:1,kind:'epub-cfi',cfiRange:'epubcfi(/6/2!/4/2:0)',href:'chapter.xhtml',quote:'word'};
|
|
5
|
+
describe('EPUB contextual anchors',()=>{
|
|
6
|
+
it('rejects malformed CFI and unsafe hrefs',()=>{expect(annotations.validAnchor(anchor)).toBe(true);expect(annotations.validAnchor({...anchor,cfiRange:'bad'})).toBe(false);expect(annotations.validAnchor({...anchor,href:'javascript:alert(1)'})).toBe(false);});
|
|
7
|
+
it('recovers uniquely in chapter text preserving UTF16 and excludes overlays',()=>{document.body.innerHTML='<p>A 😀 word end</p><div data-papyrus-overlay>word</div>';expect(annotations.recoverRange(document,anchor)?.toString()).toBe('word');});
|
|
8
|
+
it('leaves ambiguous quotes unresolved unless context distinguishes them',()=>{document.body.innerHTML='<p>one word two word end</p>';expect(annotations.recoverRange(document,anchor)).toBeNull();expect(annotations.recoverRange(document,{...anchor,prefix:'two '})?.toString()).toBe('word');});
|
|
9
|
+
it('verifies exact CFI quote before controlled recovery',()=>{document.body.innerHTML='<p>other word</p>';const bad=document.createRange();bad.selectNodeContents(document.body);expect(annotations.resolveRange({document,range:()=>bad},anchor)?.toString()).toBe('word');});
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('renders true strikeout, grouped notes and reconciles 120 stable IDs after reflow',()=>{
|
|
13
|
+
document.body.innerHTML='<p>word</p>';
|
|
14
|
+
const range=document.createRange();range.selectNodeContents(document.querySelector('p')!);
|
|
15
|
+
let top=20;Object.defineProperty(range,'getClientRects',{value:()=>[{left:10,right:50,top,bottom:top+20,width:40,height:20}]});
|
|
16
|
+
let queue:FrameRequestCallback[]=[];
|
|
17
|
+
const originalRAF=window.requestAnimationFrame;window.requestAnimationFrame=cb=>{queue.push(cb);return queue.length;};
|
|
18
|
+
let snapshot=Array.from({length:120},(_,i)=>({id:`n${i}`,anchor,color:'#ff0000',markupStyle:'strikeout',noteContent:`note ${i}`}));
|
|
19
|
+
const taps:string[]=[];
|
|
20
|
+
const renderer=annotations.install({document,window,range:()=>range},{href:'chapter.xhtml',documentId:undefined,annotations:()=>snapshot,labels:()=>({comment:'Nota'}),isCurrent:()=>true,onTap:(id:string)=>taps.push(id)});
|
|
21
|
+
const flush=()=>{const tasks=queue;queue=[];tasks.forEach(cb=>cb(0));};flush();
|
|
22
|
+
expect(document.querySelectorAll('[data-annotation-id]')).toHaveLength(120);
|
|
23
|
+
expect(document.querySelectorAll('[data-papyrus-overlay] button')).toHaveLength(1);
|
|
24
|
+
const group=document.querySelector('[data-annotation-id="n0"]')!;
|
|
25
|
+
expect((group.firstChild as HTMLElement).style.top).toBe('30px');
|
|
26
|
+
expect((group.lastChild as HTMLElement).textContent).toBe('120');
|
|
27
|
+
(group.lastChild as HTMLElement).click();expect(taps).toEqual(['n0']);
|
|
28
|
+
top=80;renderer.schedule();flush();expect(document.querySelector('[data-annotation-id="n0"]')).toBe(group);expect((group.firstChild as HTMLElement).style.top).toBe('90px');
|
|
29
|
+
snapshot=[];renderer.schedule();flush();expect(document.querySelectorAll('[data-annotation-id]')).toHaveLength(0);
|
|
30
|
+
renderer.destroy();expect(document.querySelector('[data-papyrus-overlay]')).toBeNull();window.requestAnimationFrame=originalRAF;
|
|
31
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {readFileSync} from 'node:fs';
|
|
2
|
+
import {JSDOM} from 'jsdom';
|
|
3
|
+
import {describe,it,expect} from 'vitest';
|
|
4
|
+
const source=readFileSync('packages/ui-react-native/runtime/runtime.js','utf8');
|
|
5
|
+
function fixture() {
|
|
6
|
+
const messages:any[]=[];
|
|
7
|
+
const dom=new JSDOM('<div id="viewer"></div>',{runScripts:'outside-only'});
|
|
8
|
+
dom.window.ReactNativeWebView={postMessage:(raw:string)=>messages.push(JSON.parse(raw))} as never;
|
|
9
|
+
// Expose only the setup boundary in the test copy; execute the production handler.
|
|
10
|
+
dom.window.eval(source.replace("sendMessage({ type: 'ready' });",`
|
|
11
|
+
window.seedMenu=(session,payload,contents)=>{documentSessionId=session;nativeMenuSelection={payload,contents};};`));
|
|
12
|
+
const chapter=new JSDOM('<p>one word and a phrase</p>');
|
|
13
|
+
const text=chapter.window.document.querySelector('p')!.firstChild!;
|
|
14
|
+
const range=chapter.window.document.createRange();range.setStart(text,4);range.setEnd(text,8);
|
|
15
|
+
chapter.window.getSelection()!.addRange(range);
|
|
16
|
+
const payload={documentSessionId:'current',text:'word',pageIndex:1,
|
|
17
|
+
anchor:{kind:'epub-cfi',version:1,cfiRange:'epubcfi(/6/2!/4/2:4)',href:'one.xhtml',quote:'word'}};
|
|
18
|
+
(dom.window as any).seedMenu('current',payload,{document:chapter.window.document,window:chapter.window});
|
|
19
|
+
const send=(key:string,session='current')=>dom.window.dispatchEvent(new dom.window.MessageEvent('message',
|
|
20
|
+
{data:JSON.stringify({type:'epub-selection-action',id:'selection-menu',key,documentSessionId:session})}));
|
|
21
|
+
return {messages,chapter,send,dom};
|
|
22
|
+
}
|
|
23
|
+
describe('native EPUB menu dispatch',()=>{
|
|
24
|
+
it('uses the chapter CFI snapshot even when root selection is empty',()=>{
|
|
25
|
+
const f=fixture();expect(f.dom.window.getSelection()!.toString()).toBe('');f.send('highlight');
|
|
26
|
+
expect(f.messages).toContainEqual(expect.objectContaining({name:'EPUB_SELECTION_ACTION',payload:expect.objectContaining({action:'highlight',text:'word',anchor:expect.objectContaining({href:'one.xhtml'})})}));
|
|
27
|
+
expect(f.chapter.window.getSelection()!.toString()).toBe('');
|
|
28
|
+
});
|
|
29
|
+
it('rejects stale document sessions and unknown actions',()=>{
|
|
30
|
+
const f=fixture();f.send('copy','old');f.send('deleteDocument');expect(f.messages).toHaveLength(0);
|
|
31
|
+
expect(f.chapter.window.getSelection()!.toString()).toBe('word');
|
|
32
|
+
});
|
|
33
|
+
it('selects all inside the chapter, without annotating the previous word',()=>{
|
|
34
|
+
const f=fixture();f.send('selectAll');expect(f.chapter.window.getSelection()!.toString()).toBe('one word and a phrase');expect(f.messages).toHaveLength(0);
|
|
35
|
+
});
|
|
36
|
+
it('consumes each action once',()=>{
|
|
37
|
+
const f=fixture();f.send('comment');f.send('comment');expect(f.messages).toHaveLength(1);
|
|
38
|
+
});
|
|
39
|
+
});
|