SPB Git

Repository Public

PageReading.swift 10.1 KB 196 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Core/Aura/PageReading.swift10// Module           : SPBrowser11// Repository       : https://git.spboucher.ai/sp-browser12// Created          : 2026-11-1913// Last Modified    : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreGraphics88import Foundation8990/// Scripts and models for reading a page, shared by the Mac and iOS engines. They run in the browser's isolated91/// content world and return plain JSON; nothing here modifies a page.92enum ReadingScripts {93    /// Extracts the readable part of an article as a flat list of text blocks. No HTML is carried over.94    static let reader = """95    (function () {96      const candidates = Array.from(document.querySelectorAll('article, main, [role=main], .post, .article, .entry-content, #content'));97      const score = (el) => Array.from(el.querySelectorAll('p')).reduce((n, p) => n + p.innerText.length, 0);98      let root = candidates.sort((a, b) => score(b) - score(a))[0];99      if (!root || score(root) < 400) { root = document.body; }100      if (!root) { return JSON.stringify({ title: document.title, blocks: [] }); }101      const blocks = [];102      const skip = 'nav, aside, footer, header, form, script, style, noscript, figure figcaption ~ *, [aria-hidden=true], .ad, .ads, .share, .social, .comments';103      root.querySelectorAll('h1, h2, h3, h4, p, li, blockquote, pre').forEach(el => {104        if (el.closest(skip)) { return; }105        if (el.tagName === 'LI' && el.querySelector('p, ul, ol')) { return; }106        if (el.tagName === 'P' && el.closest('li, blockquote')) { return; }107        const text = (el.tagName === 'PRE' ? el.textContent : el.innerText || '').trim();108        if (!text || (el.tagName === 'P' && text.length < 2)) { return; }109        const kind = { H1: 'h1', H2: 'h2', H3: 'h3', H4: 'h3', P: 'p', LI: 'li', BLOCKQUOTE: 'quote', PRE: 'pre' }[el.tagName];110        blocks.push({ kind: kind, text: text.slice(0, 20000) });111      });112      const byline = document.querySelector("[rel=author], .byline, .author, meta[name='author']");113      return JSON.stringify({ title: document.title, byline: byline ? (byline.content || byline.innerText || '').trim().slice(0, 200) : '',114                              blocks: blocks.slice(0, 2000) });115    })()116    """117118    /// Name of the message handler the bridge script posts to (isolated world only).119    static let bridgeName = "spbAura"120121    /// Reports, to the app only, the link under the pointer (address, rectangle, ⌥ state) and the reading progress.122    /// It reads the page; it never changes it. Events are throttled to one per animation frame.123    static let bridge = """124    (function () {125      if (window.__spbAura) { return; }126      window.__spbAura = true;127      const post = (m) => { try { webkit.messageHandlers.spbAura.postMessage(m); } catch (e) {} };128      let current = null, alt = false, queued = false, lastProgress = -1;129      const linkOf = (t) => { while (t && t !== document) { if (t.tagName === 'A' && t.href) { return t; } t = t.parentNode; } return null; };130      const report = () => {131        if (!current) { post({ t: 'hover', href: '' }); return; }132        const r = current.getBoundingClientRect();133        post({ t: 'hover', href: current.href, text: (current.innerText || current.getAttribute('aria-label') || '').trim().slice(0, 200),134               x: r.left, y: r.top, w: r.width, h: r.height, vw: window.innerWidth, vh: window.innerHeight, alt: alt });135      };136      document.addEventListener('mouseover', (e) => { const a = linkOf(e.target); if (a !== current) { current = a; alt = e.altKey; report(); } }, true);137      document.addEventListener('mouseleave', () => { if (current) { current = null; report(); } }, true);138      const key = (e) => { if (e.altKey !== alt) { alt = e.altKey; if (current) { report(); } } };139      document.addEventListener('keydown', key, true);140      document.addEventListener('keyup', key, true);141      document.addEventListener('mousedown', (e) => { const a = linkOf(e.target); if (a) { post({ t: 'press', href: a.href, x: e.clientX, y: e.clientY, vw: window.innerWidth, vh: window.innerHeight }); } }, true);142      const progress = () => {143        queued = false;144        const el = document.scrollingElement || document.documentElement;145        const max = Math.max(1, el.scrollHeight - window.innerHeight);146        const p = Math.max(0, Math.min(1, el.scrollTop / max));147        if (Math.abs(p - lastProgress) >= 0.004 || p === 0 || p === 1) { lastProgress = p; post({ t: 'scroll', p: p, y: el.scrollTop, tall: el.scrollHeight > window.innerHeight * 1.5 }); }148      };149      window.addEventListener('scroll', () => { if (!queued) { queued = true; requestAnimationFrame(progress); } }, { passive: true, capture: true });150      if (window === window.top) { setTimeout(progress, 300); }151    })()152    """153}154155struct ReaderArticle: Decodable, Equatable, Sendable {156    struct Block: Decodable, Equatable, Identifiable, Sendable {157        var kind: String158        var text: String159        var id: String { kind + String(text.hashValue) }160    }161    var title: String162    var byline: String?163    var blocks: [Block]164165    /// Reader view is offered only when there is enough running text to be worth it.166    var isReadable: Bool { blocks.filter { $0.kind == "p" }.reduce(0) { $0 + $1.text.count } >= 600 }167168    /// Approximate reading time in minutes at 230 words per minute (at least 1).169    var readingMinutes: Int {170        let words = blocks.reduce(0) { $0 + $1.text.split(whereSeparator: { $0 == " " || $0 == "\n" }).count }171        return max(1, Int((Double(words) / 230).rounded()))172    }173}174175/// A link reported by the page bridge: where it points and where it sits in the web view (unit coordinates, origin top-left).176struct HoveredLink: Equatable, Sendable {177    var url: URL178    var text: String179    /// Rectangle of the link in the visible viewport, each value in 0…1.180    var unitRect: CGRect181    var optionHeld: Bool182183    /// Decodes a bridge message; returns nil for anything that is not a well-formed http(s) link.184    static func parse(_ body: [String: Any]) -> HoveredLink? {185        guard let href = body["href"] as? String, !href.isEmpty, href.count < 4000, let url = URL(string: href),186              let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }187        func number(_ key: String) -> Double { (body[key] as? NSNumber)?.doubleValue ?? 0 }188        let vw = max(number("vw"), 1), vh = max(number("vh"), 1)189        let w = body["w"] == nil ? 0 : number("w"), h = body["h"] == nil ? 0 : number("h")190        let rect = CGRect(x: clamp(number("x") / vw), y: clamp(number("y") / vh), width: clamp(w / vw), height: clamp(h / vh))191        return HoveredLink(url: url, text: String((body["text"] as? String ?? "").prefix(200)), unitRect: rect, optionHeld: (body["alt"] as? Bool) ?? false)192    }193194    private static func clamp(_ v: Double) -> Double { min(max(v.isFinite ? v : 0, 0), 1) }195}196
Files main
Menu

Theme