eval.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Handle communication between rust and evaluating javascript
  2. export class Channel {
  3. pending: any[];
  4. waiting: ((data: any) => void)[];
  5. constructor() {
  6. this.pending = [];
  7. this.waiting = [];
  8. }
  9. send(data: any) {
  10. // If there's a waiting callback, call it
  11. if (this.waiting.length > 0) {
  12. this.waiting.shift()(data);
  13. return;
  14. }
  15. // Otherwise queue the data
  16. this.pending.push(data);
  17. }
  18. async recv(): Promise<any> {
  19. return new Promise((resolve, _reject) => {
  20. // If data already exists, resolve immediately
  21. if (this.pending.length > 0) {
  22. resolve(this.pending.shift());
  23. return;
  24. }
  25. // Otherwise queue the resolve callback
  26. this.waiting.push(resolve);
  27. });
  28. }
  29. }
  30. export class WeakDioxusChannel {
  31. inner: WeakRef<DioxusChannel>;
  32. constructor(channel: DioxusChannel) {
  33. this.inner = new WeakRef(channel);
  34. }
  35. // Send data from rust to javascript
  36. rustSend(data: any) {
  37. let channel = this.inner.deref();
  38. if (channel) {
  39. channel.rustSend(data);
  40. }
  41. }
  42. // Receive data sent from javascript in rust
  43. async rustRecv(): Promise<any> {
  44. let channel = this.inner.deref();
  45. if (channel) {
  46. return await channel.rustRecv();
  47. }
  48. }
  49. }
  50. export abstract class DioxusChannel {
  51. // Return a weak reference to this channel
  52. weak(): WeakDioxusChannel {
  53. return new WeakDioxusChannel(this);
  54. }
  55. // Send data from rust to javascript
  56. abstract rustSend(data: any): void;
  57. // Receive data sent from javascript in rust
  58. abstract rustRecv(): Promise<any>;
  59. }