nsh-js 0.8.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
//! Touches and the gesture responder system, and `PanResponder`
//! (`nsh/gesture`), in Rust as it runs on every touch move.
//!
//! Native views whose node has a touch or responder handler listen to
//! touches (`onTouch`); their touches (and those on views inside them)
//! arrive with the path of listening views from the target outwards.
//! Handlers then run as in React Native: touch handlers capture inwards and
//! bubble outwards, and the responder is negotiated with the
//! `…ShouldSetResponder` handlers, which also get the gesture since the
//! first finger went down (`gestureState`, as `PanResponder`'s). A view with
//! `panActivation` is not asked: it becomes the responder when the platform
//! activates its pan (`TouchEvent::activated`).

use std::{
    cell::{Cell, RefCell},
    ffi::{CStr, c_int},
};

use nsh_core::{
    Command, NodeId, Op, TouchEvent, TouchPhase, TouchPoint, decl, element::PanGesture,
    keymap::Modifiers,
};
use rquickjs::qjs;
use rustc_hash::FxHashMap;

use crate::{
    dom,
    modules::{Export, Item, Ts},
    reactive::{self, arg},
};

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

const UNDEFINED: JsValue = qjs::JS_UNDEFINED;

/// The touch and responder props: name, handler type and documentation
/// (the declarations of `TouchProps`).
pub(crate) const TOUCH_PROPS: [(&str, &str, &str); 20] = [
    (
        "onTouchStart",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchMove",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchEnd",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchCancel",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchStartCapture",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchMoveCapture",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchEndCapture",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onTouchCancelCapture",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onStartShouldSetResponder",
        decl!("(e: GestureResponderEvent, gestureState: ResponderGestureState) => boolean"),
        decl!("Become the responder when a finger goes down (asked from the target outwards)."),
    ),
    (
        "onMoveShouldSetResponder",
        decl!("(e: GestureResponderEvent, gestureState: ResponderGestureState) => boolean"),
        decl!(
            "Become the responder when a finger moves (`gestureState`: the gesture since the first finger went down, e.g. `Math.abs(g.dx) > 10`)."
        ),
    ),
    (
        "onStartShouldSetResponderCapture",
        decl!("(e: GestureResponderEvent, gestureState: ResponderGestureState) => boolean"),
        decl!("As above, asked from the outside in, before the bubbling ones."),
    ),
    (
        "onMoveShouldSetResponderCapture",
        decl!("(e: GestureResponderEvent, gestureState: ResponderGestureState) => boolean"),
        "",
    ),
    (
        "onResponderGrant",
        decl!("(e: GestureResponderEvent) => boolean | void"),
        decl!(
            "This view is the responder now. Return true to keep native scroll views from taking the touches."
        ),
    ),
    (
        "onResponderReject",
        decl!("(e: GestureResponderEvent) => void"),
        decl!("Another view is the responder and would not let go."),
    ),
    (
        "onResponderStart",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onResponderMove",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onResponderEnd",
        decl!("(e: GestureResponderEvent) => void"),
        "",
    ),
    (
        "onResponderRelease",
        decl!("(e: GestureResponderEvent) => void"),
        decl!("The last finger lifted."),
    ),
    (
        "onResponderTerminate",
        decl!("(e: GestureResponderEvent) => void"),
        decl!("Another view (or a native gesture) took the touches."),
    ),
    (
        "onResponderTerminationRequest",
        decl!("(e: GestureResponderEvent) => boolean"),
        decl!("Another view wants the touches: return false to keep them (default true)."),
    ),
];

/// The index of touch prop `name`.
pub(crate) fn touch_prop(name: &str) -> Option<u8> {
    TOUCH_PROPS
        .iter()
        .position(|p| p.0 == name)
        .map(|i| i as u8)
}

fn index(name: &str) -> u8 {
    touch_prop(name).expect("a touch prop")
}

/// The touches' part of a context's state.
#[derive(Default)]
pub(crate) struct Touches {
    /// Listening views around each finger, innermost first.
    paths: RefCell<FxHashMap<u32, Vec<NodeId>>>,
    responder: Cell<Option<NodeId>>,
    /// The responder keeps native scroll views from taking the touches.
    blocks: Cell<bool>,
    /// `PanResponder` gesture state ids.
    pan_states: Cell<u32>,
    /// The gesture since the first finger went down, for the negotiation.
    gesture: Cell<PanGesture>,
}

fn touches<'a>(cx: *mut JsContext) -> &'a Touches {
    // SAFETY: a projection of the state's field, by shared reference.
    unsafe { &(*crate::state::state(cx)).touches }
}

fn number(v: f64) -> JsValue {
    qjs::JS_NewFloat64(v)
}

fn set(cx: *mut JsContext, obj: JsValue, key: &CStr, v: JsValue) {
    // SAFETY: the object takes `v`.
    unsafe { qjs::JS_SetPropertyStr(cx, obj, key.as_ptr(), v) };
}

fn get(cx: *mut JsContext, obj: JsValue, key: &CStr) -> JsValue {
    // SAFETY: a property read of a live value.
    unsafe {
        if !qjs::JS_IsObject(obj) {
            return UNDEFINED;
        }
        qjs::JS_GetPropertyStr(cx, obj, key.as_ptr())
    }
}

