tauri.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. declare global {
  2. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  3. interface Window {
  4. __TAURI_INVOKE_HANDLER__: (command: string) => void
  5. }
  6. }
  7. function s4(): string {
  8. return Math.floor((1 + Math.random()) * 0x10000)
  9. .toString(16)
  10. .substring(1)
  11. }
  12. function uid(): string {
  13. return (
  14. s4() +
  15. s4() +
  16. '-' +
  17. s4() +
  18. '-' +
  19. s4() +
  20. '-' +
  21. s4() +
  22. '-' +
  23. s4() +
  24. s4() +
  25. s4()
  26. )
  27. }
  28. /**
  29. * sends a synchronous command to the backend
  30. *
  31. * @param args
  32. */
  33. function invoke(args: any): void {
  34. window.__TAURI_INVOKE_HANDLER__(args)
  35. }
  36. function transformCallback(
  37. callback?: (response: any) => void,
  38. once = false
  39. ): string {
  40. const identifier = uid()
  41. Object.defineProperty(window, identifier, {
  42. value: (result: any) => {
  43. if (once) {
  44. Reflect.deleteProperty(window, identifier)
  45. }
  46. return callback?.(result)
  47. },
  48. writable: false,
  49. configurable: true
  50. })
  51. return identifier
  52. }
  53. /**
  54. * sends an asynchronous command to the backend
  55. *
  56. * @param args
  57. *
  58. * @return {Promise<T>} Promise resolving or rejecting to the backend response
  59. */
  60. async function promisified<T>(args: any): Promise<T> {
  61. return await new Promise((resolve, reject) => {
  62. const callback = transformCallback((e) => {
  63. resolve(e)
  64. Reflect.deleteProperty(window, error)
  65. }, true)
  66. const error = transformCallback((e) => {
  67. reject(e)
  68. Reflect.deleteProperty(window, callback)
  69. }, true)
  70. invoke({
  71. callback,
  72. error,
  73. ...args
  74. })
  75. })
  76. }
  77. export { invoke, transformCallback, promisified }