tauri.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. declare global {
  2. interface Window {
  3. __TAURI_INVOKE_HANDLER__: (command: string) => void
  4. }
  5. }
  6. function s4(): string {
  7. return Math.floor((1 + Math.random()) * 0x10000)
  8. .toString(16)
  9. .substring(1)
  10. }
  11. function uid(): string {
  12. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  13. s4() + '-' + s4() + s4() + s4()
  14. }
  15. /**
  16. * sends a synchronous command to the backend
  17. *
  18. * @param args
  19. */
  20. function invoke(args: any): void {
  21. window.__TAURI_INVOKE_HANDLER__(args)
  22. }
  23. function transformCallback(callback?: (response: any) => void, once = false): string {
  24. const identifier = uid()
  25. Object.defineProperty(window, identifier, {
  26. value: (result: any) => {
  27. if (once) {
  28. Reflect.deleteProperty(window, identifier)
  29. }
  30. return callback?.(result)
  31. },
  32. writable: false
  33. })
  34. return identifier
  35. }
  36. /**
  37. * sends an asynchronous command to the backend
  38. *
  39. * @param args
  40. *
  41. * @return {Promise<T>} Promise resolving or rejecting to the backend response
  42. */
  43. async function promisified<T>(args: any): Promise<T> {
  44. return await new Promise((resolve, reject) => {
  45. invoke({
  46. callback: transformCallback(resolve),
  47. error: transformCallback(reject),
  48. ...args
  49. })
  50. })
  51. }
  52. export {
  53. invoke,
  54. transformCallback,
  55. promisified
  56. }