fn get_number(cx: *mut JsContext, obj: JsValue, key: &CStr) -> f64 {
    let v = get(cx, obj, key);
    let mut n = 0f64;
    // SAFETY: converting and freeing a value got.
    unsafe {
        qjs::JS_ToFloat64(cx, &mut n, v);
        qjs::JS_FreeValue(cx, v);
    }
    n
}

fn free(cx: *mut JsContext, v: JsValue) {
    // SAFETY: an owned value.
    unsafe { qjs::JS_FreeValue(cx, v) };
}

/// The pointer fields of `p` on `o` (`pointerType`, `pressure`, `tiltX`,
/// `tiltY`, `eraser`, `barrel`, `coalesced`).
fn set_pointer(cx: *mut JsContext, o: JsValue, p: &TouchPoint) {
    let name = p.pointer_type.name();
    // SAFETY: a new string the object takes.
    let kind = unsafe { qjs::JS_NewStringLen(cx, name.as_ptr().cast(), name.len() as _) };
    set(cx, o, c"pointerType", kind);
    set(cx, o, c"pressure", number(p.pressure as f64));
    set(cx, o, c"tiltX", number(p.tilt_x as f64));
    set(cx, o, c"tiltY", number(p.tilt_y as f64));
    let flag = |v: bool| if v { qjs::JS_TRUE } else { qjs::JS_FALSE };
    set(cx, o, c"eraser", flag(p.eraser));
    set(cx, o, c"barrel", flag(p.barrel));
    let samples = p
        .coalesced
        .iter()
        .map(|c| {
            // SAFETY: a new object.
            let s = unsafe { qjs::JS_NewObject(cx) };
            set(cx, s, c"pageX", number(c.page.x.0 as f64));
            set(cx, s, c"pageY", number(c.page.y.0 as f64));
            set(cx, s, c"locationX", number(c.location.x.0 as f64));
            set(cx, s, c"locationY", number(c.location.y.0 as f64));
            set(cx, s, c"pressure", number(c.pressure as f64));
            set(cx, s, c"tiltX", number(c.tilt_x as f64));
            set(cx, s, c"tiltY", number(c.tilt_y as f64));
            set(cx, s, c"timestamp", number(c.timestamp));
            s
        })
        .collect();
    set(cx, o, c"coalesced", array(cx, samples));
}

/// A touch point as JS sees it.
fn point(cx: *mut JsContext, p: &TouchPoint, timestamp: f64) -> JsValue {
    // SAFETY: a new object.
    let o = unsafe { qjs::JS_NewObject(cx) };
    set(cx, o, c"identifier", number(p.id as f64));
    set(cx, o, c"target", number(p.target as f64));
    set(cx, o, c"pageX", number(p.page.x.0 as f64));
    set(cx, o, c"pageY", number(p.page.y.0 as f64));
    set(cx, o, c"locationX", number(p.location.x.0 as f64));
    set(cx, o, c"locationY", number(p.location.y.0 as f64));
    set(cx, o, c"timestamp", number(timestamp));
    set_pointer(cx, o, p);
    o
}

/// `Modifiers` as a press event's (`{ control, alt, shift, platform, altGraph }`).
fn modifiers_object(cx: *mut JsContext, m: &Modifiers) -> JsValue {
    // SAFETY: a new object.
    let o = unsafe { qjs::JS_NewObject(cx) };
    let flag = |v: bool| if v { qjs::JS_TRUE } else { qjs::JS_FALSE };
    set(cx, o, c"control", flag(m.ctrl));
    set(cx, o, c"alt", flag(m.alt));
    set(cx, o, c"shift", flag(m.shift));
    set(cx, o, c"platform", flag(m.cmd));
    set(cx, o, c"altGraph", flag(m.alt_graph));
    o
}

fn array(cx: *mut JsContext, mut values: Vec<JsValue>) -> JsValue {
    // SAFETY: the array takes the values.
    unsafe { qjs::JS_NewArrayFrom(cx, values.len() as c_int, values.as_mut_ptr()) }
}

/// `e.stopPropagation()`.
unsafe extern "C" fn stop_propagation(
    cx: *mut JsContext,
    this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
) -> JsValue {
    set(cx, this, c"stopped", qjs::JS_TRUE);
    UNDEFINED
}

/// The event handlers get: about `about`, with `touches` down and
/// `changed`.
fn event(
    cx: *mut JsContext,
    about: &TouchPoint,
    touches: &[&TouchPoint],
    changed: &[&TouchPoint],
    timestamp: f64,
    modifiers: &Modifiers,
) -> JsValue {
    // SAFETY: a new object taking its fields.
    let e = unsafe { qjs::JS_NewObject(cx) };
    set(cx, e, c"identifier", number(about.id as f64));
    set(cx, e, c"locationX", number(about.location.x.0 as f64));
    set(cx, e, c"locationY", number(about.location.y.0 as f64));
    set(cx, e, c"pageX", number(about.page.x.0 as f64));
    set(cx, e, c"pageY", number(about.page.y.0 as f64));
    set(cx, e, c"target", number(about.target as f64));
    set(cx, e, c"timestamp", number(timestamp));
    set_pointer(cx, e, about);
    set(cx, e, c"modifiers", modifiers_object(cx, modifiers));
    let list = |ps: &[&TouchPoint]| array(cx, ps.iter().map(|p| point(cx, p, timestamp)).collect());
    set(cx, e, c"touches", list(touches));
    set(cx, e, c"changedTouches", list(changed));
    set(cx, e, c"stopped", qjs::JS_FALSE);
    set(
        cx,
        e,
        c"stopPropagation",
        reactive::new_function(cx, c"stopPropagation", stop_propagation, 0),
    );
    // SAFETY: a dup the object holds (a cycle the GC collects).
    set(cx, e, c"nativeEvent", unsafe { qjs::JS_DupValue(cx, e) });
    e
}

