state.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. // State management for Reflex web apps.
  2. import axios from "axios";
  3. import io from "socket.io-client";
  4. import JSON5 from "json5";
  5. import env from "$/env.json";
  6. import Cookies from "universal-cookie";
  7. import { useEffect, useRef, useState } from "react";
  8. import Router, { useRouter } from "next/router";
  9. import {
  10. initialEvents,
  11. initialState,
  12. onLoadInternalEvent,
  13. state_name,
  14. exception_state_name,
  15. } from "$/utils/context.js";
  16. import debounce from "$/utils/helpers/debounce";
  17. import throttle from "$/utils/helpers/throttle";
  18. // Endpoint URLs.
  19. const EVENTURL = env.EVENT;
  20. const UPLOADURL = env.UPLOAD;
  21. // These hostnames indicate that the backend and frontend are reachable via the same domain.
  22. const SAME_DOMAIN_HOSTNAMES = ["localhost", "0.0.0.0", "::", "0:0:0:0:0:0:0:0"];
  23. // Global variable to hold the token.
  24. let token;
  25. // Key for the token in the session storage.
  26. const TOKEN_KEY = "token";
  27. // create cookie instance
  28. const cookies = new Cookies();
  29. // Dictionary holding component references.
  30. export const refs = {};
  31. // Flag ensures that only one event is processing on the backend concurrently.
  32. let event_processing = false;
  33. // Array holding pending events to be processed.
  34. const event_queue = [];
  35. // Pending upload promises, by id
  36. const upload_controllers = {};
  37. /**
  38. * Generate a UUID (Used for session tokens).
  39. * Taken from: https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid
  40. * @returns A UUID.
  41. */
  42. export const generateUUID = () => {
  43. let d = new Date().getTime(),
  44. d2 = (performance && performance.now && performance.now() * 1000) || 0;
  45. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  46. let r = Math.random() * 16;
  47. if (d > 0) {
  48. r = (d + r) % 16 | 0;
  49. d = Math.floor(d / 16);
  50. } else {
  51. r = (d2 + r) % 16 | 0;
  52. d2 = Math.floor(d2 / 16);
  53. }
  54. return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
  55. });
  56. };
  57. /**
  58. * Get the token for the current session.
  59. * @returns The token.
  60. */
  61. export const getToken = () => {
  62. if (token) {
  63. return token;
  64. }
  65. if (typeof window !== "undefined") {
  66. if (!window.sessionStorage.getItem(TOKEN_KEY)) {
  67. window.sessionStorage.setItem(TOKEN_KEY, generateUUID());
  68. }
  69. token = window.sessionStorage.getItem(TOKEN_KEY);
  70. }
  71. return token;
  72. };
  73. /**
  74. * Get the URL for the backend server
  75. * @param url_str The URL string to parse.
  76. * @returns The given URL modified to point to the actual backend server.
  77. */
  78. export const getBackendURL = (url_str) => {
  79. // Get backend URL object from the endpoint.
  80. const endpoint = new URL(url_str);
  81. if (
  82. typeof window !== "undefined" &&
  83. SAME_DOMAIN_HOSTNAMES.includes(endpoint.hostname)
  84. ) {
  85. // Use the frontend domain to access the backend
  86. const frontend_hostname = window.location.hostname;
  87. endpoint.hostname = frontend_hostname;
  88. if (window.location.protocol === "https:") {
  89. if (endpoint.protocol === "ws:") {
  90. endpoint.protocol = "wss:";
  91. } else if (endpoint.protocol === "http:") {
  92. endpoint.protocol = "https:";
  93. }
  94. endpoint.port = ""; // Assume websocket is on https port via load balancer.
  95. }
  96. }
  97. return endpoint;
  98. };
  99. /**
  100. * Determine if any event in the event queue is stateful.
  101. *
  102. * @returns True if there's any event that requires state and False if none of them do.
  103. */
  104. export const isStateful = () => {
  105. if (event_queue.length === 0) {
  106. return false;
  107. }
  108. return event_queue.some((event) => event.name.startsWith("reflex___state"));
  109. };
  110. /**
  111. * Apply a delta to the state.
  112. * @param state The state to apply the delta to.
  113. * @param delta The delta to apply.
  114. */
  115. export const applyDelta = (state, delta) => {
  116. return { ...state, ...delta };
  117. };
  118. /**
  119. * Evaluate a dynamic component.
  120. * @param component The component to evaluate.
  121. * @returns The evaluated component.
  122. */
  123. export const evalReactComponent = async (component) => {
  124. if (!window.React && window.__reflex) {
  125. window.React = window.__reflex.react;
  126. }
  127. const encodedJs = encodeURIComponent(component);
  128. const dataUri = "data:text/javascript;charset=utf-8," + encodedJs;
  129. const module = await eval(`import(dataUri)`);
  130. return module.default;
  131. };
  132. /**
  133. * Only Queue and process events when websocket connection exists.
  134. * @param event The event to queue.
  135. * @param socket The socket object to send the event on.
  136. *
  137. * @returns Adds event to queue and processes it if websocket exits, does nothing otherwise.
  138. */
  139. export const queueEventIfSocketExists = async (events, socket) => {
  140. if (!socket) {
  141. return;
  142. }
  143. await queueEvents(events, socket);
  144. };
  145. /**
  146. * Handle frontend event or send the event to the backend via Websocket.
  147. * @param event The event to send.
  148. * @param socket The socket object to send the event on.
  149. *
  150. * @returns True if the event was sent, false if it was handled locally.
  151. */
  152. export const applyEvent = async (event, socket) => {
  153. // Handle special events
  154. if (event.name == "_redirect") {
  155. if (event.payload.external) {
  156. window.open(event.payload.path, "_blank");
  157. } else if (event.payload.replace) {
  158. Router.replace(event.payload.path);
  159. } else {
  160. Router.push(event.payload.path);
  161. }
  162. return false;
  163. }
  164. if (event.name == "_remove_cookie") {
  165. cookies.remove(event.payload.key, { ...event.payload.options });
  166. queueEventIfSocketExists(initialEvents(), socket);
  167. return false;
  168. }
  169. if (event.name == "_clear_local_storage") {
  170. localStorage.clear();
  171. queueEventIfSocketExists(initialEvents(), socket);
  172. return false;
  173. }
  174. if (event.name == "_remove_local_storage") {
  175. localStorage.removeItem(event.payload.key);
  176. queueEventIfSocketExists(initialEvents(), socket);
  177. return false;
  178. }
  179. if (event.name == "_clear_session_storage") {
  180. sessionStorage.clear();
  181. queueEvents(initialEvents(), socket);
  182. return false;
  183. }
  184. if (event.name == "_remove_session_storage") {
  185. sessionStorage.removeItem(event.payload.key);
  186. queueEvents(initialEvents(), socket);
  187. return false;
  188. }
  189. if (event.name == "_download") {
  190. const a = document.createElement("a");
  191. a.hidden = true;
  192. // Special case when linking to uploaded files
  193. a.href = event.payload.url.replace(
  194. "${getBackendURL(env.UPLOAD)}",
  195. getBackendURL(env.UPLOAD)
  196. );
  197. a.download = event.payload.filename;
  198. a.click();
  199. a.remove();
  200. return false;
  201. }
  202. if (event.name == "_set_focus") {
  203. const ref =
  204. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  205. ref.current.focus();
  206. return false;
  207. }
  208. if (event.name == "_set_value") {
  209. const ref =
  210. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  211. if (ref.current) {
  212. ref.current.value = event.payload.value;
  213. }
  214. return false;
  215. }
  216. if (
  217. event.name == "_call_function" &&
  218. typeof event.payload.function !== "string"
  219. ) {
  220. try {
  221. const eval_result = event.payload.function();
  222. if (event.payload.callback) {
  223. if (!!eval_result && typeof eval_result.then === "function") {
  224. event.payload.callback(await eval_result);
  225. } else {
  226. event.payload.callback(eval_result);
  227. }
  228. }
  229. } catch (e) {
  230. console.log("_call_function", e);
  231. if (window && window?.onerror) {
  232. window.onerror(e.message, null, null, null, e);
  233. }
  234. }
  235. return false;
  236. }
  237. if (event.name == "_call_script" || event.name == "_call_function") {
  238. try {
  239. const eval_result =
  240. event.name == "_call_script"
  241. ? eval(event.payload.javascript_code)
  242. : eval(event.payload.function)();
  243. if (event.payload.callback) {
  244. if (!!eval_result && typeof eval_result.then === "function") {
  245. eval(event.payload.callback)(await eval_result);
  246. } else {
  247. eval(event.payload.callback)(eval_result);
  248. }
  249. }
  250. } catch (e) {
  251. console.log("_call_script", e);
  252. if (window && window?.onerror) {
  253. window.onerror(e.message, null, null, null, e);
  254. }
  255. }
  256. return false;
  257. }
  258. // Update token and router data (if missing).
  259. event.token = getToken();
  260. if (
  261. event.router_data === undefined ||
  262. Object.keys(event.router_data).length === 0
  263. ) {
  264. event.router_data = (({ pathname, query, asPath }) => ({
  265. pathname,
  266. query,
  267. asPath,
  268. }))(Router);
  269. }
  270. // Send the event to the server.
  271. if (socket) {
  272. socket.emit(
  273. "event",
  274. JSON.stringify(event, (k, v) => (v === undefined ? null : v))
  275. );
  276. return true;
  277. }
  278. return false;
  279. };
  280. /**
  281. * Send an event to the server via REST.
  282. * @param event The current event.
  283. * @param socket The socket object to send the response event(s) on.
  284. *
  285. * @returns Whether the event was sent.
  286. */
  287. export const applyRestEvent = async (event, socket) => {
  288. let eventSent = false;
  289. if (event.handler === "uploadFiles") {
  290. if (event.payload.files === undefined || event.payload.files.length === 0) {
  291. // Submit the event over the websocket to trigger the event handler.
  292. return await applyEvent(Event(event.name), socket);
  293. }
  294. // Start upload, but do not wait for it, which would block other events.
  295. uploadFiles(
  296. event.name,
  297. event.payload.files,
  298. event.payload.upload_id,
  299. event.payload.on_upload_progress,
  300. socket
  301. );
  302. return false;
  303. }
  304. return eventSent;
  305. };
  306. /**
  307. * Queue events to be processed and trigger processing of queue.
  308. * @param events Array of events to queue.
  309. * @param socket The socket object to send the event on.
  310. */
  311. export const queueEvents = async (events, socket) => {
  312. event_queue.push(...events);
  313. await processEvent(socket.current);
  314. };
  315. /**
  316. * Process an event off the event queue.
  317. * @param socket The socket object to send the event on.
  318. */
  319. export const processEvent = async (socket) => {
  320. // Only proceed if the socket is up and no event in the queue uses state, otherwise we throw the event into the void
  321. if (!socket && isStateful()) {
  322. return;
  323. }
  324. // Only proceed if we're not already processing an event.
  325. if (event_queue.length === 0 || event_processing) {
  326. return;
  327. }
  328. // Set processing to true to block other events from being processed.
  329. event_processing = true;
  330. // Apply the next event in the queue.
  331. const event = event_queue.shift();
  332. let eventSent = false;
  333. // Process events with handlers via REST and all others via websockets.
  334. if (event.handler) {
  335. eventSent = await applyRestEvent(event, socket);
  336. } else {
  337. eventSent = await applyEvent(event, socket);
  338. }
  339. // If no event was sent, set processing to false.
  340. if (!eventSent) {
  341. event_processing = false;
  342. // recursively call processEvent to drain the queue, since there is
  343. // no state update to trigger the useEffect event loop.
  344. await processEvent(socket);
  345. }
  346. };
  347. /**
  348. * Connect to a websocket and set the handlers.
  349. * @param socket The socket object to connect.
  350. * @param dispatch The function to queue state update
  351. * @param transports The transports to use.
  352. * @param setConnectErrors The function to update connection error value.
  353. * @param client_storage The client storage object from context.js
  354. */
  355. export const connect = async (
  356. socket,
  357. dispatch,
  358. transports,
  359. setConnectErrors,
  360. client_storage = {}
  361. ) => {
  362. // Get backend URL object from the endpoint.
  363. const endpoint = getBackendURL(EVENTURL);
  364. // Create the socket.
  365. socket.current = io(endpoint.href, {
  366. path: endpoint["pathname"],
  367. transports: transports,
  368. autoUnref: false,
  369. });
  370. function checkVisibility() {
  371. if (document.visibilityState === "visible") {
  372. if (!socket.current.connected) {
  373. console.log("Socket is disconnected, attempting to reconnect ");
  374. socket.current.connect();
  375. } else {
  376. console.log("Socket is reconnected ");
  377. }
  378. }
  379. }
  380. const pagehideHandler = (event) => {
  381. if (event.persisted && socket.current?.connected) {
  382. console.log("Disconnect backend before bfcache on navigation");
  383. socket.current.disconnect();
  384. }
  385. };
  386. // Once the socket is open, hydrate the page.
  387. socket.current.on("connect", () => {
  388. setConnectErrors([]);
  389. window.addEventListener("pagehide", pagehideHandler);
  390. });
  391. socket.current.on("connect_error", (error) => {
  392. setConnectErrors((connectErrors) => [connectErrors.slice(-9), error]);
  393. });
  394. // When the socket disconnects reset the event_processing flag
  395. socket.current.on("disconnect", () => {
  396. event_processing = false;
  397. window.removeEventListener("pagehide", pagehideHandler);
  398. });
  399. // On each received message, queue the updates and events.
  400. socket.current.on("event", async (message) => {
  401. const update = JSON5.parse(message);
  402. for (const substate in update.delta) {
  403. dispatch[substate](update.delta[substate]);
  404. }
  405. applyClientStorageDelta(client_storage, update.delta);
  406. event_processing = !update.final;
  407. if (update.events) {
  408. queueEvents(update.events, socket);
  409. }
  410. });
  411. socket.current.on("reload", async (event) => {
  412. event_processing = false;
  413. queueEvents([...initialEvents(), JSON5.parse(event)], socket);
  414. });
  415. document.addEventListener("visibilitychange", checkVisibility);
  416. };
  417. /**
  418. * Upload files to the server.
  419. *
  420. * @param state The state to apply the delta to.
  421. * @param handler The handler to use.
  422. * @param upload_id The upload id to use.
  423. * @param on_upload_progress The function to call on upload progress.
  424. * @param socket the websocket connection
  425. *
  426. * @returns The response from posting to the UPLOADURL endpoint.
  427. */
  428. export const uploadFiles = async (
  429. handler,
  430. files,
  431. upload_id,
  432. on_upload_progress,
  433. socket
  434. ) => {
  435. // return if there's no file to upload
  436. if (files === undefined || files.length === 0) {
  437. return false;
  438. }
  439. if (upload_controllers[upload_id]) {
  440. console.log("Upload already in progress for ", upload_id);
  441. return false;
  442. }
  443. // Track how many partial updates have been processed for this upload.
  444. let resp_idx = 0;
  445. const eventHandler = (progressEvent) => {
  446. const event_callbacks = socket._callbacks.$event;
  447. // Whenever called, responseText will contain the entire response so far.
  448. const chunks = progressEvent.event.target.responseText.trim().split("\n");
  449. // So only process _new_ chunks beyond resp_idx.
  450. chunks.slice(resp_idx).map((chunk) => {
  451. event_callbacks.map((f, ix) => {
  452. f(chunk)
  453. .then(() => {
  454. if (ix === event_callbacks.length - 1) {
  455. // Mark this chunk as processed.
  456. resp_idx += 1;
  457. }
  458. })
  459. .catch((e) => {
  460. if (progressEvent.progress === 1) {
  461. // Chunk may be incomplete, so only report errors when full response is available.
  462. console.log("Error parsing chunk", chunk, e);
  463. }
  464. return;
  465. });
  466. });
  467. });
  468. };
  469. const controller = new AbortController();
  470. const config = {
  471. headers: {
  472. "Reflex-Client-Token": getToken(),
  473. "Reflex-Event-Handler": handler,
  474. },
  475. signal: controller.signal,
  476. onDownloadProgress: eventHandler,
  477. };
  478. if (on_upload_progress) {
  479. config["onUploadProgress"] = on_upload_progress;
  480. }
  481. const formdata = new FormData();
  482. // Add the token and handler to the file name.
  483. files.forEach((file) => {
  484. formdata.append("files", file, file.path || file.name);
  485. });
  486. // Send the file to the server.
  487. upload_controllers[upload_id] = controller;
  488. try {
  489. return await axios.post(getBackendURL(UPLOADURL), formdata, config);
  490. } catch (error) {
  491. if (error.response) {
  492. // The request was made and the server responded with a status code
  493. // that falls out of the range of 2xx
  494. console.log(error.response.data);
  495. } else if (error.request) {
  496. // The request was made but no response was received
  497. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  498. // http.ClientRequest in node.js
  499. console.log(error.request);
  500. } else {
  501. // Something happened in setting up the request that triggered an Error
  502. console.log(error.message);
  503. }
  504. return false;
  505. } finally {
  506. delete upload_controllers[upload_id];
  507. }
  508. };
  509. /**
  510. * Create an event object.
  511. * @param {string} name The name of the event.
  512. * @param {Object.<string, Any>} payload The payload of the event.
  513. * @param {Object.<string, (number|boolean)>} event_actions The actions to take on the event.
  514. * @param {string} handler The client handler to process event.
  515. * @returns The event object.
  516. */
  517. export const Event = (
  518. name,
  519. payload = {},
  520. event_actions = {},
  521. handler = null
  522. ) => {
  523. return { name, payload, handler, event_actions };
  524. };
  525. /**
  526. * Package client-side storage values as payload to send to the
  527. * backend with the hydrate event
  528. * @param client_storage The client storage object from context.js
  529. * @returns payload dict of client storage values
  530. */
  531. export const hydrateClientStorage = (client_storage) => {
  532. const client_storage_values = {};
  533. if (client_storage.cookies) {
  534. for (const state_key in client_storage.cookies) {
  535. const cookie_options = client_storage.cookies[state_key];
  536. const cookie_name = cookie_options.name || state_key;
  537. const cookie_value = cookies.get(cookie_name);
  538. if (cookie_value !== undefined) {
  539. client_storage_values[state_key] = cookies.get(cookie_name);
  540. }
  541. }
  542. }
  543. if (client_storage.local_storage && typeof window !== "undefined") {
  544. for (const state_key in client_storage.local_storage) {
  545. const options = client_storage.local_storage[state_key];
  546. const local_storage_value = localStorage.getItem(
  547. options.name || state_key
  548. );
  549. if (local_storage_value !== null) {
  550. client_storage_values[state_key] = local_storage_value;
  551. }
  552. }
  553. }
  554. if (client_storage.session_storage && typeof window != "undefined") {
  555. for (const state_key in client_storage.session_storage) {
  556. const session_options = client_storage.session_storage[state_key];
  557. const session_storage_value = sessionStorage.getItem(
  558. session_options.name || state_key
  559. );
  560. if (session_storage_value != null) {
  561. client_storage_values[state_key] = session_storage_value;
  562. }
  563. }
  564. }
  565. if (
  566. client_storage.cookies ||
  567. client_storage.local_storage ||
  568. client_storage.session_storage
  569. ) {
  570. return client_storage_values;
  571. }
  572. return {};
  573. };
  574. /**
  575. * Update client storage values based on backend state delta.
  576. * @param client_storage The client storage object from context.js
  577. * @param delta The state update from the backend
  578. */
  579. const applyClientStorageDelta = (client_storage, delta) => {
  580. // find the main state and check for is_hydrated
  581. const unqualified_states = Object.keys(delta).filter(
  582. (key) => key.split(".").length === 1
  583. );
  584. if (unqualified_states.length === 1) {
  585. const main_state = delta[unqualified_states[0]];
  586. if (main_state.is_hydrated !== undefined && !main_state.is_hydrated) {
  587. // skip if the state is not hydrated yet, since all client storage
  588. // values are sent in the hydrate event
  589. return;
  590. }
  591. }
  592. // Save known client storage values to cookies and localStorage.
  593. for (const substate in delta) {
  594. for (const key in delta[substate]) {
  595. const state_key = `${substate}.${key}`;
  596. if (client_storage.cookies && state_key in client_storage.cookies) {
  597. const cookie_options = { ...client_storage.cookies[state_key] };
  598. const cookie_name = cookie_options.name || state_key;
  599. delete cookie_options.name; // name is not a valid cookie option
  600. cookies.set(cookie_name, delta[substate][key], cookie_options);
  601. } else if (
  602. client_storage.local_storage &&
  603. state_key in client_storage.local_storage &&
  604. typeof window !== "undefined"
  605. ) {
  606. const options = client_storage.local_storage[state_key];
  607. localStorage.setItem(options.name || state_key, delta[substate][key]);
  608. } else if (
  609. client_storage.session_storage &&
  610. state_key in client_storage.session_storage &&
  611. typeof window !== "undefined"
  612. ) {
  613. const session_options = client_storage.session_storage[state_key];
  614. sessionStorage.setItem(
  615. session_options.name || state_key,
  616. delta[substate][key]
  617. );
  618. }
  619. }
  620. }
  621. };
  622. /**
  623. * Establish websocket event loop for a NextJS page.
  624. * @param dispatch The reducer dispatch function to update state.
  625. * @param initial_events The initial app events.
  626. * @param client_storage The client storage object from context.js
  627. *
  628. * @returns [addEvents, connectErrors] -
  629. * addEvents is used to queue an event, and
  630. * connectErrors is an array of reactive js error from the websocket connection (or null if connected).
  631. */
  632. export const useEventLoop = (
  633. dispatch,
  634. initial_events = () => [],
  635. client_storage = {}
  636. ) => {
  637. const socket = useRef(null);
  638. const router = useRouter();
  639. const [connectErrors, setConnectErrors] = useState([]);
  640. // Function to add new events to the event queue.
  641. const addEvents = (events, args, event_actions) => {
  642. if (!(args instanceof Array)) {
  643. args = [args];
  644. }
  645. event_actions = events.reduce(
  646. (acc, e) => ({ ...acc, ...e.event_actions }),
  647. event_actions ?? {}
  648. );
  649. const _e = args.filter((o) => o?.preventDefault !== undefined)[0];
  650. if (event_actions?.preventDefault && _e?.preventDefault) {
  651. _e.preventDefault();
  652. }
  653. if (event_actions?.stopPropagation && _e?.stopPropagation) {
  654. _e.stopPropagation();
  655. }
  656. const combined_name = events.map((e) => e.name).join("+++");
  657. if (event_actions?.temporal) {
  658. if (!socket.current || !socket.current.connected) {
  659. return; // don't queue when the backend is not connected
  660. }
  661. }
  662. if (event_actions?.throttle) {
  663. // If throttle returns false, the events are not added to the queue.
  664. if (!throttle(combined_name, event_actions.throttle)) {
  665. return;
  666. }
  667. }
  668. if (event_actions?.debounce) {
  669. // If debounce is used, queue the events after some delay
  670. debounce(
  671. combined_name,
  672. () => queueEvents(events, socket),
  673. event_actions.debounce
  674. );
  675. } else {
  676. queueEvents(events, socket);
  677. }
  678. };
  679. const sentHydrate = useRef(false); // Avoid double-hydrate due to React strict-mode
  680. useEffect(() => {
  681. if (router.isReady && !sentHydrate.current) {
  682. const events = initial_events();
  683. addEvents(
  684. events.map((e) => ({
  685. ...e,
  686. router_data: (({ pathname, query, asPath }) => ({
  687. pathname,
  688. query,
  689. asPath,
  690. }))(router),
  691. }))
  692. );
  693. sentHydrate.current = true;
  694. }
  695. }, [router.isReady]);
  696. // Handle frontend errors and send them to the backend via websocket.
  697. useEffect(() => {
  698. if (typeof window === "undefined") {
  699. return;
  700. }
  701. window.onerror = function (msg, url, lineNo, columnNo, error) {
  702. addEvents([
  703. Event(`${exception_state_name}.handle_frontend_exception`, {
  704. stack: error.stack,
  705. component_stack: "",
  706. }),
  707. ]);
  708. return false;
  709. };
  710. //NOTE: Only works in Chrome v49+
  711. //https://github.com/mknichel/javascript-errors?tab=readme-ov-file#promise-rejection-events
  712. window.onunhandledrejection = function (event) {
  713. addEvents([
  714. Event(`${exception_state_name}.handle_frontend_exception`, {
  715. stack: event.reason?.stack,
  716. component_stack: "",
  717. }),
  718. ]);
  719. return false;
  720. };
  721. }, []);
  722. // Main event loop.
  723. useEffect(() => {
  724. // Skip if the router is not ready.
  725. if (!router.isReady) {
  726. return;
  727. }
  728. // only use websockets if state is present
  729. if (Object.keys(initialState).length > 1) {
  730. // Initialize the websocket connection.
  731. if (!socket.current) {
  732. connect(
  733. socket,
  734. dispatch,
  735. ["websocket"],
  736. setConnectErrors,
  737. client_storage
  738. );
  739. }
  740. (async () => {
  741. // Process all outstanding events.
  742. while (event_queue.length > 0 && !event_processing) {
  743. await processEvent(socket.current);
  744. }
  745. })();
  746. }
  747. });
  748. // localStorage event handling
  749. useEffect(() => {
  750. const storage_to_state_map = {};
  751. if (client_storage.local_storage && typeof window !== "undefined") {
  752. for (const state_key in client_storage.local_storage) {
  753. const options = client_storage.local_storage[state_key];
  754. if (options.sync) {
  755. const local_storage_value_key = options.name || state_key;
  756. storage_to_state_map[local_storage_value_key] = state_key;
  757. }
  758. }
  759. }
  760. // e is StorageEvent
  761. const handleStorage = (e) => {
  762. if (storage_to_state_map[e.key]) {
  763. const vars = {};
  764. vars[storage_to_state_map[e.key]] = e.newValue;
  765. const event = Event(
  766. `${state_name}.reflex___state____update_vars_internal_state.update_vars_internal`,
  767. { vars: vars }
  768. );
  769. addEvents([event], e);
  770. }
  771. };
  772. window.addEventListener("storage", handleStorage);
  773. return () => window.removeEventListener("storage", handleStorage);
  774. });
  775. // Route after the initial page hydration.
  776. useEffect(() => {
  777. const change_start = () => {
  778. const main_state_dispatch = dispatch["reflex___state____state"];
  779. if (main_state_dispatch !== undefined) {
  780. main_state_dispatch({ is_hydrated: false });
  781. }
  782. };
  783. const change_complete = () => addEvents(onLoadInternalEvent());
  784. const change_error = () => {
  785. // Remove cached error state from router for this page, otherwise the
  786. // page will never send on_load events again.
  787. if (router.components[router.pathname].error) {
  788. delete router.components[router.pathname].error;
  789. }
  790. };
  791. router.events.on("routeChangeStart", change_start);
  792. router.events.on("routeChangeComplete", change_complete);
  793. router.events.on("routeChangeError", change_error);
  794. return () => {
  795. router.events.off("routeChangeStart", change_start);
  796. router.events.off("routeChangeComplete", change_complete);
  797. router.events.off("routeChangeError", change_error);
  798. };
  799. }, [router]);
  800. return [addEvents, connectErrors];
  801. };
  802. /***
  803. * Check if a value is truthy in python.
  804. * @param val The value to check.
  805. * @returns True if the value is truthy, false otherwise.
  806. */
  807. export const isTrue = (val) => {
  808. if (Array.isArray(val)) return val.length > 0;
  809. if (val === Object(val)) return Object.keys(val).length > 0;
  810. return Boolean(val);
  811. };
  812. /**
  813. * Get the value from a ref.
  814. * @param ref The ref to get the value from.
  815. * @returns The value.
  816. */
  817. export const getRefValue = (ref) => {
  818. if (!ref || !ref.current) {
  819. return;
  820. }
  821. if (ref.current.type == "checkbox") {
  822. return ref.current.checked; // chakra
  823. } else if (
  824. ref.current.className?.includes("rt-CheckboxRoot") ||
  825. ref.current.className?.includes("rt-SwitchRoot")
  826. ) {
  827. return ref.current.ariaChecked == "true"; // radix
  828. } else if (ref.current.className?.includes("rt-SliderRoot")) {
  829. // find the actual slider
  830. return ref.current.querySelector(".rt-SliderThumb")?.ariaValueNow;
  831. } else {
  832. //querySelector(":checked") is needed to get value from radio_group
  833. return (
  834. ref.current.value ||
  835. (ref.current.querySelector &&
  836. ref.current.querySelector(":checked") &&
  837. ref.current.querySelector(":checked")?.value)
  838. );
  839. }
  840. };
  841. /**
  842. * Get the values from a ref array.
  843. * @param refs The refs to get the values from.
  844. * @returns The values array.
  845. */
  846. export const getRefValues = (refs) => {
  847. if (!refs) {
  848. return;
  849. }
  850. // getAttribute is used by RangeSlider because it doesn't assign value
  851. return refs.map((ref) =>
  852. ref.current
  853. ? ref.current.value || ref.current.getAttribute("aria-valuenow")
  854. : null
  855. );
  856. };
  857. /**
  858. * Spread two arrays or two objects.
  859. * @param first The first array or object.
  860. * @param second The second array or object.
  861. * @returns The final merged array or object.
  862. */
  863. export const spreadArraysOrObjects = (first, second) => {
  864. if (Array.isArray(first) && Array.isArray(second)) {
  865. return [...first, ...second];
  866. } else if (typeof first === "object" && typeof second === "object") {
  867. return { ...first, ...second };
  868. } else {
  869. throw new Error("Both parameters must be either arrays or objects.");
  870. }
  871. };