state.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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, useReducer, useRef, useState } from "react";
  8. import Router, { useRouter } from "next/router";
  9. import { initialEvents } from "utils/context.js"
  10. // Endpoint URLs.
  11. const EVENTURL = env.EVENT
  12. const UPLOADURL = env.UPLOAD
  13. // Global variable to hold the token.
  14. let token;
  15. // Key for the token in the session storage.
  16. const TOKEN_KEY = "token";
  17. // create cookie instance
  18. const cookies = new Cookies();
  19. // Dictionary holding component references.
  20. export const refs = {};
  21. // Flag ensures that only one event is processing on the backend concurrently.
  22. let event_processing = false
  23. // Array holding pending events to be processed.
  24. const event_queue = [];
  25. /**
  26. * Generate a UUID (Used for session tokens).
  27. * Taken from: https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid
  28. * @returns A UUID.
  29. */
  30. const generateUUID = () => {
  31. let d = new Date().getTime(),
  32. d2 = (performance && performance.now && performance.now() * 1000) || 0;
  33. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  34. let r = Math.random() * 16;
  35. if (d > 0) {
  36. r = (d + r) % 16 | 0;
  37. d = Math.floor(d / 16);
  38. } else {
  39. r = (d2 + r) % 16 | 0;
  40. d2 = Math.floor(d2 / 16);
  41. }
  42. return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
  43. });
  44. };
  45. /**
  46. * Get the token for the current session.
  47. * @returns The token.
  48. */
  49. export const getToken = () => {
  50. if (token) {
  51. return token;
  52. }
  53. if (window) {
  54. if (!window.sessionStorage.getItem(TOKEN_KEY)) {
  55. window.sessionStorage.setItem(TOKEN_KEY, generateUUID());
  56. }
  57. token = window.sessionStorage.getItem(TOKEN_KEY);
  58. }
  59. return token;
  60. };
  61. /**
  62. * Get the URL for the websocket connection
  63. * @returns The websocket URL object.
  64. */
  65. export const getEventURL = () => {
  66. // Get backend URL object from the endpoint.
  67. const endpoint = new URL(EVENTURL);
  68. if (endpoint.hostname === "localhost") {
  69. // If the backend URL references localhost, and the frontend is not on localhost,
  70. // then use the frontend host.
  71. const frontend_hostname = window.location.hostname;
  72. if (frontend_hostname !== "localhost") {
  73. endpoint.hostname = frontend_hostname;
  74. }
  75. }
  76. return endpoint
  77. }
  78. /**
  79. * Apply a delta to the state.
  80. * @param state The state to apply the delta to.
  81. * @param delta The delta to apply.
  82. */
  83. export const applyDelta = (state, delta) => {
  84. const new_state = { ...state }
  85. for (const substate in delta) {
  86. let s = new_state;
  87. const path = substate.split(".").slice(1);
  88. while (path.length > 0) {
  89. s = s[path.shift()];
  90. }
  91. for (const key in delta[substate]) {
  92. s[key] = delta[substate][key];
  93. }
  94. }
  95. return new_state
  96. };
  97. /**
  98. * Get all local storage items in a key-value object.
  99. * @returns object of items in local storage.
  100. */
  101. export const getAllLocalStorageItems = () => {
  102. var localStorageItems = {};
  103. for (var i = 0, len = localStorage.length; i < len; i++) {
  104. var key = localStorage.key(i);
  105. localStorageItems[key] = localStorage.getItem(key);
  106. }
  107. return localStorageItems;
  108. }
  109. /**
  110. * Handle frontend event or send the event to the backend via Websocket.
  111. * @param event The event to send.
  112. * @param socket The socket object to send the event on.
  113. *
  114. * @returns True if the event was sent, false if it was handled locally.
  115. */
  116. export const applyEvent = async (event, socket) => {
  117. // Handle special events
  118. if (event.name == "_redirect") {
  119. if (event.payload.external)
  120. window.open(event.payload.path, "_blank");
  121. else
  122. Router.push(event.payload.path);
  123. return false;
  124. }
  125. if (event.name == "_console") {
  126. console.log(event.payload.message);
  127. return false;
  128. }
  129. if (event.name == "_remove_cookie") {
  130. cookies.remove(event.payload.key, { ...event.payload.options })
  131. queueEvents(initialEvents(), socket)
  132. return false;
  133. }
  134. if (event.name == "_clear_local_storage") {
  135. localStorage.clear();
  136. queueEvents(initialEvents(), socket)
  137. return false;
  138. }
  139. if (event.name == "_remove_local_storage") {
  140. localStorage.removeItem(event.payload.key);
  141. queueEvents(initialEvents(), socket)
  142. return false;
  143. }
  144. if (event.name == "_set_clipboard") {
  145. const content = event.payload.content;
  146. navigator.clipboard.writeText(content);
  147. return false;
  148. }
  149. if (event.name == "_download") {
  150. const a = document.createElement('a');
  151. a.hidden = true;
  152. a.href = event.payload.url;
  153. a.download = event.payload.filename;
  154. a.click();
  155. a.remove();
  156. return false;
  157. }
  158. if (event.name == "_alert") {
  159. alert(event.payload.message);
  160. return false;
  161. }
  162. if (event.name == "_set_focus") {
  163. const ref =
  164. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  165. ref.current.focus();
  166. return false;
  167. }
  168. if (event.name == "_set_value") {
  169. const ref =
  170. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  171. ref.current.value = event.payload.value;
  172. return false;
  173. }
  174. if (event.name == "_call_script") {
  175. try {
  176. const eval_result = eval(event.payload.javascript_code);
  177. if (event.payload.callback) {
  178. eval(event.payload.callback)(eval_result)
  179. }
  180. } catch (e) {
  181. console.log("_call_script", e);
  182. }
  183. return false;
  184. }
  185. // Update token and router data (if missing).
  186. event.token = getToken()
  187. if (event.router_data === undefined || Object.keys(event.router_data).length === 0) {
  188. event.router_data = (({ pathname, query, asPath }) => ({ pathname, query, asPath }))(Router)
  189. }
  190. // Send the event to the server.
  191. if (socket) {
  192. socket.emit("event", JSON.stringify(event, (k, v) => v === undefined ? null : v));
  193. return true;
  194. }
  195. return false;
  196. };
  197. /**
  198. * Send an event to the server via REST.
  199. * @param event The current event.
  200. * @param state The state with the event queue.
  201. *
  202. * @returns Whether the event was sent.
  203. */
  204. export const applyRestEvent = async (event) => {
  205. let eventSent = false;
  206. if (event.handler == "uploadFiles") {
  207. eventSent = await uploadFiles(event.name, event.payload.files);
  208. }
  209. return eventSent;
  210. };
  211. /**
  212. * Queue events to be processed and trigger processing of queue.
  213. * @param events Array of events to queue.
  214. * @param socket The socket object to send the event on.
  215. */
  216. export const queueEvents = async (events, socket) => {
  217. event_queue.push(...events)
  218. await processEvent(socket.current)
  219. }
  220. /**
  221. * Process an event off the event queue.
  222. * @param socket The socket object to send the event on.
  223. */
  224. export const processEvent = async (
  225. socket
  226. ) => {
  227. // Only proceed if the socket is up, otherwise we throw the event into the void
  228. if (!socket) {
  229. return;
  230. }
  231. // Only proceed if we're not already processing an event.
  232. if (event_queue.length === 0 || event_processing) {
  233. return;
  234. }
  235. // Set processing to true to block other events from being processed.
  236. event_processing = true
  237. // Apply the next event in the queue.
  238. const event = event_queue.shift();
  239. let eventSent = false
  240. // Process events with handlers via REST and all others via websockets.
  241. if (event.handler) {
  242. eventSent = await applyRestEvent(event);
  243. } else {
  244. eventSent = await applyEvent(event, socket);
  245. }
  246. // If no event was sent, set processing to false.
  247. if (!eventSent) {
  248. event_processing = false;
  249. // recursively call processEvent to drain the queue, since there is
  250. // no state update to trigger the useEffect event loop.
  251. await processEvent(socket)
  252. }
  253. }
  254. /**
  255. * Connect to a websocket and set the handlers.
  256. * @param socket The socket object to connect.
  257. * @param dispatch The function to queue state update
  258. * @param transports The transports to use.
  259. * @param setConnectError The function to update connection error value.
  260. * @param client_storage The client storage object from context.js
  261. */
  262. export const connect = async (
  263. socket,
  264. dispatch,
  265. transports,
  266. setConnectError,
  267. client_storage = {},
  268. ) => {
  269. // Get backend URL object from the endpoint.
  270. const endpoint = getEventURL()
  271. // Create the socket.
  272. socket.current = io(endpoint.href, {
  273. path: endpoint["pathname"],
  274. transports: transports,
  275. autoUnref: false,
  276. });
  277. // Once the socket is open, hydrate the page.
  278. socket.current.on("connect", () => {
  279. setConnectError(null)
  280. });
  281. socket.current.on('connect_error', (error) => {
  282. setConnectError(error)
  283. });
  284. // On each received message, queue the updates and events.
  285. socket.current.on("event", message => {
  286. const update = JSON5.parse(message)
  287. dispatch(update.delta)
  288. applyClientStorageDelta(client_storage, update.delta)
  289. event_processing = !update.final
  290. if (update.events) {
  291. queueEvents(update.events, socket)
  292. }
  293. });
  294. };
  295. /**
  296. * Upload files to the server.
  297. *
  298. * @param state The state to apply the delta to.
  299. * @param handler The handler to use.
  300. *
  301. * @returns Whether the files were uploaded.
  302. */
  303. export const uploadFiles = async (handler, files) => {
  304. // return if there's no file to upload
  305. if (files.length == 0) {
  306. return false;
  307. }
  308. const headers = {
  309. "Content-Type": files[0].type,
  310. };
  311. const formdata = new FormData();
  312. // Add the token and handler to the file name.
  313. for (let i = 0; i < files.length; i++) {
  314. formdata.append(
  315. "files",
  316. files[i],
  317. getToken() + ":" + handler + ":" + files[i].name
  318. );
  319. }
  320. // Send the file to the server.
  321. await axios.post(UPLOADURL, formdata, headers)
  322. .then(() => { return true; })
  323. .catch(
  324. error => {
  325. if (error.response) {
  326. // The request was made and the server responded with a status code
  327. // that falls out of the range of 2xx
  328. console.log(error.response.data);
  329. } else if (error.request) {
  330. // The request was made but no response was received
  331. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  332. // http.ClientRequest in node.js
  333. console.log(error.request);
  334. } else {
  335. // Something happened in setting up the request that triggered an Error
  336. console.log(error.message);
  337. }
  338. return false;
  339. }
  340. )
  341. };
  342. /**
  343. * Create an event object.
  344. * @param name The name of the event.
  345. * @param payload The payload of the event.
  346. * @param handler The client handler to process event.
  347. * @returns The event object.
  348. */
  349. export const Event = (name, payload = {}, handler = null) => {
  350. return { name, payload, handler };
  351. };
  352. /**
  353. * Package client-side storage values as payload to send to the
  354. * backend with the hydrate event
  355. * @param client_storage The client storage object from context.js
  356. * @returns payload dict of client storage values
  357. */
  358. export const hydrateClientStorage = (client_storage) => {
  359. const client_storage_values = {
  360. "cookies": {},
  361. "local_storage": {}
  362. }
  363. if (client_storage.cookies) {
  364. for (const state_key in client_storage.cookies) {
  365. const cookie_options = client_storage.cookies[state_key]
  366. const cookie_name = cookie_options.name || state_key
  367. const cookie_value = cookies.get(cookie_name)
  368. if (cookie_value !== undefined) {
  369. client_storage_values.cookies[state_key] = cookies.get(cookie_name)
  370. }
  371. }
  372. }
  373. if (client_storage.local_storage && (typeof window !== 'undefined')) {
  374. for (const state_key in client_storage.local_storage) {
  375. const options = client_storage.local_storage[state_key]
  376. const local_storage_value = localStorage.getItem(options.name || state_key)
  377. if (local_storage_value !== null) {
  378. client_storage_values.local_storage[state_key] = local_storage_value
  379. }
  380. }
  381. }
  382. if (client_storage.cookies || client_storage.local_storage) {
  383. return client_storage_values
  384. }
  385. return {}
  386. };
  387. /**
  388. * Update client storage values based on backend state delta.
  389. * @param client_storage The client storage object from context.js
  390. * @param delta The state update from the backend
  391. */
  392. const applyClientStorageDelta = (client_storage, delta) => {
  393. // find the main state and check for is_hydrated
  394. const unqualified_states = Object.keys(delta).filter((key) => key.split(".").length === 1);
  395. if (unqualified_states.length === 1) {
  396. const main_state = delta[unqualified_states[0]]
  397. if (main_state.is_hydrated !== undefined && !main_state.is_hydrated) {
  398. // skip if the state is not hydrated yet, since all client storage
  399. // values are sent in the hydrate event
  400. return;
  401. }
  402. }
  403. // Save known client storage values to cookies and localStorage.
  404. for (const substate in delta) {
  405. for (const key in delta[substate]) {
  406. const state_key = `${substate}.${key}`
  407. if (client_storage.cookies && state_key in client_storage.cookies) {
  408. const cookie_options = { ...client_storage.cookies[state_key] }
  409. const cookie_name = cookie_options.name || state_key
  410. delete cookie_options.name // name is not a valid cookie option
  411. cookies.set(cookie_name, delta[substate][key], cookie_options);
  412. } else if (client_storage.local_storage && state_key in client_storage.local_storage && (typeof window !== 'undefined')) {
  413. const options = client_storage.local_storage[state_key]
  414. localStorage.setItem(options.name || state_key, delta[substate][key]);
  415. }
  416. }
  417. }
  418. }
  419. /**
  420. * Establish websocket event loop for a NextJS page.
  421. * @param initial_state The initial app state.
  422. * @param initial_events Function that returns the initial app events.
  423. * @param client_storage The client storage object from context.js
  424. *
  425. * @returns [state, addEvents, connectError] -
  426. * state is a reactive dict,
  427. * addEvents is used to queue an event, and
  428. * connectError is a reactive js error from the websocket connection (or null if connected).
  429. */
  430. export const useEventLoop = (
  431. initial_state = {},
  432. initial_events = () => [],
  433. client_storage = {},
  434. ) => {
  435. const socket = useRef(null)
  436. const router = useRouter()
  437. const [state, dispatch] = useReducer(applyDelta, initial_state)
  438. const [connectError, setConnectError] = useState(null)
  439. // Function to add new events to the event queue.
  440. const addEvents = (events, _e) => {
  441. preventDefault(_e);
  442. queueEvents(events, socket)
  443. }
  444. const sentHydrate = useRef(false); // Avoid double-hydrate due to React strict-mode
  445. // initial state hydrate
  446. useEffect(() => {
  447. if (router.isReady && !sentHydrate.current) {
  448. addEvents(initial_events())
  449. sentHydrate.current = true
  450. }
  451. }, [router.isReady])
  452. // Main event loop.
  453. useEffect(() => {
  454. // Skip if the router is not ready.
  455. if (!router.isReady) {
  456. return;
  457. }
  458. // only use websockets if state is present
  459. if (Object.keys(state).length > 0) {
  460. // Initialize the websocket connection.
  461. if (!socket.current) {
  462. connect(socket, dispatch, ['websocket', 'polling'], setConnectError, client_storage)
  463. }
  464. (async () => {
  465. // Process all outstanding events.
  466. while (event_queue.length > 0 && !event_processing) {
  467. await processEvent(socket.current)
  468. }
  469. })()
  470. }
  471. })
  472. return [state, addEvents, connectError]
  473. }
  474. /***
  475. * Check if a value is truthy in python.
  476. * @param val The value to check.
  477. * @returns True if the value is truthy, false otherwise.
  478. */
  479. export const isTrue = (val) => {
  480. return Array.isArray(val) ? val.length > 0 : !!val;
  481. };
  482. /**
  483. * Prevent the default event for form submission.
  484. * @param event
  485. */
  486. export const preventDefault = (event) => {
  487. if (event && event.type == "submit") {
  488. event.preventDefault();
  489. }
  490. };
  491. /**
  492. * Get the value from a ref.
  493. * @param ref The ref to get the value from.
  494. * @returns The value.
  495. */
  496. export const getRefValue = (ref) => {
  497. if (!ref || !ref.current) {
  498. return;
  499. }
  500. if (ref.current.type == "checkbox") {
  501. return ref.current.checked;
  502. } else {
  503. //querySelector(":checked") is needed to get value from radio_group
  504. return ref.current.value || (ref.current.querySelector(':checked') && ref.current.querySelector(':checked').value);
  505. }
  506. }
  507. /**
  508. * Get the values from a ref array.
  509. * @param refs The refs to get the values from.
  510. * @returns The values array.
  511. */
  512. export const getRefValues = (refs) => {
  513. if (!refs) {
  514. return;
  515. }
  516. // getAttribute is used by RangeSlider because it doesn't assign value
  517. return refs.map((ref) => ref.current.value || ref.current.getAttribute("aria-valuenow"));
  518. }
  519. /**
  520. * Spread two arrays or two objects.
  521. * @param first The first array or object.
  522. * @param second The second array or object.
  523. * @returns The final merged array or object.
  524. */
  525. export const spreadArraysOrObjects = (first, second) => {
  526. if (Array.isArray(first) && Array.isArray(second)) {
  527. return [...first, ...second];
  528. } else if (typeof first === 'object' && typeof second === 'object') {
  529. return { ...first, ...second };
  530. } else {
  531. throw new Error('Both parameters must be either arrays or objects.');
  532. }
  533. }