fn stopped(cx: *mut JsContext, e: JsValue) -> bool {
    let v = get(cx, e, c"stopped");
    // SAFETY: an inline check of a value got, then freed.
    let s = unsafe { qjs::JS_ToBool(cx, v) == 1 };
    free(cx, v);
    s
}

/// Calls node `id`'s handler `prop` with `e`; its result (owned).
fn call(cx: *mut JsContext, id: NodeId, prop: u8, e: JsValue) -> Result<JsValue, JsValue> {
    call_with(cx, id, prop, &mut [e])
}

/// Calls node `id`'s handler `prop` with `args` (borrowed); its result
/// (owned).
fn call_with(
    cx: *mut JsContext,
    id: NodeId,
    prop: u8,
    args: &mut [JsValue],
) -> Result<JsValue, JsValue> {
    let Some(f) = dom::touch_handler(cx, id, prop) else {
        return Ok(UNDEFINED);
    };
    // SAFETY: an owned function, called then freed.
    let r = unsafe { qjs::JS_Call(cx, f, UNDEFINED, args.len() as c_int, args.as_mut_ptr()) };
    free(cx, f);
    // SAFETY: an inline tag check.
    if unsafe { qjs::JS_IsException(r) } {
        // A listener made under an error boundary fails into it.
        if dom::catch_listener_failure(cx, id) {
            return Ok(UNDEFINED);
        }
        Err(r)
    } else {
        Ok(r)
    }
}

/// Calls `prop` with `args` and tells whether it returned `true`.
fn asks(cx: *mut JsContext, id: NodeId, prop: u8, args: &mut [JsValue]) -> Result<bool, JsValue> {
    let r = call_with(cx, id, prop, args)?;
    // SAFETY: an inline check of an owned value.
    let yes = unsafe { qjs::JS_IsBool(r) && qjs::JS_VALUE_GET_BOOL(r) };
    free(cx, r);
    Ok(yes)
}

fn run(cx: *mut JsContext, id: NodeId, prop: u8, e: JsValue) -> Result<(), JsValue> {
    call(cx, id, prop, e).map(|r| free(cx, r))
}

/// `name` on `path` (innermost first): capture outside in, then bubble.
fn two_phase(cx: *mut JsContext, path: &[NodeId], name: &str, e: JsValue) -> Result<(), JsValue> {
    let capture = index(&format!("{name}Capture"));
    let bubble = index(name);
    for &id in path.iter().rev() {
        if stopped(cx, e) {
            return Ok(());
        }
        run(cx, id, capture, e)?;
    }
    for &id in path {
        if stopped(cx, e) {
            return Ok(());
        }
        run(cx, id, bubble, e)?;
    }
    Ok(())
}

fn command(cx: *mut JsContext, id: NodeId, command: Command) -> Result<(), JsValue> {
    dom::push_op(cx, Op::Command { id, command })
}

fn grant(cx: *mut JsContext, id: NodeId, e: JsValue) -> Result<(), JsValue> {
    let t = touches(cx);
    t.responder.set(Some(id));
    let block = asks(cx, id, index("onResponderGrant"), &mut [e])?;
    if block {
        command(cx, id, Command::SetJsResponder { block: true })?;
    } else if t.blocks.get() {
        command(cx, 1, Command::ClearJsResponder)?;
    }
    t.blocks.set(block);
    Ok(())
}

fn release(cx: *mut JsContext) -> Result<(), JsValue> {
    let t = touches(cx);
    t.responder.set(None);
    if t.blocks.replace(false) {
        command(cx, 1, Command::ClearJsResponder)?;
    }
    Ok(())
}

/// The negotiation's `gestureState` (owned): the gesture since the first
/// finger went down.
fn gesture_state(cx: *mut JsContext) -> JsValue {
    let g = touches(cx).gesture.get();
    // SAFETY: a new object taking its fields.
    let o = unsafe { qjs::JS_NewObject(cx) };
    for (k, v) in [
        (c"moveX", g.position.x.0),
        (c"moveY", g.position.y.0),
        (c"x0", g.origin.x.0),
        (c"y0", g.origin.y.0),
        (c"dx", g.delta.x.0),
        (c"dy", g.delta.y.0),
        (c"vx", g.vx),
        (c"vy", g.vy),
    ] {
        set(cx, o, k, number(v as f64));
    }
    set(
        cx,
        o,
        c"numberActiveTouches",
        number(g.active_touches as f64),
    );
    o
}

