// HV leaf spike, the native half. JavaScriptCore runs js/app.js; its renderer sends batches of ops // (create / prop / insert) that this file applies to real UIKit views. Focus belongs to the tvOS focus // engine (no JS key routing): rails are UICollectionViews whose cells are focusable and recycled; the // focused poster gets Apple's parallax through UIImageView.adjustsImageWhenAncestorFocused, the way // react-native-tvos's RCTViewComponentView does it for its focusable views (design reference, MIT). // // Every measurement goes to Documents/spike.log as one line: the harness reads it back. import UIKit import JavaScriptCore // MARK: - log enum Log { static let url: URL = { let d = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] return d.appendingPathComponent("spike.log") }() static let t0 = CACurrentMediaTime() static func line(_ s: String) { let ms = String(format: "%.1f", (CACurrentMediaTime() - t0) * 1000) let text = "[\(ms)ms] \(s)\n" print(text, terminator: "") if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(text.data(using: .utf8)!); try? h.close() } else { try? text.data(using: .utf8)!.write(to: url) } } } // MARK: - colour func color(_ s: String) -> UIColor { if s.hasPrefix("#"), s.count == 7, let v = UInt32(s.dropFirst(), radix: 16) { return UIColor(red: CGFloat(v >> 16 & 0xff) / 255, green: CGFloat(v >> 8 & 0xff) / 255, blue: CGFloat(v & 0xff) / 255, alpha: 1) } if s.hasPrefix("hsl("), let inner = s.dropFirst(4).split(separator: ")").first { let p = inner.split(separator: ",").map { Double($0.trimmingCharacters(in: CharacterSet(charactersIn: " %"))) ?? 0 } let (h, sat, l) = (p[0] / 360, p[1] / 100, p[2] / 100) let b = l + sat * min(l, 1 - l), sv = b == 0 ? 0 : 2 * (1 - l / b) return UIColor(hue: h, saturation: sv, brightness: b, alpha: 1) } return .magenta } // MARK: - the rail: a recycled, focusable collection struct Item { let id: String; let title: String; let color: UIColor } final class PosterCell: UICollectionViewCell { let poster = UIImageView() let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) poster.adjustsImageWhenAncestorFocused = true // Apple's lift, parallax and glare poster.clipsToBounds = false contentView.addSubview(poster) label.font = .systemFont(ofSize: 26, weight: .medium) label.textColor = .white label.textAlignment = .center contentView.addSubview(label) isAccessibilityElement = true } required init?(coder: NSCoder) { fatalError() } static var cache: [String: UIImage] = [:] func bind(_ it: Item, size: CGSize) { poster.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height - 50) label.frame = CGRect(x: 0, y: size.height - 44, width: size.width, height: 40) let key = it.id if let img = PosterCell.cache[key] { poster.image = img } else { let r = UIGraphicsImageRenderer(size: poster.bounds.size) let img = r.image { c in it.color.setFill(); c.fill(CGRect(origin: .zero, size: poster.bounds.size)) } PosterCell.cache[key] = img poster.image = img } label.text = it.title accessibilityLabel = it.title } } final class RailView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { var items: [Item] = [] { didSet { collection.reloadData() } } var itemSize = CGSize(width: 300, height: 220) var onFocus: ((Int) -> Void)? var onSelect: ((Int) -> Void)? let title = UILabel() lazy var collection: UICollectionView = { let l = UICollectionViewFlowLayout() l.scrollDirection = .horizontal l.minimumLineSpacing = 48 let c = UICollectionView(frame: .zero, collectionViewLayout: l) c.register(PosterCell.self, forCellWithReuseIdentifier: "p") c.dataSource = self c.delegate = self c.clipsToBounds = false c.contentInset = UIEdgeInsets(top: 0, left: 90, bottom: 0, right: 90) c.backgroundColor = .clear c.remembersLastFocusedIndexPath = true return c }() static var created = 0 override init(frame: CGRect) { super.init(frame: frame) title.font = .systemFont(ofSize: 34, weight: .semibold) title.textColor = UIColor(white: 0.85, alpha: 1) addSubview(title) addSubview(collection) } required init?(coder: NSCoder) { fatalError() } override func layoutSubviews() { super.layoutSubviews() title.frame = CGRect(x: 90, y: 0, width: bounds.width - 180, height: 50) collection.frame = CGRect(x: 0, y: 64, width: bounds.width, height: bounds.height - 64) (collection.collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = itemSize } func collectionView(_ c: UICollectionView, numberOfItemsInSection s: Int) -> Int { items.count } func collectionView(_ c: UICollectionView, cellForItemAt i: IndexPath) -> UICollectionViewCell { let cell = c.dequeueReusableCell(withReuseIdentifier: "p", for: i) as! PosterCell if cell.tag == 0 { RailView.created += 1; cell.tag = 1 } cell.bind(items[i.item], size: itemSize) return cell } func collectionView(_ c: UICollectionView, didUpdateFocusIn ctx: UICollectionViewFocusUpdateContext, with co: UIFocusAnimationCoordinator) { if let i = ctx.nextFocusedIndexPath { onFocus?(i.item) } } func collectionView(_ c: UICollectionView, didSelectItemAt i: IndexPath) { onSelect?(i.item) } } // MARK: - the renderer: ops → views final class Renderer { var views: [Int: UIView] = [0: UIView()] var kinds: [Int: String] = [:] var railItems: [Int: [[String: Any]]] = [:] let js: JSContext var applied = 0, batches = 0, maxBatchMs = 0.0, totalMs = 0.0 init(root: UIView, js: JSContext) { views[0] = root; self.js = js } func apply(_ json: String) { let t = CACurrentMediaTime() guard let ops = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [[Any]] else { return } for op in ops { switch op[0] as! String { case "c": let id = op[1] as! Int, kind = op[2] as! String let v: UIView switch kind { case "text": let l = UILabel(); l.numberOfLines = 1; v = l case "scroll": let s = UIScrollView(); s.clipsToBounds = false; v = s case "rail": let r = RailView(); bindRail(r, id: id); v = r default: v = UIView() } views[id] = v; kinds[id] = kind case "p": setProp(op[1] as! Int, op[2] as! String, op[3]) case "i": guard let parent = views[op[1] as! Int], let child = views[op[2] as! Int] else { continue } parent.addSubview(child) if let s = parent as? UIScrollView { s.contentSize = CGSize(width: s.bounds.width, height: max(s.contentSize.height, child.frame.maxY)) } default: break } applied += 1 } let ms = (CACurrentMediaTime() - t) * 1000 batches += 1; totalMs += ms; maxBatchMs = max(maxBatchMs, ms) Log.line(String(format: "batch ops=%d apply=%.2fms", ops.count, ms)) } func setProp(_ id: Int, _ name: String, _ value: Any) { guard let v = views[id] else { return } let n = (value as? NSNumber).map { CGFloat($0.doubleValue) } switch name { case "x": v.frame.origin.x = n ?? 0 case "y": v.frame.origin.y = n ?? 0 case "width": v.frame.size.width = n ?? 0 case "height": v.frame.size.height = n ?? 0 case "color": if let l = v as? UILabel { l.textColor = color(value as! String) } else { v.backgroundColor = color(value as! String) } case "text": (v as? UILabel)?.text = value as? String case "fontSize": (v as? UILabel)?.font = .systemFont(ofSize: n ?? 17, weight: .bold) case "title": (v as? RailView)?.title.text = value as? String case "itemWidth": (v as? RailView)?.itemSize.width = n ?? 300 case "itemHeight": (v as? RailView)?.itemSize.height = n ?? 220 case "items": let raw = value as? [[String: Any]] ?? [] railItems[id] = raw (v as? RailView)?.items = raw.map { Item(id: $0["id"] as! String, title: $0["title"] as! String, color: color($0["color"] as! String)) } default: break } } func bindRail(_ r: RailView, id: Int) { r.onFocus = { [weak self] i in guard let self, let it = self.railItems[id]?[i] else { return } let t = CACurrentMediaTime() self.js.objectForKeyedSubscript("__event").call(withArguments: [id, "onFocusItem", it]) Log.line(String(format: "focus %@ js+apply=%.2fms", it["id"] as! String, (CACurrentMediaTime() - t) * 1000)) } r.onSelect = { [weak self] i in guard let self, let it = self.railItems[id]?[i] else { return } self.js.objectForKeyedSubscript("__event").call(withArguments: [id, "onSelectItem", it]) } } } // MARK: - frame hitches: a display link counting frames that missed their deadline final class Hitches: NSObject { var link: CADisplayLink? var last: CFTimeInterval = 0, frames = 0, late = 0, worst = 0.0 func start() { link = CADisplayLink(target: self, selector: #selector(tick(_:))); link?.add(to: .main, forMode: .common) } @objc func tick(_ l: CADisplayLink) { if last > 0 { let dt = (l.timestamp - last) * 1000, budget = (l.targetTimestamp - l.timestamp) * 1000 frames += 1 if dt > budget * 1.5 { late += 1 } worst = max(worst, dt) } last = l.timestamp } func report(_ tag: String) { Log.line(String(format: "frames %@ total=%d late=%d worst=%.1fms", tag, frames, late, worst)) frames = 0; late = 0; worst = 0 } } // MARK: - app final class RootVC: UIViewController { var renderer: Renderer! let js = JSContext()! let hitches = Hitches() override func viewDidLoad() { super.viewDidLoad() try? FileManager.default.removeItem(at: Log.url) view.backgroundColor = .black js.exceptionHandler = { _, e in Log.line("JS error: \(e?.toString() ?? "?")") } renderer = Renderer(root: view, js: js) let native = JSValue(newObjectIn: js)! let apply: @convention(block) (String) -> Void = { [weak self] s in self?.renderer.apply(s) } let log: @convention(block) (String) -> Void = { s in Log.line("js: \(s)") } native.setObject(apply, forKeyedSubscript: "apply" as NSString) native.setObject(log, forKeyedSubscript: "log" as NSString) js.setObject(native, forKeyedSubscript: "__native" as NSString) let src = try! String(contentsOf: Bundle.main.url(forResource: "app", withExtension: "js")!, encoding: .utf8) let t = CACurrentMediaTime() js.evaluateScript(src) Log.line(String(format: "mount total (js eval + apply) = %.1fms, views=%d", (CACurrentMediaTime() - t) * 1000, renderer.views.count)) hitches.start() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Log.line(String(format: "first appear; cells created so far=%d", RailView.created)) DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [self] in hitches.report("idle") let mem = Self.residentMB() Log.line(String(format: "memory resident=%.1fMB", mem)) } // The scripted walk: a remote has no injection API in simctl, so the app asks the focus engine to move // to each target in turn (setNeedsFocusUpdate on a preferred environment), the path a remote press takes // through the same engine. 6 rails x 19 steps right, then down to the next rail. DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [self] in walk(rail: 0, item: 0) } Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [self] _ in hitches.report("window") Log.line(String(format: "stats batches=%d ops=%d maxBatch=%.2fms cellsCreated=%d mem=%.1fMB", renderer.batches, renderer.applied, renderer.maxBatchMs, RailView.created, Self.residentMB())) } } var focusTarget: UIFocusEnvironment? override var preferredFocusEnvironments: [UIFocusEnvironment] { focusTarget.map { [$0] } ?? super.preferredFocusEnvironments } lazy var rails: [RailView] = renderer.views.values.compactMap { $0 as? RailView }.sorted { $0.frame.minY < $1.frame.minY } var walkStart = 0.0, steps = 0, misses = 0 func walk(rail: Int, item: Int) { if rail == 0 && item == 0 { walkStart = CACurrentMediaTime(); hitches.report("before-walk") } guard rail < rails.count else { let s = CACurrentMediaTime() - walkStart hitches.report("walk") Log.line(String(format: "walk done steps=%d misses=%d in %.2fs cellsCreated=%d mem=%.1fMB", steps, misses, s, RailView.created, Self.residentMB())) // E6: what VoiceOver would read: every visible cell exposes its title as an accessibility element. let cells = rails.flatMap { $0.collection.visibleCells } let labelled = cells.filter { $0.isAccessibilityElement && !($0.accessibilityLabel ?? "").isEmpty }.count let bengali = cells.compactMap { $0.accessibilityLabel }.filter { $0.unicodeScalars.contains { (0x0980...0x09FF).contains($0.value) } }.count Log.line("a11y visibleCells=\(cells.count) labelled=\(labelled) bengaliLabels=\(bengali)") Log.line("SPIKE-DONE") return } let r = rails[rail] let scroller = r.superview as? UIScrollView scroller?.scrollRectToVisible(r.frame, animated: false) r.collection.scrollToItem(at: IndexPath(item: item, section: 0), at: .centeredHorizontally, animated: false) r.collection.layoutIfNeeded() if let cell = r.collection.cellForItem(at: IndexPath(item: item, section: 0)) { focusTarget = cell setNeedsFocusUpdate(); updateFocusIfNeeded() let focused = UIFocusSystem.focusSystem(for: view)?.focusedItem as? UIView if focused !== cell && focused?.isDescendant(of: cell) != true { misses += 1 } } else { misses += 1 } steps += 1 let next = item + 1 < r.items.count ? (rail, item + 1) : (rail + 1, 0) DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) { [self] in walk(rail: next.0, item: next.1) } } static func residentMB() -> Double { var info = mach_task_basic_info(); var count = mach_msg_type_number_t(MemoryLayout.size / 4) let kr = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } } return kr == KERN_SUCCESS ? Double(info.resident_size) / 1_048_576 : -1 } } // tvOS 27 traps an app without UIScene lifecycle adoption at launch // (UIApplicationEvaluateRuntimeIssueForNoSceneLifecycleAdoption), so the window comes from a scene delegate. @main final class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ a: UIApplication, configurationForConnecting s: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { let c = UISceneConfiguration(name: "main", sessionRole: s.role) c.delegateClass = SceneDelegate.self return c } } final class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo s: UISceneSession, options: UIScene.ConnectionOptions) { guard let ws = scene as? UIWindowScene else { return } window = UIWindow(windowScene: ws) window?.rootViewController = RootVC() window?.makeKeyAndVisible() } }