Lightpanda: the headless browser designed for AI and automation
webapi: improve animation
Karl Seguine81ebc10669f
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 36b937cf6..926365a00 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -32,6 +32,7 @@ const Performance = @import("webapi/Performance.zig");const Screen = @import("webapi/Screen.zig");const EventTarget = @import("webapi/EventTarget.zig");const MediaQueryList = @import("webapi/css/MediaQueryList.zig");+const Animation = @import("webapi/animation/Animation.zig");const XMLHttpRequestEventTarget = @import("webapi/net/XMLHttpRequestEventTarget.zig");const log = lp.log;@@ -91,6 +92,7 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) Dispat.node => try self.dispatchNode(target.subtype(Node), event),.xhr => try self.dispatchDirect(target, event, target.subtype(XMLHttpRequestEventTarget).inlineHandler(event._type_string), .{ .context = "dispatch" }),.media_query_list => try self.dispatchDirect(target, event, target.subtype(MediaQueryList).inlineHandler(event._type_string), .{ .context = "dispatch" }),+ .animation => try self.dispatchDirect(target, event, target.subtype(Animation).inlineHandler(event._type_string), .{ .context = "dispatch" }),.performance => try self.dispatchDirect(target, event, target.subtype(Performance).inlineHandler(event._type_string), .{ .context = "dispatch" }),.screen_orientation => try self.dispatchDirect(target, event, target.subtype(Screen.Orientation).inlineHandler(event._type_string), .{ .context = "dispatch" }),.window => try self.dispatchDirect(target, event, windowInlineHandler(target.subtype(Window), event._type_string), .{ .context = "dispatch" }),diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 964c76a9a..1507246aa 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1223,6 +1223,7 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/event/PopStateEvent.zig"),@import("../webapi/event/HashChangeEvent.zig"),@import("../webapi/event/MediaQueryListEvent.zig"),+ @import("../webapi/event/AnimationPlaybackEvent.zig"),@import("../webapi/event/BeforeUnloadEvent.zig"),@import("../webapi/event/StorageEvent.zig"),@import("../webapi/event/DeviceMotionEvent.zig"),diff --git a/src/browser/tests/animation/animation.html b/src/browser/tests/animation/animation.htmlindex 9851e8051..bbbb7965d 100644--- a/src/browser/tests/animation/animation.html+++ b/src/browser/tests/animation/animation.html@@ -1,12 +1,24 @@<!DOCTYPE html><script src="../testing.js"></script>+<!--+ Animations are faked: keyframes and timing are ignored and a running+ animation finishes ~10ms after play(). Tests pass an explicit duration so+ they behave the same in a real browser.+-->+<script>+ function newAnimation(duration = 50) {+ return document.createElement('div').animate(null, { duration });+ }+</script>+<script id=animation type=module>{const state = await testing.async();- let a1 = document.createElement('div').animate(null, null);- testing.expectEqual('idle', a1.playState);+ // animate() plays the animation.+ let a1 = newAnimation();+ testing.expectEqual('running', a1.playState);let cb = [];a1.finished.then((x) => {@@ -15,21 +27,16 @@state.resolve();});- a1.ready.then(() => {- cb.push(a1.playState);- a1.play();- cb.push(a1.playState);- });-await state.done(() => {- testing.expectEqual(['idle', 'running', 'finished', true], cb);+ testing.expectEqual(['finished', true], cb);});}</script><script id=startTime>- let a2 = document.createElement('div').animate(null, null);- // startTime defaults to null+ let a2 = newAnimation();+ a2.cancel();+ // startTime is null once cancelledtesting.expectEqual(null, a2.startTime);// startTime is settablea2.startTime = 42.5;@@ -42,17 +49,15 @@<script id=onfinish type=module>{const state = await testing.async();- let a3 = document.createElement('div').animate(null, null);+ let a3 = newAnimation();// onfinish defaults to nulltesting.expectEqual(null, a3.onfinish);let calls = [];- // onfinish callback should be scheduled and called asynchronouslya3.onfinish = function() {calls.push('finish');state.resolve();};- a3.play();await state.done(() => {testing.expectEqual(['finish'], calls);@@ -64,22 +69,21 @@{const state = await testing.async();- let a4 = document.createElement('div').animate(null, null);+ let a4 = newAnimation(1000);let cb4 = [];- a4.finished.then((x) => {- cb4.push(a4.playState)+ a4.finished.then(() => {+ cb4.push('finished');state.resolve();});a4.ready.then(() => {- a4.play();cb4.push(a4.playState)a4.pause();cb4.push(a4.playState)- // should not called finished! Let's wait a bit to see+ // should not resolve finished! Let's wait a bit to seesetTimeout(() => {state.resolve();- }, 10)+ }, 30)});await state.done(() => {testing.expectEqual(['running', 'paused'], cb4);@@ -90,22 +94,129 @@<script id=finish type=module>{const state = await testing.async();- let a5 = document.createElement('div').animate(null, null);- testing.expectEqual('idle', a5.playState);+ let a5 = newAnimation(1000);let cb5 = [];- a5.finished.then((x) => {+ a5.finished.then(() => {cb5.push(a5.playState)state.resolve();});- a5.ready.then(() => {- cb5.push(a5.playState);- a5.play();+ a5.finish();+ cb5.push(a5.playState);++ await state.done(() => {+ testing.expectEqual(['finished', 'finished'], cb5)+ });+ }+</script>++<script id=event_target>+ {+ const a = newAnimation();+ testing.expectEqual(true, a instanceof EventTarget);+ testing.expectEqual('function', typeof a.addEventListener);+ testing.expectEqual('function', typeof a.removeEventListener);+ testing.expectEqual('[object Animation]', Object.prototype.toString.call(a));+ testing.expectEqual(null, a.oncancel);+ }+</script>++<script id=finish_event type=module>+ {+ const state = await testing.async();+ const a = newAnimation();++ let calls = [];+ const removed = () => calls.push('removed');+ a.addEventListener('finish', removed);+ a.removeEventListener('finish', removed);+ a.onfinish = function(e) {+ calls.push(['onfinish', this === a, e.type]);+ };+ a.addEventListener('finish', (e) => {+ calls.push(['listener', e.target === a, e instanceof AnimationPlaybackEvent, e.isTrusted]);+ state.resolve();+ });++ await state.done(() => {+ testing.expectEqual([+ ['onfinish', true, 'finish'],+ ['listener', true, true, true],+ ], calls);+ });+ }+</script>++<script id=finish_method_event type=module>+ {+ const state = await testing.async();+ const a = newAnimation(1000);+ let calls = [];+ a.addEventListener('finish', (e) => {+ calls.push(e.type);+ setTimeout(() => state.resolve(), 30);+ });+ a.finish();+ a.finish();+ // queued, not dispatched inline+ testing.expectEqual([], calls);++ await state.done(() => {+ testing.expectEqual(['finish'], calls);+ });+ }+</script>++<script id=cancel_event type=module>+ {+ const state = await testing.async();+ const a = newAnimation(1000);+ let calls = [];+ a.oncancel = (e) => calls.push('oncancel:' + e.type);+ a.addEventListener('cancel', (e) => {+ calls.push('listener:' + e.type);+ // cancelling an idle animation doesn't queue another event+ a.cancel();+ setTimeout(() => state.resolve(), 30);});+ const first = a.finished;+ first.catch((e) => calls.push('rejected:' + e.name));++ a.cancel();+ testing.expectEqual('idle', a.playState);+ // queued, not dispatched inline+ testing.expectEqual([], calls);+ // the rejected promise is replaced+ testing.expectEqual(false, first === a.finished);+await state.done(() => {- testing.expectEqual(['idle', 'finished'], cb5)+ testing.expectEqual(['rejected:AbortError', 'oncancel:cancel', 'listener:cancel'], calls);});}</script>++<script id=dispatch_event>+ {+ const a = newAnimation();+ let calls = [];+ a.onfinish = (e) => calls.push(e.isTrusted);+ a.dispatchEvent(new AnimationPlaybackEvent('finish'));+ testing.expectEqual([false], calls);+ }+</script>++<script id=playback_event>+ {+ const e = new AnimationPlaybackEvent('finish', { currentTime: 100, timelineTime: 250.5 });+ testing.expectEqual('finish', e.type);+ testing.expectEqual(100, e.currentTime);+ testing.expectEqual(250.5, e.timelineTime);+ testing.expectEqual(true, e instanceof Event);++ const d = new AnimationPlaybackEvent('cancel');+ testing.expectEqual(null, d.currentTime);+ testing.expectEqual(null, d.timelineTime);+ }+</script>diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex e2e1007b7..23dd63d88 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -1496,7 +1496,9 @@ pub fn getAnimations(_: *const Element) []*Animation {}pub fn animate(_: *Element, _: ?js.Object, _: ?js.Object, frame: *Frame) !*Animation {- return Animation.init(frame);+ const animation = try Animation.init(frame);+ try animation.play(frame);+ return animation;}pub fn closest(self: *Element, input: []const u8, frame: *Frame) !?*Element {diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zigindex cd15525b8..02403626a 100644--- a/src/browser/webapi/Event.zig+++ b/src/browser/webapi/Event.zig@@ -89,6 +89,7 @@ pub const Type = union(enum) {pop_state_event: *@import("event/PopStateEvent.zig"),hash_change_event: *@import("event/HashChangeEvent.zig"),media_query_list_event: *@import("event/MediaQueryListEvent.zig"),+ animation_playback_event: *@import("event/AnimationPlaybackEvent.zig"),before_unload_event: *@import("event/BeforeUnloadEvent.zig"),storage_event: *@import("event/StorageEvent.zig"),device_motion_event: *@import("event/DeviceMotionEvent.zig"),@@ -206,6 +207,7 @@ pub fn is(self: *Event, comptime T: type) ?*T {.pop_state_event => |e| return if (T == @import("event/PopStateEvent.zig")) e else null,.hash_change_event => |e| return if (T == @import("event/HashChangeEvent.zig")) e else null,.media_query_list_event => |e| return if (T == @import("event/MediaQueryListEvent.zig")) e else null,+ .animation_playback_event => |e| return if (T == @import("event/AnimationPlaybackEvent.zig")) e else null,.before_unload_event => |e| return if (T == @import("event/BeforeUnloadEvent.zig")) e else null,.storage_event => |e| return if (T == @import("event/StorageEvent.zig")) e else null,.device_motion_event => |e| return if (T == @import("event/DeviceMotionEvent.zig")) e else null,diff --git a/src/browser/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zigindex 905b6557e..3bec233c4 100644--- a/src/browser/webapi/EventTarget.zig+++ b/src/browser/webapi/EventTarget.zig@@ -54,6 +54,8 @@ const MediaQueryList = @import("css/MediaQueryList.zig");const TextTrackCue = @import("media/TextTrackCue.zig");+const Animation = @import("animation/Animation.zig");+const Navigation = @import("navigation/Navigation.zig");const NavigationHistoryEntry = @import("navigation/NavigationHistoryEntry.zig");const XMLHttpRequestEventTarget = @import("net/XMLHttpRequestEventTarget.zig");@@ -72,6 +74,7 @@ _type: Type align(8),pub const Type = enum(u8) {abort_signal,+ animation,broadcast_channel,cookie_store,event_source,@@ -108,6 +111,7 @@ pub const Type = enum(u8) {pub fn Subtype(comptime tag: Type) type {return switch (tag) {.abort_signal => AbortSignal,+ .animation => Animation,.broadcast_channel => BroadcastChannel,.cookie_store => CookieStore,.event_source => EventSource,@@ -328,6 +332,7 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {.worker_global_scope => writer.writeAll("<WorkerGlobalScope>"),.xhr => writer.writeAll("<XMLHttpRequestEventTarget>"),.abort_signal => writer.writeAll("<AbortSignal>"),+ .animation => writer.writeAll("<Animation>"),.media_query_list => writer.writeAll("<MediaQueryList>"),.message_port => writer.writeAll("<MessagePort>"),.broadcast_channel => writer.writeAll("<BroadcastChannel>"),@@ -352,6 +357,7 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {pub fn toString(self: *EventTarget) []const u8 {return switch (self._type) {.abort_signal => return "[object AbortSignal]",+ .animation => return "[object Animation]",.broadcast_channel => return "[object BroadcastChannel]",.cookie_store => return "[object CookieStore]",.event_source => return "[object EventSource]",diff --git a/src/browser/webapi/animation/Animation.zig b/src/browser/webapi/animation/Animation.zigindex be4ab00ce..cf1c26fd4 100644--- a/src/browser/webapi/animation/Animation.zig+++ b/src/browser/webapi/animation/Animation.zig@@ -17,14 +17,20 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const lp = @import("lightpanda");+const js = @import("../../js/js.zig");const Page = @import("../../Page.zig");const Frame = @import("../../Frame.zig");+const EventTarget = @import("../EventTarget.zig");+const AnimationPlaybackEvent = @import("../event/AnimationPlaybackEvent.zig");+const log = lp.log;const Animation = @This();+pub const Proto = EventTarget;+const PlayState = enum {idle,running,@@ -33,6 +39,7 @@ const PlayState = enum {};_rc: lp.RC = .{},+_proto: *EventTarget,_frame: *Frame,_arena: *lp.Arena,@@ -42,6 +49,7 @@ _ready_resolver: ?js.PromiseResolver.Global = null,_finished_resolver: ?js.PromiseResolver.Global = null,_startTime: ?f64 = null,_onFinish: ?js.Function.Global = null,+_onCancel: ?js.Function.Global = null,_playState: PlayState = .idle,// Fake the animation by passing the states:@@ -53,13 +61,11 @@ pub fn init(frame: *Frame) !*Animation {const arena = try frame.getArena(.tiny, "Animation");errdefer arena.release();- const self = try arena.create(Animation);- self.* = .{+ return frame._factory.eventTargetWithAllocator(arena.allocator(), Animation{+ ._proto = undefined,._frame = frame,._arena = arena,- };-- return self;+ });}pub fn deinit(self: *Animation, _: *Page) void {@@ -74,6 +80,10 @@ pub fn acquireRef(self: *Animation) void {self._rc.acquire();}+pub fn asEventTarget(self: *Animation) *EventTarget {+ return self._proto;+}+pub fn play(self: *Animation, frame: *Frame) !void {if (self._playState == .running) {return;@@ -93,8 +103,7 @@ pub fn play(self: *Animation, frame: *Frame) !void {);}-// The scheduler drops pending tasks when the context is torn down. `update`-// and `cancelled` are mutually exclusive, so play()'s ref is released once.+// The scheduler drops pending tasks when the context is torn down.fn cancelled(ctx: *anyopaque) void {const self: *Animation = @ptrCast(@alignCast(ctx));self.releaseRef(self._frame.page);@@ -104,14 +113,28 @@ pub fn pause(self: *Animation) void {self._playState = .paused;}-pub fn cancel(self: *Animation) void {+pub fn cancel(self: *Animation, frame: *Frame) !void {+ if (self._playState == .idle) {+ return;+ }// Transition to idle. If the animation was .running, the already-scheduled// update() callback will fire but see .idle state, skip the finish// transition, and release the strong ref via weakRef() as normal.self._playState = .idle;++ if (self._finished_resolver) |global| {+ // reject the current finished promised+ self._finished_resolver = null;+ defer global.release();+ const resolver = frame.js.local.?.toLocal(global);+ // prevent it from reporting as unhandled+ resolver.promise().markAsHandled();+ resolver.rejectError("Animation.cancel", .{ .dom_exception = .{ .err = error.AbortError } });+ }+ return self.queuePlaybackEvent(.cancel);}-pub fn finish(self: *Animation, frame: *Frame) void {+pub fn finish(self: *Animation, frame: *Frame) !void {if (self._playState == .finished) {return;}@@ -122,12 +145,47 @@ pub fn finish(self: *Animation, frame: *Frame) void {if (self._finished_resolver) |resolver| {frame.js.local.?.toLocal(resolver).resolve("Animation.getFinished", self);}- // call onfinish- if (self._onFinish) |func| {- frame.js.local.?.toLocal(func).call(void, .{}) catch |err| {- log.debug(.js, "Animation._onFinish", .{ .err = err });- };+ return self.queuePlaybackEvent(.finish);+}++const PlaybackEventType = enum { finish, cancel };++fn queuePlaybackEvent(self: *Animation, comptime typ: PlaybackEventType) !void {+ self.acquireRef();+ errdefer self.releaseRef(self._frame.page);+ try self._frame.js.scheduler.add(self, struct {+ fn run(ctx: *anyopaque) !?u32 {+ const animation: *Animation = @ptrCast(@alignCast(ctx));+ defer animation.releaseRef(animation._frame.page);+ const handler = switch (typ) {+ .finish => animation._onFinish,+ .cancel => animation._onCancel,+ };+ try animation.dispatchPlaybackEvent(comptime .wrap(@tagName(typ)), handler);+ return null;+ }+ }.run, 0, .{ .name = "animation." ++ @tagName(typ), .finalizer = Animation.cancelled });+}++fn dispatchPlaybackEvent(self: *Animation, typ: lp.String, handler: ?js.Function.Global) !void {+ const frame = self._frame;+ const target = self.asEventTarget();+ if (frame.hasDirectListeners(target, typ.str(), handler) == false) {+ return;+ }+ const event = try AnimationPlaybackEvent.initTrusted(typ, null, frame);+ return frame.dispatch(target, event.asEvent(), handler, .{ .context = "Animation" });+}++// The property handler for a JS-side dispatchEvent (see EventManager.dispatch).+pub fn inlineHandler(self: *const Animation, typ: lp.String) ?js.Function.Global {+ if (typ.eql(comptime .wrap("finish"))) {+ return self._onFinish;}+ if (typ.eql(comptime .wrap("cancel"))) {+ return self._onCancel;+ }+ return null;}pub fn reverse(_: *Animation) void {@@ -192,6 +250,7 @@ fn getOnFinish(self: *const Animation) ?js.Function.Global {// callback function transitioning from a state to anotherfn update(ctx: *anyopaque) !?u32 {const self: *Animation = @ptrCast(@alignCast(ctx));+ defer self.releaseRef(self._frame.page);switch (self._playState) {.running => {@@ -206,18 +265,10 @@ fn update(ctx: *anyopaque) !?u32 {if (self._finished_resolver) |resolver| {ls.toLocal(resolver).resolve("Animation.getFinished", self);}- // call onfinish- if (self._onFinish) |func| {- ls.toLocal(func).call(void, .{}) catch |err| {- log.debug(.js, "Animation._onFinish", .{ .err = err });- };- }+ try self.dispatchPlaybackEvent(comptime .wrap("finish"), self._onFinish);},.idle, .paused, .finished => {},}-- // No future change scheduled, set the object weak for garbage collection.- self.releaseRef(self._frame.page);return null;}@@ -225,6 +276,14 @@ fn setOnFinish(self: *Animation, cb: ?js.Function.Global) !void {self._onFinish = cb;}+fn getOnCancel(self: *const Animation) ?js.Function.Global {+ return self._onCancel;+}++fn setOnCancel(self: *Animation, cb: ?js.Function.Global) !void {+ self._onCancel = cb;+}+fn playState(self: *const Animation) []const u8 {return @tagName(self._playState);}@@ -251,6 +310,7 @@ pub const JsApi = struct {pub const timeline = bridge.accessor(Animation.getTimeline, Animation.setTimeline, .{});pub const startTime = bridge.accessor(Animation.getStartTime, Animation.setStartTime, .{});pub const onfinish = bridge.accessor(Animation.getOnFinish, Animation.setOnFinish, .{});+ pub const oncancel = bridge.accessor(Animation.getOnCancel, Animation.setOnCancel, .{});};const testing = @import("../../../testing.zig");diff --git a/src/browser/webapi/event/AnimationPlaybackEvent.zig b/src/browser/webapi/event/AnimationPlaybackEvent.zignew file mode 100644index 000000000..871748937--- /dev/null+++ b/src/browser/webapi/event/AnimationPlaybackEvent.zig@@ -0,0 +1,98 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Frame = @import("../../Frame.zig");++const Event = @import("../Event.zig");++const String = lp.String;++// https://drafts.csswg.org/web-animations-1/#the-animationplaybackevent-interface+const AnimationPlaybackEvent = @This();++pub const Proto = Event;++_proto: *Event,+_current_time: ?f64,+_timeline_time: ?f64,++const AnimationPlaybackEventOptions = struct {+ currentTime: ?f64 = null,+ timelineTime: ?f64 = null,+};++const Options = Event.inheritOptions(AnimationPlaybackEvent, AnimationPlaybackEventOptions);++pub fn init(typ: []const u8, _opts: ?Options, frame: *Frame) !*AnimationPlaybackEvent {+ const arena = try frame.getArena(.tiny, "AnimationPlaybackEvent");+ errdefer arena.release();+ const type_string = try String.init(arena.allocator(), typ, .{});+ return initWithTrusted(arena, type_string, _opts, false, frame);+}++pub fn initTrusted(typ: String, _opts: ?Options, frame: *Frame) !*AnimationPlaybackEvent {+ const arena = try frame.getArena(.tiny, "AnimationPlaybackEvent.trusted");+ errdefer arena.release();+ return initWithTrusted(arena, typ, _opts, true, frame);+}++fn initWithTrusted(arena: *lp.Arena, typ: String, _opts: ?Options, trusted: bool, frame: *Frame) !*AnimationPlaybackEvent {+ const opts = _opts orelse Options{};++ const event = try frame._factory.event(+ arena,+ typ,+ AnimationPlaybackEvent{+ ._proto = undefined,+ ._current_time = opts.currentTime,+ ._timeline_time = opts.timelineTime,+ },+ );++ Event.populatePrototypes(event, opts, trusted);+ return event;+}++pub fn asEvent(self: *AnimationPlaybackEvent) *Event {+ return self._proto;+}++fn getCurrentTime(self: *const AnimationPlaybackEvent) ?f64 {+ return self._current_time;+}++fn getTimelineTime(self: *const AnimationPlaybackEvent) ?f64 {+ return self._timeline_time;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(AnimationPlaybackEvent);++ pub const Meta = struct {+ pub const name = "AnimationPlaybackEvent";+ pub const prototype_chain = bridge.prototypeChain();+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(AnimationPlaybackEvent.init, .{});+ pub const currentTime = bridge.accessor(AnimationPlaybackEvent.getCurrentTime, null, .{});+ pub const timelineTime = bridge.accessor(AnimationPlaybackEvent.getTimelineTime, null, .{});+};