/// Asks `path` whether a view wants to become the responder (`kind`:
/// `onStartShouldSetResponder` or `onMoveShouldSetResponder`), from the
/// views around both the target and the current responder, the responder
/// itself and views waiting for their pan excluded.
fn negotiate(cx: *mut JsContext, kind: &str, path: &[NodeId], e: JsValue) -> Result<(), JsValue> {
    let responder = touches(cx).responder.get();
    let mut from = 0;
    if let Some(r) = responder {
        while from < path.len() && !dom::is_ancestor_of(cx, path[from], r) {
            from += 1;
        }
        if path.get(from) == Some(&r) {
            from += 1;
        }
    }
    let capture = index(&format!("{kind}Capture"));
    let bubble = index(kind);
    let asked = &path[from.min(path.len())..];
    // Made for the first handler asked.
    let mut gs = UNDEFINED;
    let mut ask = |id: NodeId, prop: u8| -> Result<bool, JsValue> {
        if dom::pan_gated(cx, id) || !dom::touch_handler_exists(cx, id, prop) {
            return Ok(false);
        }
        // SAFETY: an inline tag check.
        if unsafe { qjs::JS_IsUndefined(gs) } {
            gs = gesture_state(cx);
        }
        asks(cx, id, prop, &mut [e, gs])
    };
    let mut wanting = None;
    let mut result = Ok(());
    for &id in asked.iter().rev() {
        match ask(id, capture) {
            Ok(false) => {}
            Ok(true) => {
                wanting = Some(id);
                break;
            }
            Err(x) => {
                result = Err(x);
                break;
            }
        }
    }
    if wanting.is_none() && result.is_ok() {
        for &id in asked {
            match ask(id, bubble) {
                Ok(false) => {}
                Ok(true) => {
                    wanting = Some(id);
                    break;
                }
                Err(x) => {
                    result = Err(x);
                    break;
                }
            }
        }
    }
    free(cx, gs);
    result?;
    match wanting {
        Some(wanting) if Some(wanting) != responder => take_over(cx, wanting, e),
        _ => Ok(()),
    }
}

/// View `wanting` wants the touches: it becomes the responder unless the
/// current one refuses to let go.
fn take_over(cx: *mut JsContext, wanting: NodeId, e: JsValue) -> Result<(), JsValue> {
    if let Some(r) = touches(cx).responder.get() {
        let request = index("onResponderTerminationRequest");
        if dom::touch_handler_exists(cx, r, request) {
            let r_ok = call(cx, r, request, e)?;
            // SAFETY: an inline check of an owned value.
            let refused = unsafe { qjs::JS_IsBool(r_ok) && !qjs::JS_VALUE_GET_BOOL(r_ok) };
            free(cx, r_ok);
            if refused {
                return run(cx, wanting, index("onResponderReject"), e);
            }
        }
        run(cx, r, index("onResponderTerminate"), e)?;
    }
    grant(cx, wanting, e)
}

/// Delivers a touch event to the JS handlers along its path.
pub(crate) fn dispatch(cx: *mut JsContext, touch: &TouchEvent) -> Result<(), JsValue> {
    let t = touches(cx);
    let phase = touch.phase;
    for p in &touch.points {
        if phase == TouchPhase::Start && p.changed {
            let path: Vec<NodeId> = p
                .path
                .iter()
                .copied()
                .filter(|&id| dom::listens_to_touches(cx, id))
                .collect();
            t.paths.borrow_mut().insert(p.id, path);
        }
    }
    let lifted = matches!(phase, TouchPhase::End | TouchPhase::Cancel);
    let mut gesture = t.gesture.get();
    match phase {
        // The gesture starts with the first fingers: no other was down
        // (two landing together come in one event).
        TouchPhase::Start if touch.points.iter().all(|p| p.changed) => {
            gesture = PanGesture::begin(touch)
        }
        TouchPhase::Start | TouchPhase::Move => gesture.update(touch),
        TouchPhase::End | TouchPhase::Cancel => {}
    }
    t.gesture.set(gesture);
    let down: Vec<&TouchPoint> = touch
        .points
        .iter()
        .filter(|p| !lifted || !p.changed)
        .collect();
    let changed: Vec<&TouchPoint> = touch.points.iter().filter(|p| p.changed).collect();
    let Some(about) = changed.first().copied() else {
        return Ok(());
    };
    let path = t.paths.borrow().get(&about.id).cloned().unwrap_or_default();
    let e = event(
        cx,
        about,
        &down,
        &changed,
        touch.timestamp,
        &touch.modifiers,
    );
    let result = (|| -> Result<(), JsValue> {
        let raw = match phase {
            TouchPhase::Start => "onTouchStart",
            TouchPhase::Move => "onTouchMove",
            TouchPhase::End => "onTouchEnd",
            TouchPhase::Cancel => "onTouchCancel",
        };
        two_phase(cx, &path, raw, e)?;
        set(cx, e, c"stopped", qjs::JS_FALSE);
        // A pan the platform activated: its view takes the touches.
        if let Some(id) = touch.activated
            && dom::pan_gated(cx, id)
            && dom::listens_to_touches(cx, id)
            && touches(cx).responder.get() != Some(id)
        {
            take_over(cx, id, e)?;
        }
        match phase {
            TouchPhase::Start => negotiate(cx, "onStartShouldSetResponder", &path, e)?,
            TouchPhase::Move => negotiate(cx, "onMoveShouldSetResponder", &path, e)?,
            _ => {}
        }
        if let Some(r) = touches(cx).responder.get() {
            if phase == TouchPhase::Cancel {
                run(cx, r, index("onResponderTerminate"), e)?;
                release(cx)?;
            } else {
                let handler = match phase {
                    TouchPhase::Start => "onResponderStart",
                    TouchPhase::Move => "onResponderMove",
                    _ => "onResponderEnd",
                };
                run(cx, r, index(handler), e)?;
                if phase == TouchPhase::End && down.is_empty() {
                    release(cx)?;
                    run(cx, r, index("onResponderRelease"), e)?;
                }
            }
        }
        Ok(())
    })();
    free(cx, e);
    if lifted {
        let mut paths = touches(cx).paths.borrow_mut();
        for p in &changed {
            paths.remove(&p.id);
        }
    }
    result
}

