| 66 | //============================================================================== |
| 67 | |
| 68 | inline void registerConsoleFunctions (choc::javascript::Context& context, |
| 69 | std::function<void(std::string_view, LoggingLevel)> handleOutput) |
| 70 | { |
| 71 | if (! handleOutput) |
| 72 | { |
| 73 | handleOutput = [] (std::string_view content, LoggingLevel level) |
| 74 | { |
| 75 | if (level == LoggingLevel::debug) |
| 76 | std::cerr << content << std::endl; |
| 77 | else |
| 78 | std::cout << content << std::endl; |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | context.registerFunction ("_choc_console_log", |
| 83 | [handleOutput] (ArgumentList args) mutable -> choc::value::Value |
| 84 | { |
| 85 | if (auto content = args[0]) |
| 86 | { |
| 87 | auto level = LoggingLevel::log; |
| 88 | |
| 89 | switch (args.get<int> (1)) |
| 90 | { |
| 91 | case 0: level = LoggingLevel::log; break; |
| 92 | case 1: level = LoggingLevel::info; break; |
| 93 | case 2: level = LoggingLevel::warn; break; |
| 94 | case 3: level = LoggingLevel::error; break; |
| 95 | case 4: level = LoggingLevel::debug; break; |
| 96 | } |
| 97 | |
| 98 | handleOutput (content->isString() ? content->toString() |
| 99 | : choc::json::toString (*content), level); |
| 100 | } |
| 101 | |
| 102 | return {}; |
| 103 | }); |
| 104 | |
| 105 | context.run (R"( |
| 106 | console = { |
| 107 | log: function() { for (let a of arguments) _choc_console_log (a, 0); }, |
| 108 | info: function() { for (let a of arguments) _choc_console_log (a, 1); }, |
| 109 | warn: function() { for (let a of arguments) _choc_console_log (a, 2); }, |
| 110 | error: function() { for (let a of arguments) _choc_console_log (a, 3); }, |
| 111 | debug: function() { for (let a of arguments) _choc_console_log (a, 4); } |
| 112 | }; |
| 113 | )"); |
| 114 | } |
| 115 | |
| 116 | } // namespace choc::javascript |
| 117 | |