diff --git a/Sources/Early/PageToolsView.swift b/Sources/Early/PageToolsView.swift index d65b7a1..567dbd3 100644 --- a/Sources/Early/PageToolsView.swift +++ b/Sources/Early/PageToolsView.swift @@ -614,6 +614,7 @@ struct PageFindBar: View { var body: some View { let tint = model.chromeTheme.focusBorder(isDark: colorScheme == .dark, increasedContrast: contrast == .increased).color let status = Self.status(for: state) + let canStep = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty HStack(spacing: 4) { Image(systemName: "magnifyingglass") .font(.system(size: 12, weight: .semibold)) @@ -638,9 +639,9 @@ struct PageFindBar: View { .accessibilityIdentifier("find.status") Divider().frame(height: 16).padding(.horizontal, 2) control("chevron.up", "Previous Match\(model.preferences.shortcutHint(.findPrevious))", identifier: "find.previous") { step(backwards: true) } - .disabled(state.matchCount == 0) + .disabled(!canStep) control("chevron.down", "Next Match\(model.preferences.shortcutHint(.findNext))", identifier: "find.next") { step(backwards: false) } - .disabled(state.matchCount == 0) + .disabled(!canStep) control("xmark", "Close Find (Escape)", identifier: "find.close") { model.closeFind(tabID) } } .padding(.horizontal, 8) diff --git a/Sources/Early/TestPages.swift b/Sources/Early/TestPages.swift index 847feaf..c7ceae5 100644 --- a/Sources/Early/TestPages.swift +++ b/Sources/Early/TestPages.swift @@ -116,6 +116,15 @@ final class TestPages: NSObject, WKURLSchemeHandler { """) return } + if url.path == "/find" { + respond(to: task, url: url, html: """ +
Needle in the first paragraph.
Needle in the second paragraph.
+ """) + return + } if url.path == "/article" { // Long enough for Readability's article check; French for translation. let paragraph = url.query == "lang=fr" diff --git a/Sources/EarlyWeb/MediaActivityObserver.swift b/Sources/EarlyWeb/MediaActivityObserver.swift index 4492b13..589cc8a 100644 --- a/Sources/EarlyWeb/MediaActivityObserver.swift +++ b/Sources/EarlyWeb/MediaActivityObserver.swift @@ -119,12 +119,36 @@ final class MediaActivityObserver: NSObject, WKScriptMessageHandlerWithReply { if (e.target instanceof HTMLMediaElement) { track(e.target); update(); } }, true); new MutationObserver(records => { - for (const record of records) for (const node of record.addedNodes) scan(node); + const added = new Set(); + for (const record of records) for (const node of record.addedNodes) { + if (node.nodeType === Node.ELEMENT_NODE) added.add(node); + } + // A batch can contain the same node or both a node and its ancestors. + // Cache ancestor lookups so a deep shared path is examined only once. + const covered = new Map(); + for (const node of added) { + const path = []; + let parent = node.parentElement; + while (parent && !added.has(parent) && !covered.has(parent)) { + path.push(parent); + parent = parent.parentElement; + } + const hasAddedAncestor = parent !== null && (added.has(parent) || covered.get(parent)); + for (const element of path) covered.set(element, hasAddedAncestor); + // Keep this in the mutation checkpoint, including detached players + // that can still be playing. A muted tab cannot wait for a timer. + if (!hasAddedAncestor) scan(node); + } update(); }).observe(document, {subtree: true, childList: true}); - document.addEventListener('DOMContentLoaded', () => { scan(document); update(); }, {once: true}); window.addEventListener('pagehide', () => { hidden = true; send(false, true); }); - window.addEventListener('pageshow', () => { hidden = false; last = null; scan(document); update(); }); + window.addEventListener('pageshow', () => { + const restored = hidden; + hidden = false; + last = null; + if (restored) scan(document); + update(); + }); // Only the native owner in the isolated world can set tab mute state. globalThis.__earlyMediaControl = {applyState, get documentToken() { return hidden ? null : token; }}; scan(document); diff --git a/Sources/EarlyWeb/PageFind.swift b/Sources/EarlyWeb/PageFind.swift index 9b2c8bd..f272048 100644 --- a/Sources/EarlyWeb/PageFind.swift +++ b/Sources/EarlyWeb/PageFind.swift @@ -132,7 +132,40 @@ extension WebViewManager { 'DETAILS', 'DIALOG', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'FORM', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HTML', 'LABEL', 'LEGEND', 'LI', 'MAIN', 'NAV', 'OL', 'P', 'PRE', 'SECTION', 'SUMMARY', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TR', 'UL']); - let query = '', ranges = [], index = -1, capped = false, dirty = true, observer = null, sheet = null; + // The DOM Standard allows these HTML elements and custom elements to host a shadow root. + const shadowHostNames = new Set(['ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'BODY', 'DIV', 'FOOTER', 'H1', 'H2', + 'H3', 'H4', 'H5', 'H6', 'HEADER', 'MAIN', 'NAV', 'P', 'SECTION', 'SPAN']); + let query = '', ranges = [], index = -1, capped = false, dirty = true, sheet = null; + let hiddenRanges = [], hiddenOverflow = false; + let roots = new Set(), potentialHosts = []; + const invalidate = () => { dirty = true; }; + const observer = new MutationObserver(invalidate); + const stylesheetLoaded = event => { if (event.target.localName === 'link') invalidate(); }; + + const observe = nextRoots => { + observer.disconnect(); + for (const root of roots) { + if (nextRoots.has(root)) continue; + root.removeEventListener('load', stylesheetLoaded, true); + if (sheet && root.adoptedStyleSheets.includes(sheet)) { + root.adoptedStyleSheets = root.adoptedStyleSheets.filter(candidate => candidate !== sheet); + } + } + for (const root of nextRoots) { + // Any attribute can participate in a CSS selector that changes visibility. + observer.observe(root, { childList: true, characterData: true, attributes: true, subtree: true }); + root.addEventListener('load', stylesheetLoaded, true); + } + roots = nextRoots; + if (roots.size) { + window.addEventListener('resize', invalidate); + window.addEventListener('pagehide', leave); + } else { + window.removeEventListener('resize', invalidate); + window.removeEventListener('pagehide', leave); + potentialHosts = []; + } + }; const blockOf = node => { let element = node.parentElement; @@ -142,27 +175,40 @@ extension WebViewManager { // All visible text as one string, with an unmatchable separator between // blocks so a match can span inline tags but not two paragraphs. const collect = () => { - const segments = []; - let text = '', lastBlock; - const visit = root => { - const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, { - acceptNode(node) { - if (node.nodeType !== Node.ELEMENT_NODE) return NodeFilter.FILTER_ACCEPT; - if (skipped.has(node.tagName)) return NodeFilter.FILTER_REJECT; - return node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; - } - }); - for (let node = walker.nextNode(); node; node = walker.nextNode()) { - if (node.nodeType === Node.ELEMENT_NODE) { visit(node.shadowRoot); continue; } - if (!node.data) continue; - const block = blockOf(node); - if (text.length && block !== lastBlock) text += '\u0000'; - lastBlock = block; - segments.push({ node, start: text.length }); - text += node.data; + const segments = [], walkers = [], searchedRoots = new Set([document]); + let text = '', lastBlock, newRoot = false; + potentialHosts = []; + const walk = root => document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, { + acceptNode: node => skipped.has(node.tagName) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT + }); + const visitHost = element => { + const root = element.shadowRoot; + if (root) { + walkers.push(walk(root)); + searchedRoots.add(root); + newRoot = true; + } else if (element instanceof HTMLElement + && (shadowHostNames.has(element.tagName) || element.localName.includes('-'))) { + potentialHosts.push(element); } }; - if (document.body) visit(document.body); + if (document.body) { + walkers.push(walk(document.body)); + visitHost(document.body); + } + while (walkers.length) { + const node = walkers[walkers.length - 1].nextNode(); + if (!node) { walkers.pop(); newRoot = true; continue; } + if (node.nodeType === Node.ELEMENT_NODE) { visitHost(node); continue; } + if (!node.length) continue; + const block = blockOf(node); + if (text.length && (newRoot || block !== lastBlock)) text += '\u0000'; + newRoot = false; + lastBlock = block; + segments.push({ node, start: text.length }); + text += node.data; + } + observe(searchedRoots); return { text, segments }; }; const pattern = value => { @@ -180,11 +226,16 @@ extension WebViewManager { return [segments[low].node, offset - segments[low].start]; }; const visible = range => { - const element = range.startContainer.parentElement; - if (!element) return false; - if (typeof element.checkVisibility === 'function' - && !element.checkVisibility({ visibilityProperty: true, checkVisibilityCSS: true })) return false; - return range.getClientRects().length > 0; + const start = range.startContainer, end = range.endContainer; + const rendered = node => { + const element = node.parentElement || node.getRootNode().host; + if (!element || !node.isConnected) return false; + if (element.checkVisibility?.({ visibilityProperty: true, checkVisibilityCSS: true }) !== false) return true; + // display:contents has no box of its own but can render text. + const style = getComputedStyle(element); + return style.display === 'contents' && style.visibility === 'visible'; + }; + return !range.collapsed && rendered(start) && (end === start || rendered(end)) && range.getClientRects().length > 0; }; const unpaint = () => { try { @@ -195,10 +246,12 @@ extension WebViewManager { const search = limit => { unpaint(); ranges = []; + hiddenRanges = []; + hiddenOverflow = false; capped = false; dirty = false; const expression = pattern(query); - if (!expression) return; + if (!expression) { observe(new Set()); return; } const { text, segments } = collect(); for (let match = expression.exec(text); match; match = expression.exec(text)) { if (!match[0].length) { expression.lastIndex++; continue; } @@ -209,28 +262,29 @@ extension WebViewManager { range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); } catch (_) { continue; } - if (!visible(range)) continue; + if (!visible(range)) { + if (hiddenRanges.length < limit) hiddenRanges.push(range); + else hiddenOverflow = true; + continue; + } if (ranges.length >= limit) { capped = true; break; } ranges.push(range); } - if (!observer) { - observer = new MutationObserver(() => { dirty = true; }); - observer.observe(document.documentElement, { childList: true, characterData: true, subtree: true }); - } }; const firstInView = () => { const found = ranges.findIndex(range => range.getBoundingClientRect().bottom >= 0); return found < 0 ? 0 : found; }; const paint = () => { + if (!ranges.length) return; try { if (!sheet) { sheet = new CSSStyleSheet(); sheet.replaceSync('::highlight(early-find){background-color:rgba(255,212,0,.45);color:inherit}' + '::highlight(early-find-current){background-color:#ff9500;color:#000}'); } - if (!document.adoptedStyleSheets.includes(sheet)) { - document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; + for (const root of roots) { + if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet]; } CSS.highlights.set('early-find', new Highlight(...ranges)); if (index >= 0) { @@ -251,7 +305,7 @@ extension WebViewManager { }; const reveal = () => { const range = ranges[index]; - const element = range && range.startContainer.parentElement; + const element = range && (range.startContainer.parentElement || range.startContainer.getRootNode().host); if (!element) return; const outside = rect => rect.top < 0 || rect.bottom > innerHeight || rect.left < 0 || rect.right > innerWidth; if (!outside(range.getBoundingClientRect())) return; @@ -261,6 +315,60 @@ extension WebViewManager { }; const answer = () => { paint(); reveal(); return { count: ranges.length, index, capped }; }; + // Positions in different trees cannot be compared directly. A shadow + // range sorts at the start of its host when viewed from the outer tree. + function* startPositions(range) { + for (let position = range; position;) { + const root = position.startContainer.getRootNode(); + yield [root, position]; + if (!root.host?.isConnected) return; + position = document.createRange(); + position.setStart(root.host, 0); + } + } + const positionAfterSearch = (previous, ordinal, delta) => { + if (!previous) return -1; + const anchors = new Map(startPositions(previous)); + for (const [next, range] of ranges.entries()) { + for (const [root, position] of startPositions(range)) { + const anchor = anchors.get(root); + if (!anchor) continue; + const order = position.compareBoundaryPoints(Range.START_TO_START, anchor); + if (order > 0) return delta > 0 ? next - 1 : next; + if (order === 0) return next; + break; + } + } + const next = previous.startContainer.isConnected ? ranges.length : Math.min(ordinal, ranges.length); + return delta > 0 ? next - 1 : next; + }; + const needsSearch = () => dirty || observer.takeRecords().length > 0 + // Attaching an open root to an existing host emits no mutation record. + || potentialHosts.some(host => host.shadowRoot) + // In-place CSSOM changes can affect visibility without touching the DOM. + || hiddenOverflow || hiddenRanges.some(visible) || ranges.some(range => !visible(range)); + const clear = selectCurrent => { + const current = ranges[index]; + unpaint(); + observe(new Set()); + if (selectCurrent && current && visible(current)) { + const text = current.toString(); + const match = pattern(query)?.exec(text); + const selection = window.getSelection(); + if (selection && match?.index === 0 && match[0].length === text.length) { + selection.removeAllRanges(); + selection.addRange(current.cloneRange()); + } + } + ranges = []; + hiddenRanges = []; + hiddenOverflow = false; + index = -1; + query = ''; + dirty = true; + }; + const leave = () => clear(false); + return { update(value, delta, limit) { query = value; @@ -270,41 +378,17 @@ extension WebViewManager { }, step(value, delta, limit) { if (value !== query) { query = value; search(limit); index = -1; } - else if (dirty) { - // Keep the place in a changed page: resume at the old match. - const previous = ranges[index]; + else if (needsSearch()) { + const previous = ranges[index], ordinal = index; search(limit); - index = -1; - if (previous && ranges.length) { - let next = ranges.findIndex(range => { - try { return range.compareBoundaryPoints(Range.START_TO_START, previous) >= 0; } - catch (_) { return false; } - }); - if (next < 0) next = ranges.length; - let same = false; - try { same = !!ranges[next] && ranges[next].compareBoundaryPoints(Range.START_TO_START, previous) === 0; } - catch (_) {} - index = same ? next : (delta > 0 ? next - 1 : next); - } + index = positionAfterSearch(previous, ordinal, delta); } if (!ranges.length) { index = -1; return answer(); } if (index < 0 && delta < 0) index = ranges.length; index = ((index + delta) % ranges.length + ranges.length) % ranges.length; return answer(); }, - clear(selectCurrent) { - const current = ranges[index]; - unpaint(); - if (observer) { observer.disconnect(); observer = null; } - if (selectCurrent && current) { - const selection = window.getSelection(); - if (selection) { selection.removeAllRanges(); selection.addRange(current.cloneRange()); } - } - ranges = []; - index = -1; - query = ''; - dirty = true; - } + clear }; })(); """# diff --git a/Sources/EarlyWeb/PageReader.swift b/Sources/EarlyWeb/PageReader.swift index dc3eb75..28543e7 100644 --- a/Sources/EarlyWeb/PageReader.swift +++ b/Sources/EarlyWeb/PageReader.swift @@ -5,6 +5,7 @@ import WebKit /// A readable copy of an article, extracted by Mozilla Readability. public struct ReaderArticle: Equatable, Sendable { + static let maximumContentBytes = 4_000_000 public let title: String public let byline: String? public let siteName: String? @@ -18,7 +19,7 @@ public struct ReaderArticle: Equatable, Sendable { init?(_ value: Any?) { guard let values = value as? [String: Any], let content = values["content"] as? String, - !content.isEmpty, content.utf8.count <= 4_000_000 else { return nil } + !content.isEmpty, content.utf8.count <= Self.maximumContentBytes else { return nil } func text(_ key: String) -> String? { let value = (values[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) return value?.isEmpty == false ? String(value!.prefix(300)) : nil @@ -141,6 +142,8 @@ extension WebViewManager { static let readerWorld = WKContentWorld.world(name: "Early.Reader") static let readabilitySource = readabilityResource("Readability") static let readerableSource = readabilityResource("Readability-readerable") + static let readerArguments = ["maxElements": 20_000, "maxNodes": 60_000, "maxDepth": 256, + "maxSourceCharacters": 4_000_000, "maxContentBytes": ReaderArticle.maximumContentBytes] private static func readabilityResource(_ name: String) -> String? { Bundle.module.url(forResource: name, withExtension: "js", subdirectory: "Readability") @@ -160,8 +163,8 @@ extension WebViewManager { return } let generation = page.navigationGeneration - page.view.callAsyncJavaScript("\(source)\nreturn isProbablyReaderable(document);", - arguments: [:], in: nil, in: Self.readerWorld) { [weak self, weak page] result in + page.view.callAsyncJavaScript("\(Self.readerPreflight)\n\(source)\nreturn isProbablyReaderable(document);", + arguments: Self.readerArguments, in: nil, in: Self.readerWorld) { [weak self, weak page] result in guard let self, let page, self.pages[id] === page, page.navigationGeneration == generation else { return } let available = (try? result.get()) as? Bool ?? false if page.isReaderAvailable != available { page.isReaderAvailable = available } @@ -179,7 +182,7 @@ extension WebViewManager { defer { page.isPreparingReader = false } let generation = page.navigationGeneration let value = try? await page.view.callAsyncJavaScript("\(source)\n\(Self.readerExtraction)", - arguments: [:], in: nil, contentWorld: Self.readerWorld) + arguments: Self.readerArguments, in: nil, contentWorld: Self.readerWorld) guard pages[id] === page, page.navigationGeneration == generation, !page.isReaderShown, let article = ReaderArticle(value) else { return false } hideFind(id) @@ -229,10 +232,53 @@ extension WebViewManager { } } + /// Check the live document without allocating a clone or a complete node list. + static let readerPreflight = #""" + const withinReaderBudget = () => { + let elements = 0, nodes = 0, characters = 0; + const stack = [document.childNodes.values()]; + while (stack.length) { + const next = stack[stack.length - 1].next(); + if (next.done) { stack.pop(); continue; } + if (++nodes > maxNodes || stack.length > maxDepth) return false; + const node = next.value; + if (node.nodeType === Node.ELEMENT_NODE) { + if (++elements > maxElements || (nodes += node.attributes.length) > maxNodes) return false; + characters += node.localName.length; + for (const attribute of node.attributes) { + characters += attribute.name.length + attribute.value.length; + if (characters > maxSourceCharacters) return false; + } + } else if (node instanceof CharacterData) { + characters += node.length; + } else if (node.nodeType === Node.DOCUMENT_TYPE_NODE) { + characters += node.name.length + node.systemId.length + node.publicId.length; + } + if (characters > maxSourceCharacters) return false; + const container = node instanceof HTMLTemplateElement ? node.content : node; + const children = container.childNodes, childCount = children.length; + // Reject wide subtrees before crossing into JavaScript for each child. + if (childCount > maxNodes - nodes || (childCount > maxElements - elements + && container.childElementCount > maxElements - elements)) return false; + if (childCount) stack.push(children.values()); + // A document clone also copies open roots marked as clonable. + const shadow = node.shadowRoot; + if (shadow?.clonable && shadow.firstChild) stack.push(shadow.childNodes.values()); + } + return true; + }; + if (!withinReaderBudget()) return null; + """# + /// Appended to Readability in the same function body. - static let readerExtraction = #""" - const parsed = new Readability(document.cloneNode(true), { charThreshold: 500 }).parse(); - if (!parsed || !parsed.content) return null; + static let readerExtraction = readerPreflight + #""" + + const fitsContentBudget = content => !!content && content.length <= maxContentBytes + && (content.length <= maxContentBytes / 3 || new TextEncoder().encode(content).length <= maxContentBytes); + const parsed = new Readability(document.cloneNode(true), { + charThreshold: 500, maxElemsToParse: maxElements + }).parse(); + if (!parsed || !fitsContentBudget(parsed.content)) return null; const holder = new DOMParser().parseFromString('', 'text/html'); holder.body.innerHTML = parsed.content; holder.querySelectorAll('script, style, link, meta, base, iframe, frame, frameset, object, embed, applet, ' @@ -250,14 +296,17 @@ extension WebViewManager { } } } + const content = holder.body.innerHTML; + if (!fitsContentBudget(content)) return null; const text = holder.body.textContent || ''; + const metadata = value => typeof value === 'string' ? value.slice(0, 1200) : null; return { - title: parsed.title || document.title || '', - byline: parsed.byline || null, - siteName: parsed.siteName || null, - lang: parsed.lang || document.documentElement.lang || null, - dir: parsed.dir || null, - content: holder.body.innerHTML, + title: metadata(parsed.title || document.title), + byline: metadata(parsed.byline), + siteName: metadata(parsed.siteName), + lang: metadata(parsed.lang || document.documentElement.lang), + dir: metadata(parsed.dir), + content, words: (text.match(/\S+/g) || []).length }; """# diff --git a/Sources/EarlyWeb/PageTranslation.swift b/Sources/EarlyWeb/PageTranslation.swift index c98ec8c..8fcb1d3 100644 --- a/Sources/EarlyWeb/PageTranslation.swift +++ b/Sources/EarlyWeb/PageTranslation.swift @@ -35,6 +35,7 @@ extension WebViewManager { static let translationWorld = WKContentWorld.world(name: "Early.Translate") static let translationBatchSize = 40 static let translationLimits = (nodes: 3000, characters: 100_000, visited: 30_000) + static let languageSampleArguments = ["maxCharacters": 2_000, "maxRead": 8_000, "maxVisited": 4_000] public func canTranslate(_ id: UUID) -> Bool { translationTarget(for: id) != nil @@ -51,10 +52,8 @@ extension WebViewManager { func detectPageLanguage(_ id: UUID) { guard let page = pages[id], page.view.url.flatMap({ try? input.validate($0) }) != nil else { return } let generation = page.navigationGeneration - page.view.callAsyncJavaScript(""" - return { lang: document.documentElement.lang || '', - text: (document.body ? document.body.innerText : '').slice(0, 2000) }; - """, arguments: [:], in: nil, in: Self.translationWorld) { [weak self, weak page] result in + page.view.callAsyncJavaScript(Self.languageSample, arguments: Self.languageSampleArguments, + in: nil, in: Self.translationWorld) { [weak self, weak page] result in guard let self, let page, self.pages[id] === page, page.navigationGeneration == generation, let values = (try? result.get()) as? [String: Any] else { return } let language = Self.dominantLanguage(text: values["text"] as? String ?? "", hint: values["lang"] as? String ?? "") @@ -154,7 +153,72 @@ extension WebViewManager { private struct TranslationMismatch: Error {} - static let translationCollect = #""" + private static let visibleTextNodes = #""" + function* visibleTextNodes(excludeElement) { + const skipped = new Set(['head', 'script', 'style', 'noscript', 'template', 'textarea', 'input', 'select', 'option', + 'code', 'pre', 'kbd', 'samp', 'var', 'svg', 'math', 'iframe', 'object', 'embed', 'canvas', 'audio', 'video']); + let visited = 0; + function* slotChildren(slot) { + const host = slot.getRootNode().host; + if (!host || host.childNodes.length <= maxVisited - visited) { + const assigned = slot.assignedNodes(); + yield* (assigned.length ? assigned : slot.childNodes); + return; + } + // Charge oversized slot assignments to the same visit budget without copying the list. + let found = false; + for (const child of host.childNodes) { + if (++visited >= maxVisited) return; + if (child.assignedSlot === slot) { found = true; yield child; } + } + if (!found) yield* slot.childNodes; + } + const stack = [{ children: document.childNodes.values(), visible: true }]; + while (stack.length && visited < maxVisited) { + const level = stack[stack.length - 1], next = level.children.next(); + if (next.done) { stack.pop(); continue; } + const node = next.value; + visited++; + if (level.summaryOnly) { + if (node.localName !== 'summary') continue; + stack.pop(); // Only the first direct summary is rendered in closed details. + } + if (node.nodeType === Node.TEXT_NODE) { + if (level.visible && node.length) yield node; + continue; + } + if (node.nodeType !== Node.ELEMENT_NODE || skipped.has(node.localName) || node.hasAttribute('hidden') + || node.isContentEditable || excludeElement(node)) continue; + const style = getComputedStyle(node); + if (style.display === 'none' || style.contentVisibility === 'hidden' || style.opacity === '0') continue; + // Descendants can override inherited visibility. Their own styles decide. + const visible = style.visibility !== 'hidden' && style.visibility !== 'collapse'; + const root = node.shadowRoot || node; + const children = node.localName === 'slot' ? slotChildren(node) + : (visible ? root.childNodes : root.children)[Symbol.iterator](); + stack.push({ children, visible, summaryOnly: node.localName === 'details' && !node.open }); + } + } + """# + + static let languageSample = visibleTextNodes + #""" + + let text = '', read = 0; + for (const node of visibleTextNodes(() => false)) { + const separator = text ? ' ' : ''; + const length = Math.min(node.length, maxCharacters - text.length - separator.length, maxRead - read); + if (length <= 0) break; + // Read only the needed prefix even when one node contains megabytes. + const part = node.substringData(0, length).trim(); + read += length; + if (/\p{L}/u.test(part)) text += separator + part; + if (text.length >= maxCharacters || read >= maxRead) break; + } + return { lang: (document.documentElement?.lang || '').slice(0, 64), text }; + """# + + static let translationCollect = visibleTextNodes + #""" + window.__earlyTranslation?.restore(); const entries = [], texts = []; window.__earlyTranslation = { runID, entries, restore() { @@ -165,56 +229,17 @@ extension WebViewManager { } entries.length = 0; }}; - const skipped = new Set(['head', 'script', 'style', 'noscript', 'template', 'textarea', 'input', 'select', 'option', - 'code', 'pre', 'kbd', 'samp', 'var', 'svg', 'math', 'iframe', 'object', 'embed', 'canvas', 'audio', 'video']); - let visited = 0, characters = 0; - function* slotChildren(slot) { - const host = slot.getRootNode().host; - if (!host || host.childNodes.length <= maxVisited - visited) { - const assigned = slot.assignedNodes(); - yield* (assigned.length ? assigned : slot.childNodes); - return; - } - // Avoid materializing an oversized assignment list. Charge the light - // children we inspect to the same traversal budget. - let found = false; - for (const child of host.childNodes) { - if (++visited >= maxVisited) return; - if (child.assignedSlot === slot) { found = true; yield child; } - } - if (!found) yield* slot.childNodes; - } - const stack = [{ children: document.childNodes.values(), visible: true }]; - while (stack.length && visited < maxVisited && entries.length < maxNodes && characters < maxCharacters) { - const level = stack[stack.length - 1], next = level.children.next(); - if (next.done) { stack.pop(); continue; } - const node = next.value; - visited++; - if (level.summaryOnly) { - if (node.localName !== 'summary') continue; - stack.pop(); // Only the first direct summary is rendered in closed details. - } - if (node.nodeType === Node.TEXT_NODE) { - if (!level.visible || node.length > maxCharacters) continue; - const original = node.data, text = original.trim(); - if (text.length <= maxCharacters - characters && /\p{L}/u.test(text)) { - entries.push({ node, parent: node.parentNode, original, written: null }); - texts.push(text); - characters += text.length; - } - continue; + let characters = 0; + const exclude = node => node.getAttribute('translate')?.toLowerCase() === 'no' || node.classList.contains('notranslate'); + for (const node of visibleTextNodes(exclude)) { + if (node.length > maxCharacters) continue; + const original = node.data, text = original.trim(); + if (text.length <= maxCharacters - characters && /\p{L}/u.test(text)) { + entries.push({ node, parent: node.parentNode, original, written: null }); + texts.push(text); + characters += text.length; + if (entries.length >= maxNodes || characters >= maxCharacters) break; } - if (node.nodeType !== Node.ELEMENT_NODE || skipped.has(node.localName) || node.hasAttribute('hidden') - || node.getAttribute('translate')?.toLowerCase() === 'no' || node.classList.contains('notranslate') - || node.isContentEditable) continue; - const style = getComputedStyle(node); - if (style.display === 'none' || style.contentVisibility === 'hidden' || style.opacity === '0') continue; - // Descendants can override inherited visibility. Their own styles decide. - const visible = style.visibility !== 'hidden' && style.visibility !== 'collapse'; - const root = node.shadowRoot || node; - const children = node.localName === 'slot' ? slotChildren(node) - : (visible ? root.childNodes : root.children)[Symbol.iterator](); - stack.push({ children, visible, summaryOnly: node.localName === 'details' && !node.open }); } return texts; """# diff --git a/Tests/EarlyWebTests/MediaControlTests.swift b/Tests/EarlyWebTests/MediaControlTests.swift index f7e860d..3a0d866 100644 --- a/Tests/EarlyWebTests/MediaControlTests.swift +++ b/Tests/EarlyWebTests/MediaControlTests.swift @@ -71,6 +71,54 @@ struct MediaControlTests { try await waitForState([false, true, false], in: view) } + @Test func overlappingAdditionsDiscoverPlayersOnceAndMuteInTheSameCheckpoint() async throws { + try await withPlaybackPage { manager, tab, page in + let view = page.view + #expect(manager.setMuted(true, for: tab.id)) + try await waitForState([true, true, true], in: view) + let scan = try #require(try await view.callAsyncJavaScript(""" + const query = Element.prototype.querySelectorAll; + let scans = 0, visits = 0; + Element.prototype.querySelectorAll = function(selector) { + const result = query.call(this, selector); + if (selector === 'audio,video') { scans++; visits += result.length; } + return result; + }; + const players = []; + try { + return await new Promise(resolve => { + const checkpoint = new MutationObserver(() => { + checkpoint.disconnect(); + resolve({scans, visits, muted: players.every(player => player.muted)}); + }); + checkpoint.observe(document.body, {childList:true, subtree:true}); + const root = document.body.appendChild(document.createElement('div')); + let branch = root; + for (let n = 0; n < 24; n++) branch = branch.appendChild(document.createElement('div')); + for (let n = 0; n < 100; n++) { + const player = document.createElement('audio'); + player.muted = n % 2 === 0; + players.push(player); + branch.append(player); + } + document.body.append(root); // The same subtree appears in more than one record. + globalThis.addedPlayers = players; + }); + } finally { Element.prototype.querySelectorAll = query; } + """, arguments: [:], in: nil, contentWorld: .defaultClient) as? [String: Any]) + let scans = try #require(scan["scans"] as? Int) + let visits = try #require(scan["visits"] as? Int) + #expect(scans == 1 && visits == 100, "Discovery performed \(scans) queries and visited \(visits) players") + #expect(scan["muted"] as? Bool == true) + #expect(manager.setMuted(false, for: tab.id)) + try await waitForState([false, true, false], in: view) + let restored = try await view.callAsyncJavaScript(""" + return addedPlayers.every((player, index) => player.muted === (index % 2 === 0)); + """, arguments: [:], in: nil, contentWorld: .defaultClient) + #expect(restored as? Bool == true) + } + } + @Test func playIntentIsNotActivityUntilPlaybackProgressesEvenInAnUnselectedView() async throws { try await withPlaybackPage { manager, tab, page in let view = page.view diff --git a/Tests/EarlyWebTests/PageFindTests.swift b/Tests/EarlyWebTests/PageFindTests.swift index fb573e1..f501769 100644 --- a/Tests/EarlyWebTests/PageFindTests.swift +++ b/Tests/EarlyWebTests/PageFindTests.swift @@ -3,6 +3,7 @@ @testable import EarlyWeb import Foundation import Testing +import WebKit /// Find in page against real WebKit documents in unshown views. @Suite(.serialized) @MainActor @@ -110,4 +111,155 @@ struct PageFindTests { #expect(state.matchCount == PageFindState.matchLimit && state.isCapped) #expect(state.query == "word") } + + @Test func visibilityChangesRefreshZeroAndExistingMatchesWithoutRetyping() async throws { + let fixture = PageToolFixture(pages: ["visibility": """ + +needle
+needle
+needle
+ """]) + defer { fixture.cleanup() } + let tab = try await fixture.open("visibility") + let manager = fixture.manager + manager.showFind(tab.id) + manager.updateFind(tab.id, query: "needle") + #expect(try await waitForAnswer(fixture, tab.id, "initially hidden").matchCount == 0) + + _ = try await fixture.evaluate("document.querySelector('#first').hidden = false", in: tab) + #expect(manager.findNext(tab.id)) + var state = try await waitForAnswer(fixture, tab.id, "revealed") + #expect(state.matchCount == 1 && state.currentIndex == 0) + + _ = try await fixture.evaluate(""" + document.querySelector('#second').className = ''; + document.querySelector('#third').style.visibility = 'visible'; + """, in: tab) + #expect(manager.findNext(tab.id)) + state = try await waitForAnswer(fixture, tab.id, "class and style") + #expect(state.matchCount == 3 && state.currentIndex == 1) + + _ = try await fixture.evaluate("document.querySelector('#second').setAttribute('data-hide', '')", in: tab) + #expect(manager.findNext(tab.id, backwards: true)) + state = try await waitForAnswer(fixture, tab.id, "previous after hiding current") + #expect(state.matchCount == 2 && state.currentIndex == 0) + + _ = try await fixture.evaluate("document.querySelector('#second').removeAttribute('data-hide')", in: tab) + #expect(manager.findNext(tab.id)) + state = try await waitForAnswer(fixture, tab.id, "revealed again") + #expect(state.matchCount == 3 && state.currentIndex == 1) + + // An in-place CSSOM change has no mutation record. Existing ranges + // still need to be checked before stepping. + _ = try await fixture.evaluate("document.styleSheets[0].insertRule('#second {display:none}')", in: tab) + #expect(manager.findNext(tab.id)) + state = try await waitForAnswer(fixture, tab.id, "CSSOM hid current") + #expect(state.matchCount == 2 && state.currentIndex == 1) + + _ = try await fixture.evaluate("document.styleSheets[0].deleteRule(0)", in: tab) + #expect(manager.findNext(tab.id, backwards: true)) + state = try await waitForAnswer(fixture, tab.id, "CSSOM revealed previous") + #expect(state.matchCount == 3 && state.currentIndex == 1) + } + + @Test func shadowTreeEditsRefreshHighlightsAndKeepDocumentOrder() async throws { + let fixture = PageToolFixture(pages: ["shadow": """ +needle
needle
+ + """]) + defer { fixture.cleanup() } + let tab = try await fixture.open("shadow") + let manager = fixture.manager, view = try fixture.page(tab).view + manager.showFind(tab.id) + manager.updateFind(tab.id, query: "needle") + #expect(try await waitForAnswer(fixture, tab.id, "shadow search").matchCount == 3) + #expect(manager.findNext(tab.id)) + #expect(try await waitForAnswer(fixture, tab.id, "selected shadow match").currentIndex == 1) + let painted = try await view.callAsyncJavaScript(""" + const root = document.querySelector('#host').shadowRoot; + const active = [...CSS.highlights.get('early-find-current')][0]; + return [active.startContainer.getRootNode() === root, + root.adoptedStyleSheets.some(sheet => sheet.cssRules[0].selectorText === '::highlight(early-find)')]; + """, arguments: [:], in: nil, contentWorld: WebViewManager.findWorld) + #expect(painted as? [Bool] == [true, true]) + + _ = try await fixture.evaluate("root.querySelector('#inside').className = 'concealed'", in: tab) + #expect(manager.findNext(tab.id)) + var state = try await waitForAnswer(fixture, tab.id, "step out of hidden shadow match") + #expect(state.matchCount == 2 && state.currentIndex == 1) + + _ = try await fixture.evaluate(""" + root.querySelector('#inside').className = ''; + root.querySelector('#inside').firstChild.data = 'changed'; + root.querySelector('#late').attachShadow({mode:'open'}).append('needle'); + """, in: tab) + #expect(manager.findNext(tab.id, backwards: true)) + state = try await waitForAnswer(fixture, tab.id, "nested match") + #expect(state.matchCount == 3 && state.currentIndex == 1) + _ = try await fixture.evaluate("root.querySelector('#late').shadowRoot.firstChild.remove()", in: tab) + #expect(manager.findNext(tab.id)) + state = try await waitForAnswer(fixture, tab.id, "removed shadow text") + #expect(state.matchCount == 2 && state.currentIndex == 1) + + // Attaching a root alone must also be noticed when the other matches stay visible. + _ = try await fixture.evaluate("root.querySelector('#inside').attachShadow({mode:'open'}).textContent = 'needle'", in: tab) + #expect(manager.findNext(tab.id, backwards: true)) + state = try await waitForAnswer(fixture, tab.id, "attached root") + #expect(state.matchCount == 3 && state.currentIndex == 1) + manager.hideFind(tab.id) + let cleaned = try await view.callAsyncJavaScript(""" + const root = document.querySelector('#host').shadowRoot; + return [CSS.highlights.has('early-find'), CSS.highlights.has('early-find-current'), + document.adoptedStyleSheets.length > 0, root.adoptedStyleSheets.length > 0]; + """, arguments: [:], in: nil, contentWorld: WebViewManager.findWorld) + #expect(cleaned as? [Bool] == [false, false, false, false]) + } + + @Test func findCoalescesMutationsAndReleasesItsObserverWhenThePageLeaves() async throws { + let fixture = PageToolFixture(pages: ["visibility": "needle
needle
"]) + defer { fixture.cleanup() } + let tab = try await fixture.open("visibility") + let view = try fixture.page(tab).view + let result = try await view.callAsyncJavaScript(""" + const observe = MutationObserver.prototype.observe; + const disconnect = MutationObserver.prototype.disconnect; + const observing = new Set(); + MutationObserver.prototype.observe = function(...args) { + observing.add(this); + return observe.apply(this, args); + }; + MutationObserver.prototype.disconnect = function() { + observing.delete(this); + return disconnect.call(this); + }; + const createWalker = document.createTreeWalker; + let scans = 0; + document.createTreeWalker = function(...args) { + scans++; + return createWalker.apply(this, args); + }; + try { + \(WebViewManager.findLibrary) + const find = window.__earlyFind, paragraph = document.querySelector('p'); + const before = find.update('needle', 0, 1000); + for (let n = 0; n < 5; n++) { + paragraph.hidden = !paragraph.hidden; + await Promise.resolve(); + } + const coalesced = scans === 1; + const after = find.step('needle', -1, 1000); + const refreshed = scans === 2 && after.count === 2; + window.dispatchEvent(new Event('pagehide')); + return [before.count === 1, coalesced, refreshed, observing.size === 0, !CSS.highlights.has('early-find')]; + } finally { + MutationObserver.prototype.observe = observe; + MutationObserver.prototype.disconnect = disconnect; + document.createTreeWalker = createWalker; + } + """, arguments: [:], in: nil, contentWorld: WebViewManager.findWorld) + #expect(result as? [Bool] == [true, true, true, true, true]) + } } diff --git a/Tests/EarlyWebTests/PageReaderTests.swift b/Tests/EarlyWebTests/PageReaderTests.swift index a079f6a..fe52b1e 100644 --- a/Tests/EarlyWebTests/PageReaderTests.swift +++ b/Tests/EarlyWebTests/PageReaderTests.swift @@ -78,6 +78,65 @@ struct PageReaderTests { #expect(try await fixture.evaluate("typeof Readability", in: tab) as? String == "undefined") } + @Test(arguments: ["elements", "depth", "attribute", "template"]) + func oversizedPagesAreRejectedBeforeCloningEvenAfterReaderWasOffered(_ growth: String) async throws { + let (fixture, tab) = try await readerFixture() + defer { fixture.cleanup() } + let manager = fixture.manager, view = try fixture.page(tab).view + var arguments: [String: Any] = WebViewManager.readerArguments + arguments["growth"] = growth + _ = try await view.callAsyncJavaScript(""" + const extra = document.body.appendChild(document.createElement('div')); + extra.id = 'extra'; + if (growth === 'elements') { + for (let n = 0; n <= maxElements; n++) extra.append(document.createElement('span')); + } else if (growth === 'depth') { + let parent = extra; + for (let n = 0; n <= maxDepth; n++) parent = parent.appendChild(document.createElement('span')); + } else if (growth === 'attribute') { + extra.setAttribute('data-large', 'a'.repeat(maxSourceCharacters + 1)); + } else { + const template = extra.appendChild(document.createElement('template')); + template.content.append(document.createComment('x'.repeat(maxSourceCharacters + 1))); + } + """, arguments: arguments, in: nil, contentWorld: WebViewManager.readerWorld) + _ = try await view.callAsyncJavaScript(""" + globalThis.readerClones = 0; + const clone = Node.prototype.cloneNode; + Node.prototype.cloneNode = function(deep) { + if (this === document) readerClones++; + return clone.call(this, deep); + }; + """, arguments: [:], in: nil, contentWorld: WebViewManager.readerWorld) + #expect(await !manager.showReader(tab.id, accent: accent)) + #expect(try await view.callAsyncJavaScript("return readerClones;", arguments: [:], in: nil, + contentWorld: WebViewManager.readerWorld) as? Int == 0) + #expect(manager.readerView(for: tab.id) == nil && view.url == fixture.url("article")) + #expect(try await fixture.evaluate("!!document.querySelector('#extra') && !!document.querySelector('article iframe')", in: tab) as? Bool == true) + } + + @Test func utf8LimitRejectsOversizedArticleHTMLBeforeReparsingIt() async throws { + let (fixture, tab) = try await readerFixture() + defer { fixture.cleanup() } + let view = try fixture.page(tab).view + let source = try #require(WebViewManager.readabilitySource) + let probe = try await view.callAsyncJavaScript(""" + document.querySelector('article').appendChild(document.createElement('p')).textContent = '字'.repeat(2200); + const parse = DOMParser.prototype.parseFromString; + let parses = 0; + DOMParser.prototype.parseFromString = function(...args) { + parses++; + return parse.apply(this, args); + }; + try { + const result = (() => { \(source)\n\(WebViewManager.readerExtraction) })(); + return [result === null, parses === 0]; + } finally { DOMParser.prototype.parseFromString = parse; } + """, arguments: WebViewManager.readerArguments.merging(["maxContentBytes": 6000]) { _, new in new }, + in: nil, contentWorld: WebViewManager.readerWorld) + #expect(probe as? [Bool] == [true, true], "The result fits in UTF-16 length but exceeds the UTF-8 byte cap") + } + @Test func readerSharesZoomAndFindAndLinksOrNavigationReturnToThePage() async throws { let (fixture, tab) = try await readerFixture() defer { fixture.cleanup() } diff --git a/Tests/EarlyWebTests/PageTranslationTests.swift b/Tests/EarlyWebTests/PageTranslationTests.swift index c75b2d9..ba1712f 100644 --- a/Tests/EarlyWebTests/PageTranslationTests.swift +++ b/Tests/EarlyWebTests/PageTranslationTests.swift @@ -37,6 +37,69 @@ struct PageTranslationTests { #expect(WebViewManager.dominantLanguage(text: "", hint: "not a language") == nil) } + @Test func languageSamplingReadsAVisiblePrefixWithoutReadingWholeTextNodes() async throws { + let fixture = PageToolFixture(pages: ["article": """ + + + + + """]) + defer { fixture.cleanup() } + let tab = try await fixture.open("article") + let page = try fixture.page(tab) + try await fixture.waitUntil("detected French") { page.language == "fr" } + let sample = try #require(try await page.view.callAsyncJavaScript(""" + const substringData = CharacterData.prototype.substringData; + let units = 0; + const longNodeReads = []; + CharacterData.prototype.substringData = function(offset, length) { + units += length; + if (this.length > 100000) longNodeReads.push(length); + return substringData.call(this, offset, length); + }; + try { + const sample = (() => { \(WebViewManager.languageSample) })(); + return { ...sample, units, longNodeReads }; + } finally { CharacterData.prototype.substringData = substringData; } + """, arguments: WebViewManager.languageSampleArguments, in: nil, contentWorld: WebViewManager.translationWorld) as? [String: Any]) + let text = try #require(sample["text"] as? String) + #expect(text.hasPrefix("La lecture doit rester simple")) + #expect(text.utf16.count <= 2_000 && sample["longNodeReads"] as? [Int] == [2_000]) + #expect((sample["units"] as? Int ?? .max) <= 8_000) + } + + @Test func languageSamplingStopsAtItsVisitBudgetAndKeepsTheLanguageHint() async throws { + let fixture = PageToolFixture(pages: ["deep": """ + + """]) + defer { fixture.cleanup() } + let tab = try await fixture.open("deep") + let page = try fixture.page(tab) + let budget = 64 + let arguments = WebViewManager.languageSampleArguments.merging(["maxVisited": budget]) { _, new in new } + let sample = try #require(try await page.view.callAsyncJavaScript(""" + const originalStyle = window.getComputedStyle; + let reads = 0; + window.getComputedStyle = element => { reads++; return originalStyle(element); }; + try { + const sample = (() => { \(WebViewManager.languageSample) })(); + return { ...sample, reads }; + } finally { window.getComputedStyle = originalStyle; } + """, arguments: arguments, in: nil, contentWorld: WebViewManager.translationWorld) as? [String: Any]) + let text = try #require(sample["text"] as? String) + let hint = try #require(sample["lang"] as? String) + #expect(text.isEmpty && hint == "de-DE") + #expect((sample["reads"] as? Int).map { $0 > 0 && $0 <= budget } == true) + #expect(WebViewManager.dominantLanguage(text: text, hint: hint) == "de") + } + @Test func translationReplacesOnlyReadableTextAndShowOriginalRestoresItExactly() async throws { let fixture = PageToolFixture(pages: ["french": Self.french]) defer { fixture.cleanup() } diff --git a/UITests/EarlyUITests.swift b/UITests/EarlyUITests.swift index aa86f26..b5f09bc 100644 --- a/UITests/EarlyUITests.swift +++ b/UITests/EarlyUITests.swift @@ -2664,21 +2664,30 @@ final class EarlyUITests: XCTestCase { func testFindBarCountsMatchesAndEscapeReturnsToThePage() { let app = launchFreshApp() - navigate(app, to: "early-test://fixture/one") - expectPage(app, "One") + navigate(app, to: "early-test://fixture/find") + expectPage(app, "Find") app.typeKey("f", modifierFlags: .command) let field = app.textFields["find.field"] XCTAssertTrue(field.waitForExistence(timeout: 5)) field.click() - app.typeText("page one") - let counted = app.staticTexts.matching(NSPredicate(format: "identifier == 'find.status' AND (label == %@ OR value == %@)", - "1 of 1", "1 of 1")).firstMatch - XCTAssertTrue(counted.waitForExistence(timeout: 5), app.staticTexts["find.status"].debugDescription) + app.typeText("needle") + func expectCount(_ count: String) { + let counted = app.staticTexts.matching(NSPredicate(format: "identifier == 'find.status' AND (label == %@ OR value == %@)", + count, count)).firstMatch + XCTAssertTrue(counted.waitForExistence(timeout: 5), app.staticTexts["find.status"].debugDescription) + } + expectCount("No matches") + app.webViews.buttons["Reveal matches"].click() + app.buttons["find.next"].click() + expectCount("1 of 2") + app.buttons["find.next"].click() + expectCount("2 of 2") + field.click() app.typeKey(.escape, modifierFlags: []) XCTAssertTrue(field.waitForNonExistence(timeout: 5)) // Closing never navigates, opens tabs or leaves the page unfocusable. expectRuntime(app, tabs: 1, views: 1, created: 1) - expectPage(app, "One") + expectPage(app, "Find") } func testHoveringALinkPreviewsItsAddressWithoutTakingTheClick() {