state.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. // Endpoint URLs.
  8. const PINGURL = env.pingUrl
  9. const EVENTURL = env.eventUrl
  10. const UPLOADURL = env.uploadUrl
  11. // Global variable to hold the token.
  12. let token;
  13. // Key for the token in the session storage.
  14. const TOKEN_KEY = "token";
  15. // Dictionary holding component references.
  16. export const refs = {};
  17. /**
  18. * Generate a UUID (Used for session tokens).
  19. * Taken from: https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid
  20. * @returns A UUID.
  21. */
  22. const generateUUID = () => {
  23. let d = new Date().getTime(),
  24. d2 = (performance && performance.now && performance.now() * 1000) || 0;
  25. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  26. let r = Math.random() * 16;
  27. if (d > 0) {
  28. r = (d + r) % 16 | 0;
  29. d = Math.floor(d / 16);
  30. } else {
  31. r = (d2 + r) % 16 | 0;
  32. d2 = Math.floor(d2 / 16);
  33. }
  34. return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
  35. });
  36. };
  37. /**
  38. * Get the token for the current session.
  39. * @returns The token.
  40. */
  41. export const getToken = () => {
  42. if (token) {
  43. return token;
  44. }
  45. if (window) {
  46. if (!window.sessionStorage.getItem(TOKEN_KEY)) {
  47. window.sessionStorage.setItem(TOKEN_KEY, generateUUID());
  48. }
  49. token = window.sessionStorage.getItem(TOKEN_KEY);
  50. }
  51. return token;
  52. };
  53. /**
  54. * Apply a delta to the state.
  55. * @param state The state to apply the delta to.
  56. * @param delta The delta to apply.
  57. */
  58. export const applyDelta = (state, delta) => {
  59. for (const substate in delta) {
  60. let s = state;
  61. const path = substate.split(".").slice(1);
  62. while (path.length > 0) {
  63. s = s[path.shift()];
  64. }
  65. for (const key in delta[substate]) {
  66. s[key] = delta[substate][key];
  67. }
  68. }
  69. };
  70. /**
  71. * Get all local storage items in a key-value object.
  72. * @returns object of items in local storage.
  73. */
  74. export const getAllLocalStorageItems = () => {
  75. var localStorageItems = {};
  76. for (var i = 0, len = localStorage.length; i < len; i++) {
  77. var key = localStorage.key(i);
  78. localStorageItems[key] = localStorage.getItem(key);
  79. }
  80. return localStorageItems;
  81. }
  82. /**
  83. * Send an event to the server.
  84. * @param event The event to send.
  85. * @param router The router object.
  86. * @param socket The socket object to send the event on.
  87. *
  88. * @returns True if the event was sent, false if it was handled locally.
  89. */
  90. export const applyEvent = async (event, router, socket) => {
  91. // Handle special events
  92. if (event.name == "_redirect") {
  93. router.push(event.payload.path);
  94. return false;
  95. }
  96. if (event.name == "_console") {
  97. console.log(event.payload.message);
  98. return false;
  99. }
  100. if (event.name == "_set_cookie") {
  101. const cookies = new Cookies();
  102. cookies.set(event.payload.key, event.payload.value);
  103. localStorage.setItem(event.payload.key, event.payload.value);
  104. return false;
  105. }
  106. if (event.name == "_set_local_storage") {
  107. localStorage.setItem(event.payload.key, event.payload.value);
  108. return false;
  109. }
  110. if (event.name == "_set_clipboard") {
  111. const content = event.payload.content;
  112. navigator.clipboard.writeText(content);
  113. return false;
  114. }
  115. if (event.name == "_alert") {
  116. alert(event.payload.message);
  117. return false;
  118. }
  119. if (event.name == "_set_focus") {
  120. const ref =
  121. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  122. ref.current.focus();
  123. return false;
  124. }
  125. if (event.name == "_set_value") {
  126. const ref =
  127. event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref;
  128. ref.current.value = event.payload.value;
  129. return false;
  130. }
  131. // Send the event to the server.
  132. event.token = getToken();
  133. event.router_data = (({ pathname, query }) => ({ pathname, query }))(router);
  134. if (socket) {
  135. socket.emit("event", JSON.stringify(event));
  136. return true;
  137. }
  138. return false;
  139. };
  140. /**
  141. * Process an event off the event queue.
  142. * @param event The current event
  143. * @param state The state with the event queue.
  144. * @param setResult The function to set the result.
  145. *
  146. * @returns Whether the event was sent.
  147. */
  148. export const applyRestEvent = async (event, state, setResult) => {
  149. let eventSent = false;
  150. if (event.handler == "uploadFiles") {
  151. eventSent = await uploadFiles(state, setResult, event.name);
  152. }
  153. return eventSent;
  154. };
  155. /**
  156. * Process an event off the event queue.
  157. * @param state The state with the event queue.
  158. * @param setState The function to set the state.
  159. * @param result The current result.
  160. * @param setResult The function to set the result.
  161. * @param router The router object.
  162. * @param socket The socket object to send the event on.
  163. */
  164. export const processEvent = async (
  165. state,
  166. setState,
  167. result,
  168. setResult,
  169. router,
  170. socket
  171. ) => {
  172. // If we are already processing an event, or there are no events to process, return.
  173. if (result.processing || state.events.length == 0) {
  174. return;
  175. }
  176. // Set processing to true to block other events from being processed.
  177. setResult({ ...result, processing: true });
  178. // Apply the next event in the queue.
  179. const event = state.events.shift();
  180. // Set new events to avoid reprocessing the same event.
  181. setState(state => ({ ...state, events: state.events }));
  182. // Process events with handlers via REST and all others via websockets.
  183. let eventSent = false;
  184. if (event.handler) {
  185. eventSent = await applyRestEvent(event, state, setResult);
  186. } else {
  187. eventSent = await applyEvent(event, router, socket);
  188. }
  189. // If no event was sent, set processing to false.
  190. if (!eventSent) {
  191. setResult({ ...state, final: true, processing: false });
  192. }
  193. };
  194. /**
  195. * Connect to a websocket and set the handlers.
  196. * @param socket The socket object to connect.
  197. * @param state The state object to apply the deltas to.
  198. * @param setState The function to set the state.
  199. * @param result The current result.
  200. * @param setResult The function to set the result.
  201. * @param endpoint The endpoint to connect to.
  202. * @param transports The transports to use.
  203. */
  204. export const connect = async (
  205. socket,
  206. state,
  207. setState,
  208. result,
  209. setResult,
  210. router,
  211. transports,
  212. setNotConnected
  213. ) => {
  214. // Get backend URL object from the endpoint
  215. const endpoint = new URL(EVENTURL);
  216. // Create the socket.
  217. socket.current = io(EVENTURL, {
  218. path: endpoint["pathname"],
  219. transports: transports,
  220. autoUnref: false,
  221. });
  222. // Once the socket is open, hydrate the page.
  223. socket.current.on("connect", () => {
  224. processEvent(state, setState, result, setResult, router, socket.current);
  225. setNotConnected(false)
  226. });
  227. socket.current.on('connect_error', (error) => {
  228. setNotConnected(true)
  229. });
  230. // On each received message, apply the delta and set the result.
  231. socket.current.on("event", update => {
  232. update = JSON5.parse(update);
  233. applyDelta(state, update.delta);
  234. setResult({
  235. state: state,
  236. events: update.events,
  237. final: update.final,
  238. processing: true,
  239. });
  240. });
  241. };
  242. /**
  243. * Upload files to the server.
  244. *
  245. * @param state The state to apply the delta to.
  246. * @param setResult The function to set the result.
  247. * @param handler The handler to use.
  248. * @param endpoint The endpoint to upload to.
  249. *
  250. * @returns Whether the files were uploaded.
  251. */
  252. export const uploadFiles = async (state, setResult, handler) => {
  253. const files = state.files;
  254. // return if there's no file to upload
  255. if (files.length == 0) {
  256. return false;
  257. }
  258. const headers = {
  259. "Content-Type": files[0].type,
  260. };
  261. const formdata = new FormData();
  262. // Add the token and handler to the file name.
  263. for (let i = 0; i < files.length; i++) {
  264. formdata.append(
  265. "files",
  266. files[i],
  267. getToken() + ":" + handler + ":" + files[i].name
  268. );
  269. }
  270. // Send the file to the server.
  271. await axios.post(UPLOADURL, formdata, headers).then((response) => {
  272. // Apply the delta and set the result.
  273. const update = response.data;
  274. applyDelta(state, update.delta);
  275. // Set processing to false and return.
  276. setResult({
  277. state: state,
  278. events: update.events,
  279. final: true,
  280. processing: false,
  281. });
  282. });
  283. return true;
  284. };
  285. /**
  286. * Create an event object.
  287. * @param name The name of the event.
  288. * @param payload The payload of the event.
  289. * @param use_websocket Whether the event uses websocket.
  290. * @param handler The client handler to process event.
  291. * @returns The event object.
  292. */
  293. export const E = (name, payload = {}, handler = null) => {
  294. return { name, payload, handler };
  295. };
  296. /***
  297. * Check if a value is truthy in python.
  298. * @param val The value to check.
  299. * @returns True if the value is truthy, false otherwise.
  300. */
  301. export const isTrue = (val) => {
  302. return Array.isArray(val) ? val.length > 0 : !!val;
  303. };
  304. /**
  305. * Prevent the default event for form submission.
  306. * @param event
  307. */
  308. export const preventDefault = (event) => {
  309. if (event && event.type == "submit") {
  310. event.preventDefault();
  311. }
  312. };
  313. /**
  314. * Get the value from a ref.
  315. * @param ref The ref to get the value from.
  316. * @returns The value.
  317. */
  318. export const getRefValue = (ref) => {
  319. if (ref.current.type == "checkbox") {
  320. return ref.current.checked;
  321. } else {
  322. return ref.current.value;
  323. }
  324. }