// --- PanResponder -----------------------------------------------------------------

/// The pan handlers, by magic.
const PAN_HANDLERS: [&CStr; 12] = [
    c"onStartShouldSetResponderCapture",
    c"onStartShouldSetResponder",
    c"onMoveShouldSetResponderCapture",
    c"onMoveShouldSetResponder",
    c"onResponderGrant",
    c"onResponderReject",
    c"onResponderStart",
    c"onResponderMove",
    c"onResponderEnd",
    c"onResponderRelease",
    c"onResponderTerminate",
    c"onResponderTerminationRequest",
];

/// `PanResponder.create(config)`: `{ panHandlers }` tracking a pan's
/// gesture state (`dx`, `vx`, ...) across the responder's events.
unsafe extern "C" fn pan_create(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let config = arg(argc, argv, 0);
    let t = touches(cx);
    let id = t.pan_states.get() + 1;
    t.pan_states.set(id);
    // SAFETY: new objects; the handlers keep dups of `data`.
    unsafe {
        let gs = qjs::JS_NewObject(cx);
        set(cx, gs, c"stateID", number(id as f64));
        for key in [
            c"moveX",
            c"moveY",
            c"x0",
            c"y0",
            c"dx",
            c"dy",
            c"vx",
            c"vy",
            c"numberActiveTouches",
        ] {
            set(cx, gs, key, number(0.0));
        }
        // The centroid, time and touch count of the last update.
        let last = qjs::JS_NewObject(cx);
        let handlers = qjs::JS_NewObject(cx);
        for (magic, name) in PAN_HANDLERS.iter().enumerate() {
            let mut data = [config, gs, last];
            let f = qjs::JS_NewCFunctionData(
                cx,
                Some(pan_handler),
                1,
                magic as c_int,
                3,
                data.as_mut_ptr(),
            );
            set(cx, handlers, name, f);
        }
        free(cx, gs);
        free(cx, last);
        let r = qjs::JS_NewObject(cx);
        set(cx, r, c"panHandlers", handlers);
        r
    }
}

/// The centroid of `e.touches`; `None` (an exception pending) when the
/// array's length throws or is longer than [`dom::MAX_ARRAY_ITEMS`] (the
/// app may call the handlers with an event of its own).
fn centroid(cx: *mut JsContext, e: JsValue) -> Option<(f64, f64, usize)> {
    let list = get(cx, e, c"touches");
    let mut len = 0;
    let (mut x, mut y) = (0.0, 0.0);
    // SAFETY: reads of live values, freed after.
    unsafe {
        if qjs::JS_IsArray(list) {
            // Read natively: a sparse array is as long as it says.
            let Some(n) = dom::checked_len(cx, list) else {
                qjs::JS_FreeValue(cx, list);
                return None;
            };
            len = n;
            for i in 0..len {
                let p = qjs::JS_GetPropertyUint32(cx, list, i);
                x += get_number(cx, p, c"pageX");
                y += get_number(cx, p, c"pageY");
                qjs::JS_FreeValue(cx, p);
            }
        }
        qjs::JS_FreeValue(cx, list);
    }
    let n = f64::from(len.max(1));
    Some((x / n, y / n, len as usize))
}

fn remember(cx: *mut JsContext, last: JsValue, x: f64, y: f64, time: f64, count: usize) {
    set(cx, last, c"x", number(x));
    set(cx, last, c"y", number(y));
    set(cx, last, c"t", number(time));
    set(cx, last, c"n", number(count as f64));
}

/// A grant or a first finger: the gesture starts here; `None` (an
/// exception pending) as [`centroid`].
fn reset(cx: *mut JsContext, gs: JsValue, last: JsValue, e: JsValue) -> Option<()> {
    let (x, y, n) = centroid(cx, e)?;
    for (k, v) in [
        (c"moveX", x),
        (c"moveY", y),
        (c"x0", x),
        (c"y0", y),
        (c"dx", 0.0),
        (c"dy", 0.0),
        (c"vx", 0.0),
        (c"vy", 0.0),
    ] {
        set(cx, gs, k, number(v));
    }
    set(cx, gs, c"numberActiveTouches", number(n as f64));
    remember(cx, last, x, y, get_number(cx, e, c"timestamp"), n);
    Some(())
}

/// Moves the gesture to `e`'s touches (a finger going down or up makes
/// the centroid jump, which is no movement); `None` (an exception
/// pending) as [`centroid`].
fn update(cx: *mut JsContext, gs: JsValue, last: JsValue, e: JsValue) -> Option<()> {
    let time = get_number(cx, e, c"timestamp");
    let (lx, ly, lt, ln) = (
        get_number(cx, last, c"x"),
        get_number(cx, last, c"y"),
        get_number(cx, last, c"t"),
        get_number(cx, last, c"n") as usize,
    );
    let (x, y, n) = centroid(cx, e)?;
    if time == lt && n == ln {
        return Some(());
    }
    set(cx, gs, c"numberActiveTouches", number(n as f64));
    if n == ln {
        // Timestamps are milliseconds, velocities per second.
        let dt = (time - lt).max(1.0) / 1000.0;
        set(cx, gs, c"dx", number(get_number(cx, gs, c"dx") + x - lx));
        set(cx, gs, c"dy", number(get_number(cx, gs, c"dy") + y - ly));
        // Smoothed over a few samples.
        set(
            cx,
            gs,
            c"vx",
            number(get_number(cx, gs, c"vx") * 0.3 + (x - lx) / dt * 0.7),
        );
        set(
            cx,
            gs,
            c"vy",
            number(get_number(cx, gs, c"vy") * 0.3 + (y - ly) / dt * 0.7),
        );
    }
    set(cx, gs, c"moveX", number(x));
    set(cx, gs, c"moveY", number(y));
    remember(cx, last, x, y, time, n);
    Some(())
}

/// Calls the config's `name(e, gs)`; `None` when it has none.
fn callback(
    cx: *mut JsContext,
    config: JsValue,
    name: &CStr,
    e: JsValue,
    gs: JsValue,
) -> Option<JsValue> {
    let f = get(cx, config, name);
    // SAFETY: an inline check; the call's arguments are borrowed.
    unsafe {
        if !qjs::JS_IsFunction(cx, f) {
            qjs::JS_FreeValue(cx, f);
            return None;
        }
        let mut args = [e, gs];
        let r = qjs::JS_Call(cx, f, UNDEFINED, 2, args.as_mut_ptr());
        qjs::JS_FreeValue(cx, f);
        Some(r)
    }
}

/// The config's answer, or `default` without a callback.
fn answer(r: Option<JsValue>, default: bool) -> JsValue {
    match r {
        Some(v) => v,
        None => {
            if default {
                qjs::JS_TRUE
            } else {
                qjs::JS_FALSE
            }
        }
    }
}

fn next_state(cx: *mut JsContext, gs: JsValue) {
    let t = touches(cx);
    let id = t.pan_states.get() + 1;
    t.pan_states.set(id);
    set(cx, gs, c"stateID", number(id as f64));
}

unsafe extern "C" fn pan_handler(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values (`pan_create`).
    let (config, gs, last) = unsafe { (*data, *data.add(1), *data.add(2)) };
    let e = arg(argc, argv, 0);
    let ignore = |r: Option<JsValue>| match r {
        Some(v) => v,
        None => UNDEFINED,
    };
    match magic {
        // onStartShouldSetResponderCapture
        0 => {
            let Some((_, _, n)) = centroid(cx, e) else {
                return qjs::JS_EXCEPTION;
            };
            if n == 1 && reset(cx, gs, last, e).is_none() {
                return qjs::JS_EXCEPTION;
            }
            set(cx, gs, c"numberActiveTouches", number(n as f64));
            let r = callback(cx, config, c"onStartShouldSetPanResponderCapture", e, gs);
            answer(r, false)
        }
        1 => answer(
            callback(cx, config, c"onStartShouldSetPanResponder", e, gs),
            false,
        ),
        2 => {
            if update(cx, gs, last, e).is_none() {
                return qjs::JS_EXCEPTION;
            }
            answer(
                callback(cx, config, c"onMoveShouldSetPanResponderCapture", e, gs),
                false,
            )
        }
        3 => {
            if update(cx, gs, last, e).is_none() {
                return qjs::JS_EXCEPTION;
            }
            answer(
                callback(cx, config, c"onMoveShouldSetPanResponder", e, gs),
                false,
            )
        }
        // onResponderGrant: the gesture starts at the grant.
        4 => {
            if reset(cx, gs, last, e).is_none() {
                return qjs::JS_EXCEPTION;
            }
            if let Some(r) = callback(cx, config, c"onPanResponderGrant", e, gs) {
                // SAFETY: an inline tag check.
                if unsafe { qjs::JS_IsException(r) } {
                    return r;
                }
                free(cx, r);
            }
            answer(
                callback(cx, config, c"onShouldBlockNativeResponder", e, gs),
                true,
            )
        }
        5 => ignore(callback(cx, config, c"onPanResponderReject", e, gs)),
        6..=8 => {
            if update(cx, gs, last, e).is_none() {
                return qjs::JS_EXCEPTION;
            }
            let name = match magic {
                6 => c"onPanResponderStart",
                7 => c"onPanResponderMove",
                _ => c"onPanResponderEnd",
            };
            ignore(callback(cx, config, name, e, gs))
        }
        9 | 10 => {
            let name = if magic == 9 {
                c"onPanResponderRelease"
            } else {
                c"onPanResponderTerminate"
            };
            let r = ignore(callback(cx, config, name, e, gs));
            next_state(cx, gs);
            r
        }
        _ => answer(
            callback(cx, config, c"onPanResponderTerminationRequest", e, gs),
            true,
        ),
    }
}

fn pan_responder(cx: *mut JsContext) -> JsValue {
    // SAFETY: a new object taking the function.
    let o = unsafe { qjs::JS_NewObject(cx) };
    set(
        cx,
        o,
        c"create",
        reactive::new_function(cx, c"create", pan_create, 1),
    );
    o
}

/// `nsh/gesture`.
pub(crate) const GESTURE_EXPORTS: &[Item] = &[(
    "PanResponder",
    Export::Value(pan_responder),
    Ts::value(
        "Pan gestures on top of the responder system (React Native's\n`PanResponder`).",
        "{ create(config: PanResponderCallbacks): PanResponderInstance }",
    ),
)];

/// The touch events' types (part of every element's props: `types.d.ts`).
pub(crate) const TOUCH_TYPES: &str = r#"/** A finger of a touch event (points). */
export interface TouchPoint {
  /** Identifies the finger while it is down. */
  identifier: number;
  /** Position in the view the finger went down on (`target`). */
  locationX: number;
  locationY: number;
  /** Position in the surface. */
  pageX: number;
  pageY: number;
  /** Id of the view the finger went down on. */
  target: number;
  /** Milliseconds. */
  timestamp: number;
  /** What touches: `"touch"` (a finger), `"pen"` or `"mouse"`. */
  pointerType: PointerType;
  /** How hard it presses, 0 to 1 (`PointerEvent.pressure`): 0.5 while down
   * and 0 once lifted on a device without pressure. */
  pressure: number;
  /** A pen's tilt in degrees, -90 to 90 (`PointerEvent.tiltX` / `tiltY`);
   * 0 when the device does not report it. */
  tiltX: number;
  tiltY: number;
  /** A pen used with its eraser end (`pointerType` stays `"pen"`). */
  eraser: boolean;
  /** A pen's barrel (side) button is held. */
  barrel: boolean;
  /** The samples the platform merged into this event, oldest first, as
   * `PointerEvent.getCoalescedEvents()` without the last one (this point):
   * a pen moves at 120-240 Hz, and a slow frame only gets its latest
   * position. Draw them before this point for a smooth stroke. Empty when
   * nothing was merged. */
  coalesced: CoalescedSample[];
}

/** A pointer sample merged into a `TouchPoint` (points). */
export interface CoalescedSample {
  pageX: number;
  pageY: number;
  locationX: number;
  locationY: number;
  pressure: number;
  tiltX: number;
  tiltY: number;
  /** When the device took it, in milliseconds (the clock of `timestamp`). */
  timestamp: number;
}

/** A touch or responder event: the finger it is about, the fingers down
 * and those that changed (React Native's `nativeEvent`, which it also is). */
export interface GestureResponderEvent extends TouchPoint {
  touches: TouchPoint[];
  changedTouches: TouchPoint[];
  nativeEvent: GestureResponderEvent;
  /** The modifier keys held when the finger (or mouse button) went down,
   * as `PressEvent`'s: an Alt-drag or a Shift-click reads them in the
   * responder grant. On every target the touch events and the responder
   * grant come before the same press's `onPressDown` (which waits ~130 ms
   * in a scroll view, as the touch may start a scroll). */
  modifiers: Modifiers;
  /** Touch handlers (`onTouchStart`…): views further out do not see it. */
  stopPropagation(): void;
}

/** A gesture followed through touch events: the fingers' centroid, how far
 * it moved and how fast (React Native's `PanResponderGestureState`). The
 * `…ShouldSetResponder` handlers get it since the first finger went down. */
export interface ResponderGestureState {
  /** Latest position of the touches' centroid (surface points). */
  moveX: number;
  moveY: number;
  /** Where the centroid was when the gesture began. */
  x0: number;
  y0: number;
  /** Distance moved since then. */
  dx: number;
  dy: number;
  /** Velocity (points per second). */
  vx: number;
  vy: number;
  numberActiveTouches: number;
}
"#;

/// `nsh/gesture`'s types.
pub(crate) const GESTURE_TYPES: &str = r#"/** The state of a pan gesture (React Native's `PanResponderGestureState`):
 * since the grant once the view is the responder. */
export interface PanResponderGestureState extends ResponderGestureState {
  stateID: number;
}

/** A `PanResponder.create` callback. */
export type PanHandler<R = void> = (e: GestureResponderEvent, gestureState: PanResponderGestureState) => R;

/** `PanResponder.create` callbacks. */
export interface PanResponderCallbacks {
  onStartShouldSetPanResponder?: PanHandler<boolean>;
  onStartShouldSetPanResponderCapture?: PanHandler<boolean>;
  onMoveShouldSetPanResponder?: PanHandler<boolean>;
  onMoveShouldSetPanResponderCapture?: PanHandler<boolean>;
  onPanResponderGrant?: PanHandler;
  onPanResponderReject?: PanHandler;
  onPanResponderStart?: PanHandler;
  onPanResponderMove?: PanHandler;
  onPanResponderEnd?: PanHandler;
  onPanResponderRelease?: PanHandler;
  onPanResponderTerminate?: PanHandler;
  onPanResponderTerminationRequest?: PanHandler<boolean>;
  /** Keep native scroll views from taking the touches (default true). */
  onShouldBlockNativeResponder?: PanHandler<boolean>;
}

/** What `PanResponder.create` returns: spread `panHandlers` on a view. */
export interface PanResponderInstance {
  panHandlers: TouchProps;
}
"#;

#[cfg(test)]
mod tests {
    use nsh_core::{
        EventKind, EventPayload, Op, TouchEvent, TouchPhase, TouchPoint,
        geometry::{point, px},
    };

    use crate::Host;

    fn touch(phase: TouchPhase, x: f32, y: f32, t: f64) -> EventPayload {
        EventPayload::Touch(Box::new(TouchEvent {
            phase,
            timestamp: t,
            modifiers: Default::default(),
            activated: None,
            points: vec![TouchPoint {
                id: 1,
                target: 4,
                path: vec![4, 2],
                page: point(px(x), px(y)),
                location: point(px(x), px(y)),
                changed: true,
                pointer_type: nsh_core::PointerType::Touch,
                pressure: 0.5,
                tilt_x: 0.0,
                tilt_y: 0.0,
                coalesced: Vec::new(),
                eraser: false,
                barrel: false,
            }],
        }))
    }

    #[test]
    fn touches_capture_bubble_and_a_pan_responder_tracks_the_gesture() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"
            import { element, append, spread } from "nsh:rt";
            import { PanResponder } from "nsh";
            const log = [];
            globalThis.log = log;
            const outer = element("view");
            const inner = element("view");
            append(outer, inner);
            spread(outer, {
                onTouchStartCapture: () => log.push("outer capture"),
                onTouchStart: () => log.push("outer bubble"),
            });
            const pan = PanResponder.create({
                onStartShouldSetPanResponder: () => true,
                onPanResponderGrant: () => log.push("grant"),
                onPanResponderMove: (e, g) => log.push(`move ${g.dx},${g.dy}`),
                onPanResponderRelease: (e, g) => log.push(`release ${g.dx}`),
            });
            spread(inner, { ...pan.panHandlers, onTouchStart: () => log.push("inner bubble") });
            globalThis.keep = outer;
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let listens: Vec<_> = ops
            .iter()
            .filter(|o| {
                matches!(
                    o,
                    Op::Listen {
                        event: EventKind::Touch,
                        enabled: true,
                        ..
                    }
                )
            })
            .collect();
        assert_eq!(listens.len(), 2, "both views listen: {ops:?}");
        host.dispatch_event(
            4,
            EventKind::Touch,
            &touch(TouchPhase::Start, 10.0, 10.0, 0.0),
        );
        host.dispatch_event(
            4,
            EventKind::Touch,
            &touch(TouchPhase::Move, 30.0, 15.0, 16.0),
        );
        host.dispatch_event(
            4,
            EventKind::Touch,
            &touch(TouchPhase::End, 30.0, 15.0, 32.0),
        );
        host.eval_source(r#"import { text } from "nsh:rt"; text(globalThis.log.join("|"));"#)
            .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let log = ops
            .iter()
            .find_map(|o| match o {
                Op::CreateText { text, .. } => Some(text.clone()),
                _ => None,
            })
            .unwrap();
        assert_eq!(
            log,
            "outer capture|inner bubble|outer bubble|grant|move 20,5|release 20"
        );
        // The grant blocks native scroll views (the default), the release
        // lets go.
        assert!(ops.iter().any(|o| matches!(
            o,
            Op::Command {
                id: 4,
                command: nsh_core::Command::SetJsResponder { block: true }
            }
        )));
        assert!(ops.iter().any(|o| matches!(
            o,
            Op::Command {
                id: 1,
                command: nsh_core::Command::ClearJsResponder
            }
        )));
    }

    #[test]
    fn responder_events_carry_the_modifiers_held_at_the_press() {
        let host = Host::new().unwrap();
        host.eval_source(
            r#"
            import { element, append, spread } from "nsh:rt";
            import { PanResponder } from "nsh";
            const log = [];
            globalThis.log = log;
            const outer = element("view");
            const inner = element("view");
            append(outer, inner);
            const mods = (e) => {
                const m = e.nativeEvent.modifiers;
                return [m.control, m.alt, m.shift, m.platform].map(Number).join("");
            };
            const pan = PanResponder.create({
                onStartShouldSetPanResponder: () => true,
                onPanResponderGrant: (e) => log.push(`grant ${mods(e)}`),
                onPanResponderRelease: (e) => log.push(`release ${mods(e)}`),
            });
            spread(inner, pan.panHandlers);
            globalThis.keep = outer;
            "#,
        )
        .unwrap();
        let alt = |phase| {
            let mut e = touch(phase, 10.0, 10.0, 0.0);
            if let EventPayload::Touch(t) = &mut e {
                t.modifiers.alt = true;
                t.modifiers.shift = true;
            }
            e
        };
        host.dispatch_event(4, EventKind::Touch, &alt(TouchPhase::Start));
        host.dispatch_event(4, EventKind::Touch, &alt(TouchPhase::End));
        host.eval_source(r#"import { text } from "nsh:rt"; text(globalThis.log.join("|"));"#)
            .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let log = ops
            .iter()
            .rev()
            .find_map(|o| match o {
                Op::CreateText { text, .. } => Some(text.clone()),
                _ => None,
            })
            .unwrap();
        assert_eq!(log, "grant 0110|release 0110");
    }
}