Repository navigation
Expand file tree
/
Copy pathruntime.cpp
More file actions
2349 lines (2166 loc) · 76.7 KB
/
Copy pathruntime.cpp
File metadata and controls
2349 lines (2166 loc) · 76.7 KB
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
#include "internal.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <source_location>
#include <typeinfo>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <huxerui/task.h>
#include "embedded_js.h"
#include "props.h"
namespace huxerui::tsx::detail {
namespace {
constexpr std::string_view kJsxRuntimeModule =
"export { jsx, jsxs, Fragment } from \"@huxerui/tsx\";\n";
quickjs::RuntimeOptions MakeEngineOptions(
const RuntimeOptions& source,
std::shared_ptr<ExecutionBudget> budget
) {
budget->user_interrupt = source.should_interrupt;
quickjs::RuntimeOptions options;
options.memory_limit_bytes = source.memory_limit_bytes;
options.stack_limit_bytes = source.stack_limit_bytes;
options.should_interrupt = [budget = std::move(budget)]() {
if (budget->Expired()) {
return true;
}
return budget->user_interrupt && budget->user_interrupt();
};
return options;
}
quickjs::EvaluateOptions MakeEvaluateOptions(const RuntimeOptions& source) {
quickjs::EvaluateOptions options;
options.time_limit = source.evaluation_time_limit;
return options;
}
template <class T> State<T> AcquireStateCell(T initial) {
using Cell = huxerui::detail::StateCell<T>;
auto candidate = std::make_shared<Cell>(std::move(initial));
const auto acquire = &::huxerui::detail::UseStateCell;
auto cell = acquire(
typeid(T),
std::source_location::current(),
std::move(candidate)
);
return State<T>(std::static_pointer_cast<Cell>(std::move(cell)));
}
State<JsSlot> AcquireSlotState(quickjs::Value initial) {
return AcquireStateCell(JsSlot{std::move(initial)});
}
huxerui::ViewHandle AcquireViewHandle(
std::source_location location = std::source_location::current()
) {
const auto acquire = &huxerui::UseViewHandle;
return acquire(location);
}
huxerui::ScrollController AcquireScrollController(float initial_offset) {
const auto acquire = &huxerui::UseScrollController;
return acquire(initial_offset, std::source_location::current());
}
huxerui::ToastHandle AcquireToastHandle() {
const auto acquire = &huxerui::UseToast;
return acquire();
}
huxerui::DialogHandle AcquireDialogHandle() {
const auto acquire = &huxerui::UseDialog;
return acquire();
}
huxerui::MenuHandle AcquireMenuHandle() {
const auto acquire = &huxerui::UseMenu;
return acquire();
}
huxerui::SnackBarHandle AcquireSnackBarHandle() {
const auto acquire = &huxerui::UseSnackBar;
return acquire();
}
huxerui::BottomSheetHandle AcquireBottomSheetHandle() {
const auto acquire = &huxerui::UseBottomSheet;
return acquire();
}
huxerui::PopupHandle AcquirePopupHandle() {
const auto acquire = &huxerui::UsePopup;
return acquire();
}
std::string RevisionName(std::string_view name, std::uint64_t revision) {
const auto dot = name.rfind('.');
const std::string suffix = ".r" + std::to_string(revision);
if (dot == std::string_view::npos) {
return std::string(name) + suffix;
}
return std::string(name.substr(0, dot)) + suffix + std::string(name.substr(dot));
}
const char* ErrorCodeName(quickjs::ErrorCode code) noexcept {
switch (code) {
case quickjs::ErrorCode::Exception:
return "Exception";
case quickjs::ErrorCode::Syntax:
return "Syntax";
case quickjs::ErrorCode::OutOfMemory:
return "OutOfMemory";
case quickjs::ErrorCode::StackOverflow:
return "StackOverflow";
case quickjs::ErrorCode::Interrupted:
return "Interrupted";
case quickjs::ErrorCode::Module:
return "Module";
case quickjs::ErrorCode::Type:
return "Type";
case quickjs::ErrorCode::Closed:
return "Closed";
case quickjs::ErrorCode::Unsupported:
return "Unsupported";
}
return "Unknown";
}
const char* PhaseName(DiagnosticPhase phase) noexcept {
switch (phase) {
case DiagnosticPhase::Load:
return "load";
case DiagnosticPhase::Reload:
return "reload";
case DiagnosticPhase::Render:
return "render";
case DiagnosticPhase::Effect:
return "effect";
case DiagnosticPhase::Event:
return "event";
case DiagnosticPhase::Evaluation:
return "evaluation";
case DiagnosticPhase::Timer:
return "timer";
case DiagnosticPhase::Unknown:
return "unknown";
}
return "unknown";
}
std::string FormatDiagnostic(const Diagnostic& diagnostic) {
std::string text;
text += PhaseName(diagnostic.phase);
text += " [";
text += ErrorCodeName(diagnostic.code);
text += "]: ";
text += diagnostic.operation;
if (!diagnostic.message.empty()) {
text += ": ";
text += diagnostic.message;
}
if (!diagnostic.filename.empty()) {
text += " (";
text += diagnostic.filename;
if (diagnostic.line > 0) {
text += ":";
text += std::to_string(diagnostic.line);
if (diagnostic.column > 0) {
text += ":";
text += std::to_string(diagnostic.column);
}
}
text += ")";
}
if (!diagnostic.stack.empty()) {
text += "\n";
text += diagnostic.stack;
}
if (!diagnostic.component_stack.empty()) {
text += "\ncomponent stack: ";
text += diagnostic.component_stack;
}
return text;
}
std::uint64_t FunctionKey(const quickjs::Value& function) {
const auto source = function.ToString();
if (source.Succeeded()) {
return static_cast<std::uint64_t>(std::hash<std::string>{}(source.Value()));
}
return 0;
}
std::string FunctionName(const quickjs::Value& function) {
const auto name = function.GetProperty("name");
if (name.Succeeded()) {
const auto text = name.Value().ToString();
if (text.Succeeded() && !text.Value().empty()) {
return text.Value();
}
}
return "<anonymous>";
}
std::string FirstLine(std::string_view text) {
const auto newline = text.find('\n');
return std::string(text.substr(0, newline));
}
class ComponentPathScope final {
public:
ComponentPathScope(RuntimeImpl& runtime, std::string_view path)
: runtime_(runtime), previous_(runtime.ActiveComponentPath()) {
runtime_.SetActiveComponentPath(std::string(path));
}
~ComponentPathScope() { runtime_.SetActiveComponentPath(std::move(previous_)); }
ComponentPathScope(const ComponentPathScope&) = delete;
ComponentPathScope& operator=(const ComponentPathScope&) = delete;
private:
RuntimeImpl& runtime_;
std::string previous_;
};
class OperationBudgetScope final {
public:
OperationBudgetScope(ExecutionBudget& budget, std::chrono::milliseconds limit)
: budget_(budget), previous_active_(budget.active), previous_deadline_(budget.deadline) {
if (limit.count() > 0) {
budget_.active = true;
budget_.deadline = std::chrono::steady_clock::now() + limit;
}
}
~OperationBudgetScope() {
budget_.active = previous_active_;
budget_.deadline = previous_deadline_;
}
OperationBudgetScope(const OperationBudgetScope&) = delete;
OperationBudgetScope& operator=(const OperationBudgetScope&) = delete;
private:
ExecutionBudget& budget_;
bool previous_active_ = false;
std::chrono::steady_clock::time_point previous_deadline_{};
};
class CurrentFrameGuard final {
public:
CurrentFrameGuard(RuntimeImpl& runtime, RuntimeImpl::RenderFrame& frame)
: runtime_(runtime), previous_(runtime.CurrentFrame()) {
runtime_.SetCurrentFrame(&frame);
}
~CurrentFrameGuard() { runtime_.SetCurrentFrame(previous_); }
CurrentFrameGuard(const CurrentFrameGuard&) = delete;
CurrentFrameGuard& operator=(const CurrentFrameGuard&) = delete;
private:
RuntimeImpl& runtime_;
RuntimeImpl::RenderFrame* previous_ = nullptr;
};
std::vector<huxerui::MenuEntry> BuildMenuEntries(
RuntimeImpl& runtime,
const quickjs::Value& entries_value,
std::string_view component
) {
std::vector<huxerui::MenuEntry> entries;
if (!entries_value.IsArray()) {
return entries;
}
const auto length = entries_value.Length();
if (!length.Succeeded() || length.Value() < 0) {
return entries;
}
entries.reserve(static_cast<std::size_t>(length.Value()));
for (std::int64_t index = 0; index < length.Value(); ++index) {
const auto value = entries_value.GetElement(static_cast<std::uint32_t>(index));
if (!value.Succeeded() || !value.Value().IsObject()) {
continue;
}
if (BoolProperty(value.Value(), "section").value_or(false)) {
entries.emplace_back(huxerui::MenuSection{});
continue;
}
const auto label = StringProperty(value.Value(), "label");
if (!label || label->empty()) {
continue;
}
auto callback = std::function<void()>([] {});
if (const auto function = Property(value.Value(), "onSelect");
function && function->IsFunction()) {
callback = [impl = &runtime, function = *function, component]() {
impl->InvokeHandler(function, {}, DiagnosticPhase::Event, component);
};
}
huxerui::MenuItem item(*label, std::move(callback));
if (const auto disabled = BoolProperty(value.Value(), "disabled"); disabled) {
item = std::move(item).Enabled(!*disabled);
}
if (const auto checked = BoolProperty(value.Value(), "checked"); checked) {
item = std::move(item).Checked(*checked);
}
entries.emplace_back(std::move(item));
}
return entries;
}
} // namespace
struct TimerRecord {
std::uint64_t id = 0;
bool repeating = false;
bool cancelled = false;
std::chrono::duration<double, std::milli> delay{0};
quickjs::Value callback;
std::string component_stack;
huxerui::TaskHandle handle;
};
bool JsDeps::operator==(const JsDeps& other) const {
if (always_run != other.always_run) {
return false;
}
if (values.size() != other.values.size()) {
return false;
}
for (std::size_t index = 0; index < values.size(); ++index) {
const auto equal = values[index].StrictEquals(other.values[index]);
if (!equal.Succeeded() || !equal.Value()) {
return false;
}
}
return true;
}
RuntimeImpl::RuntimeImpl(RuntimeOptions options_in)
: options(std::move(options_in)),
budget(std::make_shared<ExecutionBudget>()),
engine(MakeEngineOptions(options, budget)),
context_(engine) {
InstallHostFunctions();
InstallModuleLoader();
}
RuntimeImpl::~RuntimeImpl() {
for (const auto& task : async_tasks_) {
task.Cancel();
}
async_tasks_.clear();
CancelTimers();
}
void RuntimeImpl::InstallHostFunctions() {
auto install = [this](std::string_view name, quickjs::NativeFunction function, std::size_t arity) {
auto result = context_.SetGlobalFunction(name, std::move(function), arity);
if (!result.Succeeded()) {
throw std::runtime_error(
"huxerui::tsx could not install host function '" + std::string(name) +
"': " + result.Error().Message()
);
}
};
install("__huxerui_useState", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseState(owner, arguments);
}, 1);
install("__huxerui_stateValue", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostStateValue(owner, arguments);
}, 1);
install("__huxerui_setState", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostSetState(owner, arguments);
}, 2);
install("__huxerui_useRef", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseRef(owner, arguments);
}, 1);
install("__huxerui_useEffect", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseEffect(owner, arguments);
}, 2);
install("setTimeout", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostSetTimer(owner, arguments, false);
}, 2);
install("setInterval", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostSetTimer(owner, arguments, true);
}, 2);
install("clearTimeout", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostClearTimer(owner, arguments);
}, 1);
install("clearInterval", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostClearTimer(owner, arguments);
}, 1);
install("__huxerui_useFocusRequester", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseFocusRequester(owner, arguments);
}, 0);
install("__huxerui_requestFocus", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostRequestFocus(owner, arguments);
}, 1);
install("__huxerui_useScrollController", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseScrollController(owner, arguments);
}, 1);
install("__huxerui_scrollTo", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostScrollTo(owner, arguments);
}, 2);
install("__huxerui_scrollBy", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostScrollBy(owner, arguments);
}, 2);
install("__huxerui_scrollToItem", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostScrollToItem(owner, arguments);
}, 3);
install("__huxerui_scrollOffset", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostScrollOffset(owner, arguments);
}, 1);
install("__huxerui_scrollMetrics", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostScrollMetrics(owner, arguments);
}, 1);
install("__huxerui_useToast", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseToast(owner, arguments);
}, 0);
install("__huxerui_showToast", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowToast(owner, arguments);
}, 3);
install("__huxerui_dismissToast", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissToast(owner, arguments);
}, 2);
install("__huxerui_useDialog", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseDialog(owner, arguments);
}, 0);
install("__huxerui_showDialog", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowDialog(owner, arguments);
}, 2);
install("__huxerui_showDialogContent", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowDialogContent(owner, arguments);
}, 3);
install("__huxerui_dismissDialog", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissDialog(owner, arguments);
}, 2);
install("__huxerui_useMenu", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseMenu(owner, arguments);
}, 0);
install("__huxerui_showMenu", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowMenu(owner, arguments);
}, 4);
install("__huxerui_showMenuAnchored", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowMenuAnchored(owner, arguments);
}, 2);
install("__huxerui_dismissMenu", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissMenu(owner, arguments);
}, 2);
install("__huxerui_useSnackBar", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseSnackBar(owner, arguments);
}, 0);
install("__huxerui_showSnackBar", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowSnackBar(owner, arguments);
}, 5);
install("__huxerui_dismissSnackBar", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissSnackBar(owner, arguments);
}, 2);
install("__huxerui_useBottomSheet", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUseBottomSheet(owner, arguments);
}, 0);
install("__huxerui_showBottomSheet", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowBottomSheet(owner, arguments);
}, 3);
install("__huxerui_dismissBottomSheet", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissBottomSheet(owner, arguments);
}, 2);
install("__huxerui_usePopup", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostUsePopup(owner, arguments);
}, 0);
install("__huxerui_showPopup", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostShowPopup(owner, arguments);
}, 3);
install("__huxerui_dismissPopup", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostDismissPopup(owner, arguments);
}, 2);
install("__huxerui_clipboardRead", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostClipboardRead(owner, arguments);
}, 0);
install("__huxerui_clipboardWrite", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostClipboardWrite(owner, arguments);
}, 1);
install("__huxerui_clipboardAvailable", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostClipboardAvailable(owner, arguments);
}, 0);
install("__huxerui_fetch", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostFetch(owner, arguments);
}, 4);
install("__huxerui_quitApplication", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostQuitApplication(owner, arguments);
}, 0);
install("__huxerui_applicationLifecycle", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostApplicationLifecycle(owner, arguments);
}, 0);
install("__huxerui_paintFillRect", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintFillRect(owner, arguments);
}, 7);
install("__huxerui_paintStrokeRect", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintStrokeRect(owner, arguments);
}, 8);
install("__huxerui_paintLine", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintLine(owner, arguments);
}, 7);
install("__huxerui_paintCircle", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintCircle(owner, arguments);
}, 5);
install("__huxerui_paintArc", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintArc(owner, arguments);
}, 8);
install("__huxerui_paintPushClipRect", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintPushClipRect(owner, arguments);
}, 6);
install("__huxerui_paintPopClip", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintPopClip(owner, arguments);
}, 1);
install("__huxerui_paintPushTranslate", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintPushTranslate(owner, arguments);
}, 3);
install("__huxerui_paintPopTransform", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
return HostPaintPopTransform(owner, arguments);
}, 1);
install("__huxerui_log", [this](quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
if (arguments.size() < 2) {
return owner.Undefined();
}
const auto level = arguments[0].ToString();
const auto message = arguments[1].ToString();
if (level.Succeeded() && message.Succeeded()) {
const std::string name = level.Value();
LogLevel parsed = LogLevel::Info;
if (name == "debug") {
parsed = LogLevel::Debug;
} else if (name == "warn") {
parsed = LogLevel::Warn;
} else if (name == "error") {
parsed = LogLevel::Error;
}
Log(parsed, message.Value());
}
return owner.Undefined();
}, 2);
}
void RuntimeImpl::InstallModuleLoader() {
context_.SetModuleLoader([this](std::string_view name) -> quickjs::Result<std::string> {
if (name == "@huxerui/tsx" || name == "@huxerui/tsx/index") {
return quickjs::Result<std::string>::Success(std::string(kTsxRuntimeModule));
}
if (name == "@huxerui/tsx/jsx-runtime") {
return quickjs::Result<std::string>::Success(std::string(kJsxRuntimeModule));
}
if (user_loader_) {
return user_loader_(name);
}
if (!options.module_root.empty()) {
const std::filesystem::path relative(name.starts_with('/') ? name.substr(1) : name);
const auto path = options.module_root / relative;
std::ifstream stream(path, std::ios::binary);
if (stream) {
std::ostringstream buffer;
buffer << stream.rdbuf();
return quickjs::Result<std::string>::Success(buffer.str());
}
}
return quickjs::Result<std::string>::Failure(quickjs::Error{
quickjs::ErrorCode::Module,
"Cannot resolve module '" + std::string(name) +
"'. Bundle the application or provide Runtime::SetModuleLoader().",
std::string(name),
});
});
}
void RuntimeImpl::ReportError(
DiagnosticPhase phase,
std::string_view operation,
const quickjs::Error& error,
std::string_view component_stack
) {
Diagnostic diagnostic;
diagnostic.phase = phase;
diagnostic.code = error.Code();
diagnostic.operation = std::string(operation);
diagnostic.message = error.Message();
diagnostic.filename = error.Filename();
diagnostic.line = error.Line();
diagnostic.column = error.Column();
diagnostic.generated_filename = error.Filename();
diagnostic.generated_line = error.Line();
diagnostic.generated_column = error.Column();
diagnostic.stack = error.Stack();
diagnostic.component_stack = std::string(component_stack);
const bool map_applies = source_map_ && !source_map_module_.empty()
&& error.Filename() == source_map_module_;
if (map_applies) {
if (error.Line() > 0) {
if (const auto mapped = source_map_->Find(error.Line(), error.Column(), source_map_base_)) {
diagnostic.filename = mapped->filename;
diagnostic.line = mapped->line;
diagnostic.column = mapped->column;
}
}
diagnostic.stack = RemapStack(
diagnostic.stack,
source_map_module_,
*source_map_,
source_map_base_
);
}
ReportDiagnostic(std::move(diagnostic));
}
void RuntimeImpl::ReportMessage(
DiagnosticPhase phase,
std::string_view operation,
std::string_view message,
std::string_view component_stack
) {
Diagnostic diagnostic;
diagnostic.phase = phase;
diagnostic.code = quickjs::ErrorCode::Exception;
diagnostic.operation = std::string(operation);
diagnostic.message = std::string(message);
diagnostic.component_stack = std::string(component_stack);
ReportDiagnostic(std::move(diagnostic));
}
void RuntimeImpl::ReportDiagnostic(Diagnostic diagnostic) {
diagnostic.description = FormatDiagnostic(diagnostic);
last_diagnostic_ = diagnostic;
if (options.on_diagnostic) {
try {
options.on_diagnostic(diagnostic);
} catch (...) {
// A diagnostic sink must not mask the original JavaScript failure.
}
}
if (options.on_log) {
try {
options.on_log(LogLevel::Error, diagnostic.description);
} catch (...) {
}
}
if (options.on_error) {
try {
options.on_error(diagnostic.description);
} catch (...) {
}
}
}
void RuntimeImpl::Log(LogLevel level, std::string_view message) {
if (options.on_log) {
try {
options.on_log(level, message);
} catch (...) {
}
}
}
View RuntimeImpl::ApplyMenuAnchor(View view, const quickjs::Value& props) {
const auto anchor = Property(props, "menuAnchor");
if (!anchor || !anchor->IsObject()) {
return view;
}
const auto id = NumberProperty(*anchor, "id");
if (!id || !std::isfinite(*id)) {
return view;
}
const auto found = menu_handles_.find(static_cast<std::uint64_t>(*id));
if (found == menu_handles_.end()) {
return view;
}
return std::move(view).With(found->second.anchor);
}
View RuntimeImpl::ApplyPopupAnchor(View view, const quickjs::Value& props) {
const auto anchor = Property(props, "popupAnchor");
if (!anchor || !anchor->IsObject()) {
return view;
}
const auto id = NumberProperty(*anchor, "id");
if (!id || !std::isfinite(*id)) {
return view;
}
const auto found = popup_handles_.find(static_cast<std::uint64_t>(*id));
if (found == popup_handles_.end()) {
return view;
}
return std::move(view).With(found->second.anchor);
}
View RuntimeImpl::ApplyFocusRef(View view, const quickjs::Value& props) {
const auto ref = Property(props, "ref");
const auto focus_ref = ref ? ref : Property(props, "focusRef");
if (!focus_ref || !focus_ref->IsObject()) {
return view;
}
const auto id = NumberProperty(*focus_ref, "id");
if (!id || !std::isfinite(*id)) {
return view;
}
const auto found = focus_requesters_.find(static_cast<std::uint64_t>(*id));
if (found == focus_requesters_.end()) {
return view;
}
return std::move(view).With(found->second);
}
std::string RuntimeImpl::ComponentPath(const ComponentInstance& instance) const {
std::vector<std::string> chain;
chain.push_back(instance.name);
auto parent = instance.parent.lock();
while (parent) {
chain.push_back(parent->name);
parent = parent->parent.lock();
}
std::string path;
for (auto iterator = chain.rbegin(); iterator != chain.rend(); ++iterator) {
if (!path.empty()) {
path += " > ";
}
path += *iterator;
}
return path;
}
std::uint64_t RuntimeImpl::NextComponentKey(const quickjs::Value& function) {
const auto hash = FunctionKey(function);
std::uint32_t occurrence = 0;
if (current_frame_ != nullptr) {
occurrence = current_frame_->component_occurrences[hash]++;
} else {
occurrence = root_component_occurrences_[hash]++;
}
return hash ^ (static_cast<std::uint64_t>(occurrence) * 0x9E3779B97F4A7C15ULL);
}
std::string RuntimeImpl::CurrentComponentPath() const {
if (current_frame_ != nullptr && current_frame_->instance != nullptr) {
return ComponentPath(*current_frame_->instance);
}
return active_component_path_;
}
void RuntimeImpl::InvokeHandler(
const quickjs::Value& function,
std::span<const quickjs::Value> arguments,
DiagnosticPhase phase,
std::string_view component_stack
) {
if (!function.IsFunction()) {
return;
}
ComponentPathScope path_scope(*this, component_stack);
OperationBudgetScope budget_scope(*budget, options.operation_time_limit);
const auto result = function.Call(arguments);
if (!result.Succeeded()) {
ReportError(phase, "event handler", result.Error(), component_stack);
}
}
bool RuntimeImpl::InvokeDecisionHandler(
const quickjs::Value& function,
std::span<const quickjs::Value> arguments,
DiagnosticPhase phase,
std::string_view component_stack
) {
if (!function.IsFunction()) {
return false;
}
ComponentPathScope path_scope(*this, component_stack);
OperationBudgetScope budget_scope(*budget, options.operation_time_limit);
const auto result = function.Call(arguments);
if (!result.Succeeded()) {
ReportError(phase, "event handler", result.Error(), component_stack);
return false;
}
const auto truthy = result.Value().ToBoolean();
return truthy.Succeeded() && truthy.Value();
}
View RuntimeImpl::ErrorView(std::string_view message) const {
return Text("TSX error: " + FirstLine(message));
}
quickjs::Value RuntimeImpl::HostUseState(quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
auto* frame = current_frame_;
if (frame == nullptr || frame->instance == nullptr) {
throw std::runtime_error("useState() was called outside a TSX component render");
}
auto& instance = *frame->instance;
const std::size_t index = frame->next_hook++;
quickjs::Value initial = arguments.empty() ? owner.Undefined() : arguments[0];
if (index >= instance.states.size() && initial.IsFunction()) {
OperationBudgetScope budget_scope(*budget, options.operation_time_limit);
const auto produced = initial.Call();
if (!produced.Succeeded()) {
throw std::runtime_error(
"useState() initializer failed: " + produced.Error().Message()
);
}
initial = produced.Value();
}
if (index >= instance.states.size()) {
const std::uint64_t handle = next_handle++;
instance.states.push_back(AcquireSlotState(initial));
instance.handles.push_back(handle);
handles.emplace(handle, std::make_pair(std::weak_ptr<ComponentInstance>(current_frame_->owner), index));
} else {
instance.states[index] = AcquireSlotState(owner.Undefined());
}
return owner.Number(static_cast<double>(instance.handles[index]));
}
quickjs::Value RuntimeImpl::HostStateValue(quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
if (arguments.empty()) {
return owner.Undefined();
}
const auto number = arguments[0].ToNumber();
if (!number.Succeeded()) {
return owner.Undefined();
}
const auto handle = static_cast<std::uint64_t>(number.Value());
const auto found = handles.find(handle);
if (found == handles.end()) {
return owner.Undefined();
}
const auto instance = found->second.first.lock();
if (!instance || found->second.second >= instance->states.size()) {
handles.erase(found);
return owner.Undefined();
}
const auto& slot = instance->states[found->second.second].Get();
return slot.value.IsUndefined() ? owner.Undefined() : slot.value;
}
quickjs::Value RuntimeImpl::HostSetState(quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
if (arguments.size() < 2) {
return owner.Undefined();
}
const auto number = arguments[0].ToNumber();
if (!number.Succeeded()) {
return owner.Undefined();
}
const auto handle = static_cast<std::uint64_t>(number.Value());
const auto found = handles.find(handle);
if (found == handles.end()) {
return owner.Undefined();
}
const auto instance = found->second.first.lock();
if (!instance || found->second.second >= instance->states.size()) {
handles.erase(found);
return owner.Undefined();
}
instance->states[found->second.second] = JsSlot{arguments[1]};
return owner.Undefined();
}
quickjs::Value RuntimeImpl::HostUseRef(quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
auto* frame = current_frame_;
if (frame == nullptr || frame->instance == nullptr) {
throw std::runtime_error("useRef() was called outside a TSX component render");
}
auto& instance = *frame->instance;
const std::size_t index = frame->next_hook++;
if (index >= instance.states.size()) {
auto object = owner.NewObject();
if (!object.Succeeded()) {
throw std::runtime_error(object.Error().Message());
}
const quickjs::Value initial = arguments.empty() ? owner.Undefined() : arguments[0];
auto assigned = object.Value().SetProperty("current", initial);
if (!assigned.Succeeded()) {
throw std::runtime_error(assigned.Error().Message());
}
const std::uint64_t handle = next_handle++;
instance.states.push_back(AcquireSlotState(object.Value()));
instance.handles.push_back(handle);
handles.emplace(handle, std::make_pair(std::weak_ptr<ComponentInstance>(current_frame_->owner), index));
} else {
instance.states[index] = AcquireSlotState(owner.Undefined());
}
const auto& slot = instance.states[index].Get();
return slot.value.IsUndefined() ? owner.Undefined() : slot.value;
}
quickjs::Value RuntimeImpl::HostUseEffect(quickjs::Context& owner, std::span<const quickjs::Value> arguments) {
if (arguments.empty() || !arguments[0].IsFunction()) {
throw std::runtime_error("useEffect() requires a function");
}
JsDeps deps;
if (arguments.size() < 2 || arguments[1].IsNull() || arguments[1].IsUndefined()) {
deps.always_run = next_effect_dependency_++;
} else if (arguments[1].IsArray()) {
const auto length = arguments[1].Length();
if (length.Succeeded()) {
deps.values.reserve(static_cast<std::size_t>(length.Value()));
for (std::int64_t index = 0; index < length.Value(); ++index) {
auto element = arguments[1].GetElement(static_cast<std::uint32_t>(index));
if (element.Succeeded()) {
deps.values.push_back(element.Value());
}
}
}
} else {
throw std::runtime_error("useEffect() dependencies must be an array, null, or undefined");
}
const quickjs::Value effect = arguments[0];
const std::string component = CurrentComponentPath();
huxerui::Lifecycle(
[impl = this, effect, component]() -> std::function<void()> {
ComponentPathScope path_scope(*impl, component);
OperationBudgetScope budget_scope(*impl->budget, impl->options.operation_time_limit);
const auto result = effect.Call();
if (!result.Succeeded()) {
impl->ReportError(DiagnosticPhase::Effect, "useEffect", result.Error(), component);
return std::function<void()>([] {});
}
const auto cleanup = result.Value();
if (!cleanup.IsFunction()) {
return std::function<void()>([] {});
}
return std::function<void()>([impl, cleanup, component]() {
impl->InvokeHandler(cleanup, {}, DiagnosticPhase::Effect, component);
});
},
std::move(deps)
);
return owner.Undefined();
}
quickjs::Value RuntimeImpl::HostSetTimer(
quickjs::Context& owner,
std::span<const quickjs::Value> arguments,
bool repeating
) {
if (arguments.empty() || !arguments[0].IsFunction()) {
throw std::runtime_error(
std::string(repeating ? "setInterval" : "setTimeout") +
"() requires a callback function"
);
}
double milliseconds = 0.0;
if (arguments.size() > 1) {
const auto number = arguments[1].ToNumber();
if (!number.Succeeded()) {
throw std::runtime_error("Timer delay must be a number");
}
if (std::isfinite(number.Value()) && number.Value() > 0.0) {
milliseconds = std::min(number.Value(), 86'400'000.0);
}
}
auto timer = std::make_shared<TimerRecord>();
timer->id = next_timer_id_++;
timer->repeating = repeating;
timer->delay = std::chrono::duration<double, std::milli>(milliseconds);
timer->callback = arguments[0];
timer->component_stack = CurrentComponentPath();
timers_.emplace(timer->id, timer);
try {
ScheduleTimer(timer);
} catch (const std::exception& error) {
timers_.erase(timer->id);
ReportMessage(
DiagnosticPhase::Timer,
repeating ? "setInterval" : "setTimeout",
error.what(),
timer->component_stack
);