mirror of
https://github.com/readest/readest.git
synced 2026-11-30 11:49:50 +00:00
fix(lite): select a word and look it up as Readest does (owner: "continue")
A double tap on a word in a book did nothing in Lite, and the dictionary
behind it could not show a book's own-language Wiktionary entry: Lite
lacked DOM pieces Readest's selection and lookup use.
- document.caretPositionFromPoint / caretRangeFromPoint. Readest finds
the word under a double tap with them (also the reading ruler, instant
highlights and cross-page selections). Blitz maps the point to the
text node and offset (caret_position_from_point, patches/blitz.diff).
- Range cloneContents, extractContents, deleteContents, insertNode and
Text.splitText. Readest reads a selection's text from cloneContents:
makeSelection threw and no popup opened. Word Lens wraps a word with
extractContents and insertNode.
- A DocumentFragment's children have it as their parentNode and each
other as siblings (a walk over a cloned multi-paragraph selection
stopped after its first paragraph), and a fragment has querySelector,
querySelectorAll, children, textContent and append: the vocabulary
couldn't read the word's sentence.
- Element.matches is one native match. It queried the parent, which
recursed for a fragment's child and missed detached elements.
- A node from another document is adopted with its tree, as browsers
do. The Wiktionary lookup moves the section it shows out of a
DOMParser document; it threw WrongDocumentError and fell back to the
English edition.
- before, after and replaceWith, and reflected lang and dir: the lookup
unwraps links with replaceWith and marks its section's language.
Found with a new parity scenario (in a later commit): a double tap on
"Zimmer" in a German book now opens the selection popup in Lite, and
its dictionary shows the German Wiktionary's entry, as Readest does.
What still differs there: Readest raises superscripts with Tailwind's
`position: relative; top: -0.5em`, which Blitz doesn't apply to an
inline element's text.
Tests, each failing without its change:
- caret_position (4 tests): "not a function".
- range: a_ranges_contents_are_cloned_or_moved_into_a_fragment,
delete_contents_removes_what_the_range_selects,
insert_node_splits_the_text_at_the_range_start: "not a function"; the
walk over the clone lost "fo" until fragments linked their children.
- dom_basics: a_fragments_children_link_to_it_and_each_other
("false false false null null"), a_fragment_is_queried_and_read_as_a_
parent_node and nodes_go_before_after_or_in_place_of_a_child: "not a
function".
- parsed_documents: an_element_from_a_parsed_document_is_adopted_with_
its_tree: WrongDocumentError. a_lone_text_node_is_adopted and iframes'
content_document_is_the_iframes_own expected WrongDocumentError for a
page node moved into another document; they now expect the move.
cargo test -p blitz-qjs-script: 110 pass (the long-press test of the
next commit fails here, as it should). -p tauri-runtime-blitz: 89 pass.
Parity, Lite rebuilt: library 12/13, library-book 20/22, reader 20/20,
reader-tools 29/30, novel-turns 13/13, as before. One novel-turns run
gave 11/13 while builds ran alongside: a preloaded section was not
styled yet at step 0; it passed twice after.
Not run: the Kindle.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f1ffad6098
commit
003bc6f37f
9 changed files with 677 additions and 21 deletions
|
|
@ -489,7 +489,8 @@
|
|||
}
|
||||
get parentNode() {
|
||||
const p = n.parent(this._id);
|
||||
return p == null ? null : wrapIn(p, ownerOf(this));
|
||||
if (p == null) return this._frag ?? null;
|
||||
return wrapIn(p, ownerOf(this));
|
||||
}
|
||||
get parentElement() {
|
||||
const p = this.parentNode;
|
||||
|
|
@ -513,11 +514,13 @@
|
|||
}
|
||||
get nextSibling() {
|
||||
const c = n.sibling(this._id, 1);
|
||||
return c == null ? null : wrapIn(c, ownerOf(this));
|
||||
if (c == null) return this._frag ? fragSibling(this, 1) : null;
|
||||
return wrapIn(c, ownerOf(this));
|
||||
}
|
||||
get previousSibling() {
|
||||
const c = n.sibling(this._id, -1);
|
||||
return c == null || shadowIds.has(c) ? null : wrapIn(c, ownerOf(this));
|
||||
if (c == null) return this._frag ? fragSibling(this, -1) : null;
|
||||
return shadowIds.has(c) ? null : wrapIn(c, ownerOf(this));
|
||||
}
|
||||
// Shadow-including: shadow trees are in the native tree under their hosts.
|
||||
get isConnected() {
|
||||
|
|
@ -574,6 +577,7 @@
|
|||
});
|
||||
return c;
|
||||
}
|
||||
leaveFragment(c);
|
||||
const was = n.connected(c._id);
|
||||
const moved = defs.size > 0 && c.nodeType === 1 && was;
|
||||
if (liveIterators.size && c.parentNode) preRemove(c);
|
||||
|
|
@ -610,6 +614,7 @@
|
|||
return c;
|
||||
}
|
||||
removeChild(c) {
|
||||
if (c._frag) return c._frag.removeChild(c);
|
||||
if (liveIterators.size) preRemove(c);
|
||||
const removed = removal(c);
|
||||
const was = n.connected(c._id);
|
||||
|
|
@ -625,6 +630,7 @@
|
|||
return oc;
|
||||
}
|
||||
remove() {
|
||||
if (this._frag) return void this._frag.removeChild(this);
|
||||
if (liveIterators.size && this.parentNode) preRemove(this);
|
||||
const removed = removal(this);
|
||||
const was = n.connected(this._id);
|
||||
|
|
@ -706,9 +712,29 @@
|
|||
return this.nodeType === 3 ? '#text' : '#comment';
|
||||
}
|
||||
}
|
||||
class Text extends CharacterData {}
|
||||
class Text extends CharacterData {
|
||||
// The text after `offset` goes into a text node of its own, inserted after this one.
|
||||
splitText(offset) {
|
||||
if (offset > this.length) throw domError('The offset is past the node', 'IndexSizeError');
|
||||
const tail = docOf(this).createTextNode(this.data.slice(offset));
|
||||
this.parentNode?.insertBefore(tail, this.nextSibling);
|
||||
this.data = this.data.slice(0, offset);
|
||||
return tail;
|
||||
}
|
||||
}
|
||||
class Comment extends CharacterData {}
|
||||
|
||||
// A fragment's children are native nodes with no parent: the fragment lists them (`_kids`) and
|
||||
// each knows it (`_frag`), for its parentNode and siblings.
|
||||
function leaveFragment(c) {
|
||||
if (c._frag) c._frag.removeChild(c);
|
||||
}
|
||||
function fragSibling(node, step) {
|
||||
if (n.parent(node._id) != null) return null;
|
||||
const kids = node._frag._kids;
|
||||
const i = kids.indexOf(node);
|
||||
return i < 0 ? null : (kids[i + step] ?? null);
|
||||
}
|
||||
class DocumentFragment extends Node {
|
||||
constructor() {
|
||||
super(-1);
|
||||
|
|
@ -733,21 +759,62 @@
|
|||
return this._kids[this._kids.length - 1] || null;
|
||||
}
|
||||
insertBefore(c, ref) {
|
||||
if (c instanceof DocumentFragment) {
|
||||
for (const k of c._kids.slice()) this.insertBefore(k, ref);
|
||||
return c;
|
||||
}
|
||||
if (liveIterators.size && c.parentNode) preRemove(c);
|
||||
const removed = removal(c);
|
||||
const was = n.connected(c._id);
|
||||
n.remove(c._id);
|
||||
if (was) loosen(c._id);
|
||||
if (removed) queueMutation(...removed);
|
||||
leaveFragment(c);
|
||||
const i = ref ? this._kids.indexOf(ref) : -1;
|
||||
if (i < 0) this._kids.push(c);
|
||||
else this._kids.splice(i, 0, c);
|
||||
c._frag = this;
|
||||
return c;
|
||||
}
|
||||
removeChild(c) {
|
||||
this._kids = this._kids.filter((k) => k !== c);
|
||||
if (c._frag === this) c._frag = null;
|
||||
return c;
|
||||
}
|
||||
get textContent() {
|
||||
return this._kids.map((k) => (k.nodeType === 8 ? '' : k.textContent)).join('');
|
||||
}
|
||||
set textContent(v) {
|
||||
for (const k of this._kids.slice()) this.removeChild(k);
|
||||
const text = v == null ? '' : String(v);
|
||||
if (text) this.appendChild(document.createTextNode(text));
|
||||
}
|
||||
get children() {
|
||||
return withItem(this._kids.filter((k) => k.nodeType === 1));
|
||||
}
|
||||
get childElementCount() {
|
||||
return this.children.length;
|
||||
}
|
||||
get firstElementChild() {
|
||||
return this.children[0] ?? null;
|
||||
}
|
||||
get lastElementChild() {
|
||||
return this.children.at(-1) ?? null;
|
||||
}
|
||||
querySelectorAll(s) {
|
||||
const out = [];
|
||||
for (const k of this.children) {
|
||||
if (k.matches(s)) out.push(k);
|
||||
out.push(...k.querySelectorAll(s));
|
||||
}
|
||||
return withItem(out);
|
||||
}
|
||||
querySelector(s) {
|
||||
return this.querySelectorAll(s)[0] ?? null;
|
||||
}
|
||||
getElementById(id) {
|
||||
return this.querySelector('#' + CSS.escape(String(id)));
|
||||
}
|
||||
get ownerDocument() {
|
||||
return document;
|
||||
}
|
||||
|
|
@ -1107,8 +1174,7 @@
|
|||
);
|
||||
}
|
||||
matches(s) {
|
||||
const p = this.parentNode || this.ownerDocument;
|
||||
return p.querySelectorAll(s).includes(this);
|
||||
return n.matches(this._id, s);
|
||||
}
|
||||
closest(s) {
|
||||
for (let e = this; e && e.nodeType === 1; e = e.parentNode) if (e.matches(s)) return e;
|
||||
|
|
@ -1265,6 +1331,44 @@
|
|||
this.append(...nodes);
|
||||
}
|
||||
}
|
||||
// A fragment's append, prepend and replaceChildren are an element's, over its own insertBefore.
|
||||
for (const m of ['append', 'prepend', 'replaceChildren'])
|
||||
DocumentFragment.prototype[m] = Element.prototype[m];
|
||||
// ChildNode (DOM): `nodes` (strings become text) go before, after or in place of this node, at
|
||||
// the nearest sibling not among them.
|
||||
function childNodes(self, nodes) {
|
||||
const f = docOf(self).createDocumentFragment();
|
||||
for (const c of nodes) f.appendChild(typeof c === 'string' ? docOf(self).createTextNode(c) : c);
|
||||
return f;
|
||||
}
|
||||
const siblingNotIn = (node, nodes, step) => {
|
||||
let s = step > 0 ? node.nextSibling : node.previousSibling;
|
||||
while (s && nodes.includes(s)) s = step > 0 ? s.nextSibling : s.previousSibling;
|
||||
return s;
|
||||
};
|
||||
const childNode = {
|
||||
before(...nodes) {
|
||||
const p = this.parentNode;
|
||||
if (!p) return;
|
||||
const prev = siblingNotIn(this, nodes, -1);
|
||||
p.insertBefore(childNodes(this, nodes), prev ? prev.nextSibling : p.firstChild);
|
||||
},
|
||||
after(...nodes) {
|
||||
const p = this.parentNode;
|
||||
if (!p) return;
|
||||
const next = siblingNotIn(this, nodes, 1);
|
||||
p.insertBefore(childNodes(this, nodes), next);
|
||||
},
|
||||
replaceWith(...nodes) {
|
||||
const p = this.parentNode;
|
||||
if (!p) return;
|
||||
const next = siblingNotIn(this, nodes, 1);
|
||||
const f = childNodes(this, nodes);
|
||||
if (this.parentNode === p) p.removeChild(this);
|
||||
p.insertBefore(f, next);
|
||||
},
|
||||
};
|
||||
for (const cls of [Element, CharacterData]) Object.assign(cls.prototype, childNode);
|
||||
class HTMLElement extends Element {
|
||||
// Only a defined custom element class constructs (`new`, createElement or an upgrade). An
|
||||
// upgrade hands it the existing wrapper, which becomes the class's object.
|
||||
|
|
@ -1361,6 +1465,7 @@
|
|||
configurable: true,
|
||||
});
|
||||
};
|
||||
reflect(HTMLElement, ['lang', 'dir']);
|
||||
class HTMLInputElement extends HTMLElement {
|
||||
get value() {
|
||||
return this.getAttribute('value') || '';
|
||||
|
|
@ -1871,16 +1976,35 @@
|
|||
};
|
||||
// A lone text or comment node from another document becomes a copy in `doc`, which its
|
||||
// wrapper takes over (the DOM adopts it; Blitz nodes can't change documents).
|
||||
// A node of another document moves into `doc` (DOM's adopt): out of its parent there, its tree
|
||||
// made again in `doc` natively, each of its nodes' wrappers pointed at its copy (so the objects,
|
||||
// their listeners and the references JS holds stay the same).
|
||||
function adopt(c, doc) {
|
||||
const t = c.nodeType;
|
||||
if ((t !== 3 && t !== 8) || c.parentNode || docOf(c) === doc) return false;
|
||||
const copy = t === 3 ? n.createText(doc._id, c.data) : n.createComment(doc._id, c.data);
|
||||
if (c._owner) c._owner._nodes.delete(c._id);
|
||||
else if (!wrappers.delete(c._id)) loose.delete(c._id);
|
||||
c._id = copy;
|
||||
c._owner = doc._nodes ? doc : undefined;
|
||||
if (doc._nodes) doc._nodes.set(copy, c);
|
||||
else keep(copy, c);
|
||||
if ((t !== 1 && t !== 3 && t !== 8) || docOf(c) === doc) return false;
|
||||
c.parentNode?.removeChild(c);
|
||||
const make = (node) => {
|
||||
const k = node.nodeType;
|
||||
let copy;
|
||||
if (k === 3) copy = n.createText(doc._id, node.data);
|
||||
else if (k === 8) copy = n.createComment(doc._id, node.data);
|
||||
else if (k === 1) {
|
||||
copy = n.createElement(doc._id, node.namespaceURI ?? '', node.localName);
|
||||
for (const a of node.getAttributeNames()) n.setAttr(copy, a, node.getAttribute(a));
|
||||
for (const child of node.childNodes) {
|
||||
const id = make(child);
|
||||
if (id != null) n.insert(copy, id, null);
|
||||
}
|
||||
} else return null;
|
||||
if (node._owner) node._owner._nodes.delete(node._id);
|
||||
else if (!wrappers.delete(node._id)) loose.delete(node._id);
|
||||
node._id = copy;
|
||||
node._owner = doc._nodes ? doc : undefined;
|
||||
if (doc._nodes) doc._nodes.set(copy, node);
|
||||
else keep(copy, node);
|
||||
return copy;
|
||||
};
|
||||
make(c);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -2274,8 +2398,96 @@
|
|||
getBoundingClientRect() {
|
||||
return unionRect(this.getClientRects());
|
||||
}
|
||||
cloneContents() {
|
||||
return rangeContents(this, false);
|
||||
}
|
||||
extractContents() {
|
||||
return rangeContents(this, true);
|
||||
}
|
||||
deleteContents() {
|
||||
rangeContents(this, true);
|
||||
}
|
||||
// DOM Standard: at the start, splitting a text node there.
|
||||
insertNode(node) {
|
||||
const { startContainer: sc, startOffset: so } = this;
|
||||
const k = sc.nodeType;
|
||||
if (k === 7 || k === 8 || (k === 3 && !sc.parentNode) || sc === node)
|
||||
throw domError('The node cannot be inserted there', 'HierarchyRequestError');
|
||||
let ref = k === 3 ? sc : (sc.childNodes[so] ?? null);
|
||||
const parent = ref ? ref.parentNode : sc;
|
||||
if (k === 3) ref = sc.splitText(so);
|
||||
if (node === ref) ref = ref.nextSibling;
|
||||
node.parentNode?.removeChild(node);
|
||||
const at = ref ? indexOf(ref) : nodeLength(parent);
|
||||
const end = at + (node.nodeType === 11 ? node.childNodes.length : 1);
|
||||
parent.insertBefore(node, ref);
|
||||
if (this.collapsed) this.setEnd(parent, end);
|
||||
}
|
||||
detach() {}
|
||||
}
|
||||
const isCharData = (node) => node.nodeType === 3 || node.nodeType === 8;
|
||||
// DOM Standard: clone the contents of `range` (or, extracting, move them) into a fragment. The
|
||||
// elements partly in it are cloned without their children, which get what of them is in it.
|
||||
function rangeContents(range, extract) {
|
||||
const { startContainer: sc, startOffset: so, endContainer: ec, endOffset: eo } = range;
|
||||
const frag = docOf(sc).createDocumentFragment();
|
||||
if (range.collapsed) return frag;
|
||||
if (sc === ec && isCharData(sc)) {
|
||||
const c = sc.cloneNode(false);
|
||||
c.data = sc.data.slice(so, eo);
|
||||
frag.appendChild(c);
|
||||
if (extract) {
|
||||
sc.data = sc.data.slice(0, so) + sc.data.slice(eo);
|
||||
range.collapse(true);
|
||||
}
|
||||
return frag;
|
||||
}
|
||||
const common = range.commonAncestorContainer;
|
||||
const childOf = (node) => {
|
||||
while (node.parentNode !== common) node = node.parentNode;
|
||||
return node;
|
||||
};
|
||||
const first = sc.contains(ec) ? null : childOf(sc);
|
||||
const last = ec.contains(sc) ? null : childOf(ec);
|
||||
const kids = Array.from(common.childNodes);
|
||||
const from = first ? kids.indexOf(first) + 1 : so;
|
||||
const contained = kids.slice(from, last ? kids.indexOf(last) : eo);
|
||||
if (contained.some((c) => c.nodeType === 10))
|
||||
throw domError('A doctype cannot be in a fragment', 'HierarchyRequestError');
|
||||
// Where an extracted range collapses: after the start's ancestor that stays.
|
||||
let at = [sc, so];
|
||||
if (extract && first) {
|
||||
let ref = sc;
|
||||
while (ref.parentNode && !ref.parentNode.contains(ec)) ref = ref.parentNode;
|
||||
at = [ref.parentNode, indexOf(ref) + 1];
|
||||
}
|
||||
const part = (node, start, end) => {
|
||||
const c = node.cloneNode(false);
|
||||
frag.appendChild(c);
|
||||
const sub = new Range();
|
||||
sub.setStart(...start);
|
||||
sub.setEnd(...end);
|
||||
c.appendChild(rangeContents(sub, extract));
|
||||
};
|
||||
if (first && isCharData(first)) {
|
||||
const c = sc.cloneNode(false);
|
||||
c.data = sc.data.slice(so);
|
||||
frag.appendChild(c);
|
||||
if (extract) sc.data = sc.data.slice(0, so);
|
||||
} else if (first) part(first, [sc, so], [first, nodeLength(first)]);
|
||||
for (const c of contained) frag.appendChild(extract ? c : c.cloneNode(true));
|
||||
if (last && isCharData(last)) {
|
||||
const c = ec.cloneNode(false);
|
||||
c.data = ec.data.slice(0, eo);
|
||||
frag.appendChild(c);
|
||||
if (extract) ec.data = ec.data.slice(eo);
|
||||
} else if (last) part(last, [last, 0], [ec, eo]);
|
||||
if (extract) {
|
||||
range.setStart(...at);
|
||||
range.collapse(true);
|
||||
}
|
||||
return frag;
|
||||
}
|
||||
Object.assign(Range, { START_TO_START: 0, START_TO_END: 1, END_TO_END: 2, END_TO_START: 3 });
|
||||
Document.prototype.createRange = function () {
|
||||
const r = new Range();
|
||||
|
|
@ -2539,6 +2751,30 @@
|
|||
return (this._selection ??= new Selection());
|
||||
};
|
||||
|
||||
// CSSOM View: the caret nearest a point in this document's viewport, in the text under it.
|
||||
class CaretPosition {
|
||||
constructor(node, offset) {
|
||||
this.offsetNode = node;
|
||||
this.offset = offset;
|
||||
}
|
||||
getClientRect() {
|
||||
const r = docOf(this.offsetNode).createRange();
|
||||
r.setStart(this.offsetNode, this.offset);
|
||||
return r.getBoundingClientRect();
|
||||
}
|
||||
}
|
||||
Document.prototype.caretPositionFromPoint = function (x, y) {
|
||||
const [h, offset] = n.caret(this._id, x, y);
|
||||
return h == null ? null : new CaretPosition(wrapIn(h, ownerOf(this)), offset);
|
||||
};
|
||||
Document.prototype.caretRangeFromPoint = function (x, y) {
|
||||
const p = this.caretPositionFromPoint(x, y);
|
||||
if (!p) return null;
|
||||
const r = this.createRange();
|
||||
r.setStart(p.offsetNode, p.offset);
|
||||
return r;
|
||||
};
|
||||
|
||||
// ---- Shadow roots ----
|
||||
// Blitz has no shadow DOM, so a shadow tree is laid out in place: its root is an element
|
||||
// (`blitz-shadow-root`, display: contents) that is its host's first native child, which Blitz
|
||||
|
|
|
|||
|
|
@ -782,6 +782,14 @@ pub(crate) fn install(ctx: &Ctx<'_>, shared: Rc<RefCell<Shared>>, base: Option<&
|
|||
.flatten()
|
||||
});
|
||||
let d = docs.clone();
|
||||
// Whether element `h` matches selector `sel` (false for a selector that does not parse).
|
||||
op!("matches", move |h: f64, sel: String| -> bool {
|
||||
d.with(h, |doc, n, _| {
|
||||
doc.matches_selector(n, &sel).unwrap_or(false)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
});
|
||||
let d = docs.clone();
|
||||
op!("queryAll", move |scope: f64, sel: String| -> Vec<f64> {
|
||||
d.with(scope, |doc, scope, tag| {
|
||||
doc.query_selector_all_in(scope, &sel).ok().map(|v| {
|
||||
|
|
@ -914,6 +922,24 @@ pub(crate) fn install(ctx: &Ctx<'_>, shared: Rc<RefCell<Shared>>, base: Option<&
|
|||
.unwrap_or_default()
|
||||
});
|
||||
let d = docs.clone();
|
||||
// CSSOM View's caretPositionFromPoint in the document of `h`, at (x, y) in its viewport:
|
||||
// [text node, UTF-16 offset], or nothing off text.
|
||||
op!("caret", move |h: f64, x: f64, y: f64| -> Vec<f64> {
|
||||
d.resolve(h, "caret");
|
||||
d.with(h, |doc, _, tag| {
|
||||
let (node, at) = doc.caret_position_from_point(x as f32, y as f32)?;
|
||||
let NodeData::Text(t) = &doc.get_node(node)?.data else {
|
||||
return None;
|
||||
};
|
||||
Some(vec![
|
||||
d.enc(tag, node),
|
||||
t.content[..at].encode_utf16().count() as f64,
|
||||
])
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let d = docs.clone();
|
||||
// An element's scroll offset: [scrollLeft, scrollTop].
|
||||
op!("scroll", move |h: f64| -> Vec<f64> {
|
||||
d.with(h, |doc, n, _| {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,85 @@
|
|||
//! `document.caretPositionFromPoint` / `caretRangeFromPoint`: the text node under a point and the
|
||||
//! offset (UTF-16) of the caret nearest it. Readest selects the word under a double tap with them,
|
||||
//! and its reading ruler, instant highlights and cross-page selections find text by them. Points
|
||||
//! are taken from Range boxes, so no font metric is assumed; the text is bullets in Blitz's
|
||||
//! built-in bullet font, 3 bytes each in UTF-8 and one UTF-16 unit.
|
||||
|
||||
use blitz_dom::{Document as _, DocumentConfig};
|
||||
use blitz_qjs_script::QjsDocument;
|
||||
use blitz_traits::shell::{ColorScheme, Viewport};
|
||||
|
||||
fn run(body: &str, script: &str) -> Vec<String> {
|
||||
let html = format!(
|
||||
"<!DOCTYPE html><html style='margin:0'><body style='margin:0; font: 16px/20px Bullet'>{body}</body></html>"
|
||||
);
|
||||
let config = DocumentConfig {
|
||||
viewport: Some(Viewport::new(400, 100, 1.0, ColorScheme::Light)),
|
||||
..DocumentConfig::default()
|
||||
};
|
||||
let mut doc = QjsDocument::from_html(&html, config);
|
||||
doc.inner_mut().resolve(0.0);
|
||||
doc.eval(
|
||||
&format!(
|
||||
"const $ = (id) => document.getElementById(id);
|
||||
const box = (n, s, e) => {{ const r = document.createRange(); r.setStart(n, s); r.setEnd(n, e); return r.getBoundingClientRect(); }};
|
||||
// the caret at the left and the right quarter of character `i` of text node `t`
|
||||
const at = (t, i, right) => {{
|
||||
const b = box(t, i, i + 1);
|
||||
const p = document.caretPositionFromPoint(b.x + b.width * (right ? 0.75 : 0.25), b.y + b.height / 2);
|
||||
return p ? `${{p.offsetNode === t}} ${{p.offset}}` : 'null';
|
||||
}};
|
||||
{script}"
|
||||
),
|
||||
"test",
|
||||
);
|
||||
assert_eq!(doc.take_js_errors(), Vec::<String>::new());
|
||||
doc.take_messages()
|
||||
.into_iter()
|
||||
.filter_map(|m| m.strip_prefix("log: ").map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_a_character_is_a_caret_before_or_after_it() {
|
||||
let logs = run(
|
||||
"<p id='a' style='margin:0'>•• ◦◦ ▪▪</p>",
|
||||
"const t = $('a').firstChild;
|
||||
console.log(at(t, 0, false), at(t, 3, false), at(t, 3, true), at(t, 7, true));",
|
||||
);
|
||||
assert_eq!(logs, ["true 0 true 3 true 4 true 8"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caret_is_in_the_text_node_under_the_point() {
|
||||
// three text nodes on one line: the inline element's and the ones around it
|
||||
let logs = run(
|
||||
"<p id='a' style='margin:0'>•• <b id='b'>◦◦</b> ▪▪</p>",
|
||||
"const [t0, t2] = [$('a').firstChild, $('a').lastChild];
|
||||
const t1 = $('b').firstChild;
|
||||
console.log(at(t0, 1, true), at(t1, 1, false), at(t2, 1, false), at(t2, 2, true));",
|
||||
);
|
||||
assert_eq!(logs, ["true 2 true 1 true 1 true 3"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_count_the_white_space_the_line_collapsed() {
|
||||
// the DOM keeps the run of spaces and the newline; the line holds one space
|
||||
let logs = run(
|
||||
"<p id='a' style='margin:0'>•• \n ◦◦</p>",
|
||||
"const t = $('a').firstChild;
|
||||
console.log(at(t, 8, false), at(t, 9, true));",
|
||||
);
|
||||
assert_eq!(logs, ["true 8 true 10"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_range_is_collapsed_at_the_caret_position() {
|
||||
let logs = run(
|
||||
"<p id='a' style='margin:0'>•• ◦◦ ▪▪</p>",
|
||||
"const t = $('a').firstChild;
|
||||
const b = box(t, 4, 5);
|
||||
const r = document.caretRangeFromPoint(b.x + b.width * 0.75, b.y + b.height / 2);
|
||||
console.log(r.startContainer === t, r.startOffset, r.collapsed);",
|
||||
);
|
||||
assert_eq!(logs, ["true 5 true"]);
|
||||
}
|
||||
|
|
@ -349,3 +349,103 @@ fn class_list() {
|
|||
]
|
||||
);
|
||||
}
|
||||
|
||||
// A fragment's children are its children for walks over it (Readest reads a selection's text
|
||||
// with a TreeWalker over `range.cloneContents()`): their parent is the fragment, their siblings
|
||||
// are each other, until they leave it.
|
||||
#[test]
|
||||
fn a_fragments_children_link_to_it_and_each_other() {
|
||||
let html = "<!DOCTYPE html><html><body></body></html>";
|
||||
let mut doc = QjsDocument::from_html(html, DocumentConfig::default());
|
||||
doc.eval(
|
||||
"const f = document.createDocumentFragment();
|
||||
const [a, b, c] = [document.createElement('i'), document.createTextNode('x'), document.createElement('b')];
|
||||
for (const k of [a, b, c]) f.appendChild(k);
|
||||
console.log(a.parentNode === f, a.nextSibling === b, c.previousSibling === b, c.nextSibling, a.previousSibling);
|
||||
b.remove();
|
||||
console.log(a.nextSibling === c, f.childNodes.length, b.parentNode, b.nextSibling);
|
||||
document.body.appendChild(a);
|
||||
console.log(a.parentNode === document.body, f.firstChild === c, c.previousSibling, a.nextSibling);
|
||||
document.body.appendChild(f);
|
||||
console.log(c.parentNode === document.body, a.nextSibling === c, f.childNodes.length);",
|
||||
"test",
|
||||
);
|
||||
let logs = doc.take_messages();
|
||||
assert_eq!(doc.take_js_errors(), Vec::<String>::new());
|
||||
assert_eq!(
|
||||
logs,
|
||||
[
|
||||
"log: true true true null null",
|
||||
"log: true 2 null null",
|
||||
"log: true true null null",
|
||||
"log: true true 0",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// Readest's vocabulary reads a range's text with `fragment.querySelectorAll('rt, rp')` removed
|
||||
// and then `fragment.textContent`.
|
||||
#[test]
|
||||
fn a_fragment_is_queried_and_read_as_a_parent_node() {
|
||||
let html = "<!DOCTYPE html><html><body></body></html>";
|
||||
let mut doc = QjsDocument::from_html(html, DocumentConfig::default());
|
||||
doc.eval(
|
||||
"const f = document.createDocumentFragment();
|
||||
const p = document.createElement('p');
|
||||
p.innerHTML = 'a<rt>x</rt>b';
|
||||
f.append(p, 'c', document.createComment('z'));
|
||||
console.log(f.querySelectorAll('rt').length, f.querySelector('p') === p, f.querySelector('i'), f.textContent);
|
||||
console.log(f.children.length, f.childElementCount, f.firstElementChild === p, f.lastElementChild === p);
|
||||
f.querySelectorAll('rt, rp').forEach((el) => el.remove());
|
||||
console.log(f.textContent);
|
||||
f.textContent = 'd';
|
||||
console.log(f.childNodes.length, f.firstChild.data);",
|
||||
"test",
|
||||
);
|
||||
let logs = doc.take_messages();
|
||||
assert_eq!(doc.take_js_errors(), Vec::<String>::new());
|
||||
assert_eq!(
|
||||
logs,
|
||||
[
|
||||
"log: 1 true null axbc",
|
||||
"log: 1 1 true true",
|
||||
"log: abc",
|
||||
"log: 1 d"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// Readest's Wiktionary lookup unwraps links with `link.replaceWith(...link.childNodes)` and marks
|
||||
// the section it shows with `lang` and `dir`.
|
||||
#[test]
|
||||
fn nodes_go_before_after_or_in_place_of_a_child() {
|
||||
let html = "<!DOCTYPE html><html><body><p id='p'><a id='a'>x<b>y</b></a><i id='i'>z</i></p></body></html>";
|
||||
let mut doc = QjsDocument::from_html(html, DocumentConfig::default());
|
||||
doc.eval(
|
||||
"const [p, a, i] = ['p', 'a', 'i'].map((id) => document.getElementById(id));
|
||||
a.replaceWith(...Array.from(a.childNodes));
|
||||
console.log(p.innerHTML, a.parentNode);
|
||||
i.before('1', document.createElement('u'));
|
||||
i.after('2');
|
||||
console.log(p.innerHTML);
|
||||
// a node among its own replacements keeps its place among them
|
||||
i.replaceWith(i, 'w');
|
||||
console.log(p.innerHTML);
|
||||
const s = document.createElement('section');
|
||||
s.lang = 'de';
|
||||
s.dir = 'rtl';
|
||||
console.log(s.lang, s.dir, s.outerHTML);",
|
||||
"test",
|
||||
);
|
||||
let logs = doc.take_messages();
|
||||
assert_eq!(doc.take_js_errors(), Vec::<String>::new());
|
||||
assert_eq!(
|
||||
logs,
|
||||
[
|
||||
"log: x<b>y</b><i id=\"i\">z</i> null",
|
||||
"log: x<b>y</b>1<u></u><i id=\"i\">z</i>2",
|
||||
"log: x<b>y</b>1<u></u><i id=\"i\">z</i>w2",
|
||||
"log: de rtl <section lang=\"de\" dir=\"rtl\"></section>",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,10 @@ fn content_document_is_the_iframes_own() {
|
|||
const s = d.createElement('span');
|
||||
d.body.append(s, 'tail');
|
||||
console.log(s.ownerDocument === d, d.body.lastChild.data, d.querySelectorAll('span').length, document.querySelectorAll('span').length);
|
||||
try { d.body.appendChild(document.createElement('b')); } catch (e) { console.log(e.name); }
|
||||
// a node of the page moves into the iframe's document (adopted)
|
||||
const b = document.createElement('b');
|
||||
d.body.appendChild(b);
|
||||
console.log(b.ownerDocument === d, d.querySelectorAll('b').length, document.querySelectorAll('b').length);
|
||||
// foliate-js's paginator focuses the section's window after each turn
|
||||
w.focus(); w.blur(); window.focus();
|
||||
console.log(typeof w.focus, typeof window.blur);
|
||||
|
|
@ -53,7 +56,7 @@ fn content_document_is_the_iframes_own() {
|
|||
"true true true true 300 200",
|
||||
"50px 50 50px",
|
||||
"true tail 1 0",
|
||||
"WrongDocumentError",
|
||||
"true 1 0",
|
||||
"function function",
|
||||
]
|
||||
);
|
||||
|
|
|
|||
|
|
@ -57,9 +57,42 @@ fn a_lone_text_node_is_adopted() {
|
|||
const t = document.createTextNode(' ');
|
||||
d.body.insertBefore(t, d.body.firstChild);
|
||||
console.log(t.ownerDocument === d, t.parentNode === d.body, JSON.stringify(d.body.innerHTML));
|
||||
try { d.body.append(document.getElementById('x')); } catch (e) { console.log(e.name); }",
|
||||
d.body.append(document.getElementById('x'));
|
||||
console.log(d.body.lastChild.id, d.body.lastChild.ownerDocument === d, document.getElementById('x'));",
|
||||
);
|
||||
assert_eq!(out, ["true true \" <p>x</p>\"", "x true null"]);
|
||||
}
|
||||
|
||||
// Readest's Wiktionary lookup parses an edition's page with DOMParser and moves the section it
|
||||
// wants into the page: the moved nodes are the same objects, now in the page, with their tree.
|
||||
#[test]
|
||||
fn an_element_from_a_parsed_document_is_adopted_with_its_tree() {
|
||||
let mut doc = page();
|
||||
let out = logs(
|
||||
&mut doc,
|
||||
"const d = __blitzParseHTML('<div id=\"r\"><h2>Deutsch</h2><ol><li>Raum <a href=\"/wiki/x\">x</a></li></ol></div>');
|
||||
const root = d.getElementById('r');
|
||||
const li = d.querySelector('li');
|
||||
let clicks = 0;
|
||||
li.addEventListener('click', () => clicks++);
|
||||
const kids = Array.from(root.children);
|
||||
const sec = document.createElement('section');
|
||||
document.body.append(sec);
|
||||
kids.forEach((el) => sec.append(el));
|
||||
console.log(sec.innerHTML, root.children.length);
|
||||
console.log(kids[0].ownerDocument === document, kids[1].parentNode === sec, sec.querySelector('li') === li, li.ownerDocument === document);
|
||||
li.click();
|
||||
const a = sec.querySelector('a');
|
||||
console.log(clicks, li.textContent, a.getAttribute('href'), a.closest('section') === sec);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
[
|
||||
"<h2>Deutsch</h2><ol><li>Raum <a href=\"/wiki/x\">x</a></li></ol> 0",
|
||||
"true true true true",
|
||||
"1 Raum x /wiki/x true",
|
||||
]
|
||||
);
|
||||
assert_eq!(out, ["true true \" <p>x</p>\"", "WrongDocumentError"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -217,3 +217,81 @@ fn selection_holds_a_range_per_document() {
|
|||
]
|
||||
);
|
||||
}
|
||||
|
||||
// Readest reads a selection's text from `cloneContents()` (getTextFromRange), and its paragraph
|
||||
// mode, vocabulary sentences and instant highlights clone a range's contents too.
|
||||
#[test]
|
||||
fn a_ranges_contents_are_cloned_or_moved_into_a_fragment() {
|
||||
let (logs, errors) = run("
|
||||
const html = (f) => { const d = document.createElement('div'); d.append(f); return d.innerHTML; };
|
||||
const r = document.createRange();
|
||||
r.setStart(t1, 1);
|
||||
r.setEnd(t1, 3);
|
||||
console.log(html(r.cloneContents()), '|', $('p1').innerHTML);
|
||||
// across paragraphs: the elements partly in the range are cloned without what is outside
|
||||
r.setStart(t1, 2);
|
||||
r.setEnd($('p2').firstChild, 2);
|
||||
console.log(html(r.cloneContents()));
|
||||
const w = document.createTreeWalker(r.cloneContents(), NodeFilter.SHOW_TEXT);
|
||||
const texts = [];
|
||||
for (let n; (n = w.nextNode()); ) texts.push(n.data);
|
||||
console.log(JSON.stringify(texts));
|
||||
console.log($('a').innerHTML);
|
||||
// extracting moves them out and leaves the range collapsed where they were
|
||||
console.log(html(r.extractContents()));
|
||||
console.log($('a').innerHTML, r.collapsed, r.startContainer === $('a'), r.startOffset);
|
||||
");
|
||||
assert_eq!(errors, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
logs,
|
||||
[
|
||||
"ne | one <b id=\"b\">two</b> three",
|
||||
"<p id=\"p1\">e <b id=\"b\">two</b> three</p><!--c--><p id=\"p2\">fo</p>",
|
||||
"[\"e \",\"two\",\" three\",\"fo\"]",
|
||||
"<p id=\"p1\">one <b id=\"b\">two</b> three</p><!--c--><p id=\"p2\">four</p>",
|
||||
"<p id=\"p1\">e <b id=\"b\">two</b> three</p><!--c--><p id=\"p2\">fo</p>",
|
||||
"<p id=\"p1\">on</p><p id=\"p2\">ur</p> true true 1",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_contents_removes_what_the_range_selects() {
|
||||
let (logs, errors) = run("
|
||||
const r = document.createRange();
|
||||
r.setStart(t1, 1);
|
||||
r.setEnd(t3, 2);
|
||||
r.deleteContents();
|
||||
console.log($('p1').innerHTML, r.collapsed, r.startContainer === $('p1'), r.startOffset);
|
||||
");
|
||||
assert_eq!(errors, Vec::<String>::new());
|
||||
assert_eq!(logs, ["ohree true true 1"]);
|
||||
}
|
||||
|
||||
// Word Lens puts a ruby around a word: extractContents(), then insertNode() of the ruby holding it.
|
||||
#[test]
|
||||
fn insert_node_splits_the_text_at_the_range_start() {
|
||||
let (logs, errors) = run("
|
||||
const r = document.createRange();
|
||||
r.setStart(t3, 3);
|
||||
r.insertNode(document.createElement('i'));
|
||||
console.log($('p1').innerHTML, r.startContainer === t3, r.startOffset, r.endContainer === $('p1'), r.endOffset);
|
||||
r.setStart(bt, 0);
|
||||
r.setEnd(bt, 3);
|
||||
const ruby = document.createElement('ruby');
|
||||
ruby.append(r.extractContents());
|
||||
r.insertNode(ruby);
|
||||
console.log($('b').innerHTML, r.toString());
|
||||
const tail = t1.splitText(2);
|
||||
console.log(t1.data, tail.data, tail.previousSibling === t1);
|
||||
");
|
||||
assert_eq!(errors, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
logs,
|
||||
[
|
||||
"one <b id=\"b\">two</b> th<i></i>ree true 3 true 4",
|
||||
"<ruby>two</ruby> two",
|
||||
"on e true",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -285,6 +285,12 @@
|
|||
inline root's text, so its client rect is a zero-width box where its line ends, after the text
|
||||
before it, with that text's top and height (at the line's start on a line holding nothing
|
||||
else), as in Chromium. Every `<br>` was an empty box at its paragraph's start.
|
||||
- `blitz-dom` document: `caret_position_from_point` (CSSOM View's `caretPositionFromPoint`) maps
|
||||
a point to the text node under it and the byte offset of the caret nearest it, through the
|
||||
inline root's text (`find_text_position`) and back to the node's own text, counting the white
|
||||
space the line collapsed (`dom_offset`, the inverse of `laid_out_offset`) and a floated
|
||||
`::first-letter`. Generated text (`::before`, `::after`) has no caret. Readest selects the word
|
||||
under a double tap with it.
|
||||
|
||||
## stylo.diff (servo/stylo 2dca34592, 0.23.0)
|
||||
|
||||
|
|
|
|||
|
|
@ -1134,7 +1134,66 @@ diff -ruN blitz/packages/blitz-dom/src/document.rs blitz/packages/blitz-dom/src/
|
|||
}
|
||||
|
||||
/// The first element in tree order with the given tag name. The root element and
|
||||
@@ -2944,6 +3527,36 @@
|
||||
@@ -2661,6 +3244,58 @@
|
||||
Some((inline_root.id, byte_offset))
|
||||
}
|
||||
|
||||
+ /// CSSOM View's `caretPositionFromPoint`: the text node under viewport point (x, y) and the
|
||||
+ /// byte offset in its content of the caret nearest the point. A caret between two text nodes
|
||||
+ /// is at the end of the first. None off text, and on generated text (`::before`, `::after`,
|
||||
+ /// a floated `::first-letter`).
|
||||
+ pub fn caret_position_from_point(&self, x: f32, y: f32) -> Option<(NodeId, usize)> {
|
||||
+ let (root, at) = self.find_text_position(x, y)?;
|
||||
+ let text = self.get_node(root)?.element_data()?.inline_layout_data.as_deref()?;
|
||||
+ // A pseudo-element's box is not among its parent's children.
|
||||
+ let in_dom = |mut id: NodeId| {
|
||||
+ while let Some(p) = self.nodes[id].parent {
|
||||
+ if !self.nodes[p].children.contains(&id) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ id = p;
|
||||
+ }
|
||||
+ true
|
||||
+ };
|
||||
+ let texts = || {
|
||||
+ text.text_nodes
|
||||
+ .iter()
|
||||
+ .filter(|t| matches!(self.nodes[t.0].data, NodeData::Text(_)) && in_dom(t.0))
|
||||
+ };
|
||||
+ let &(node_id, from, _) = texts()
|
||||
+ .find(|t| t.1 <= at && at <= t.2)
|
||||
+ .or_else(|| texts().filter(|t| t.1 <= at).last())?;
|
||||
+ let node = &self.nodes[node_id];
|
||||
+ let NodeData::Text(data) = &node.data else {
|
||||
+ return None;
|
||||
+ };
|
||||
+ let collapse = node
|
||||
+ .parent
|
||||
+ .and_then(|p| self.get_node(p)?.primary_styles())
|
||||
+ .is_none_or(|s| {
|
||||
+ s.get_inherited_text().white_space_collapse
|
||||
+ == style::computed_values::white_space_collapse::T::Collapse
|
||||
+ });
|
||||
+ // A floated (or otherwise not inline) `::first-letter` box holds part of this text, laid
|
||||
+ // out apart from the rest (text_rects).
|
||||
+ let skip = crate::layout::inline::first_letter_skip(&self.nodes, node_id).filter(|&(b, _)| {
|
||||
+ !self.nodes[b].display_style().is_some_and(|d| {
|
||||
+ d.outside() == style::values::specified::box_::DisplayOutside::Inline
|
||||
+ && d.inside() == style::values::specified::box_::DisplayInside::Flow
|
||||
+ })
|
||||
+ });
|
||||
+ let Some((_, skip)) = skip else {
|
||||
+ return Some((node_id, dom_offset(&data.content, at, &text.text, from, collapse)));
|
||||
+ };
|
||||
+ let rest = [&data.content[..skip.start], &data.content[skip.end..]].concat();
|
||||
+ let offset = dom_offset(&rest, at, &text.text, from, collapse);
|
||||
+ Some((node_id, if offset < skip.start { offset } else { offset + skip.len() }))
|
||||
+ }
|
||||
+
|
||||
/// Set the text selection range (creates a new selection from anchor to focus)
|
||||
pub fn set_text_selection(
|
||||
&mut self,
|
||||
@@ -2944,6 +3579,66 @@
|
||||
/// Snap a CSSOM geometry value to a 1/64px grid (the precision of Blink's `LayoutUnit`).
|
||||
/// Layout values are accumulated in `f32`, so e.g. seven `55/7`-wide flex items would
|
||||
/// otherwise end at `55.0000005` and appear to overflow their 55px container.
|
||||
|
|
@ -1167,11 +1226,41 @@ diff -ruN blitz/packages/blitz-dom/src/document.rs blitz/packages/blitz-dom/src/
|
|||
+ }
|
||||
+ from + li
|
||||
+}
|
||||
+
|
||||
+/// The inverse of `laid_out_offset`: the last byte offset in `content` laid out at or before
|
||||
+/// `at`, so a caret after a run of collapsed white space is after all of it.
|
||||
+fn dom_offset(content: &str, at: usize, text: &str, from: usize, collapse: bool) -> usize {
|
||||
+ let space = |c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\u{c}');
|
||||
+ let laid = &text[from.min(text.len())..];
|
||||
+ let mut li = 0;
|
||||
+ if collapse && laid.starts_with(' ') && !content.starts_with(space) {
|
||||
+ li = 1;
|
||||
+ }
|
||||
+ let mut in_space = false;
|
||||
+ let mut last = 0;
|
||||
+ for (i, c) in content.char_indices() {
|
||||
+ if from + li > at {
|
||||
+ return last;
|
||||
+ }
|
||||
+ last = i;
|
||||
+ let next = laid[li..].chars().next();
|
||||
+ if collapse && space(c) {
|
||||
+ if !in_space && next.is_some_and(space) {
|
||||
+ li += 1;
|
||||
+ }
|
||||
+ in_space = true;
|
||||
+ continue;
|
||||
+ }
|
||||
+ in_space = false;
|
||||
+ li += next.map_or(0, char::len_utf8);
|
||||
+ }
|
||||
+ if from + li > at { last } else { content.len() }
|
||||
+}
|
||||
+
|
||||
fn snap_to_layout_unit(value: f64) -> f64 {
|
||||
(value * 64.0).round() / 64.0
|
||||
}
|
||||
@@ -3508,6 +4121,58 @@
|
||||
@@ -3508,6 +4203,58 @@
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -1230,7 +1319,7 @@ diff -ruN blitz/packages/blitz-dom/src/document.rs blitz/packages/blitz-dom/src/
|
|||
mod inline_with_only_block_children_tests {
|
||||
use super::*;
|
||||
use crate::qual_name;
|
||||
@@ -3781,3 +4446,7 @@
|
||||
@@ -3781,3 +4528,7 @@
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue