tauri.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. declare global {
  2. interface External {
  3. invoke: (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. function invoke(args: any): void {
  16. window.external.invoke(typeof args === 'object' ? JSON.stringify(args) : args)
  17. }
  18. function transformCallback(callback?: (response: any) => void, once = false): string {
  19. const identifier = uid()
  20. Object.defineProperty(window, identifier, {
  21. value: (result: any) => {
  22. if (once) {
  23. Reflect.deleteProperty(window, identifier)
  24. }
  25. return callback?.(result)
  26. },
  27. writable: false
  28. })
  29. return identifier
  30. }
  31. async function promisified<T>(args: any): Promise<T> {
  32. return await new Promise((resolve, reject) => {
  33. invoke({
  34. callback: transformCallback(resolve),
  35. error: transformCallback(reject),
  36. ...args
  37. })
  38. })
  39. }
  40. export {
  41. invoke,
  42. transformCallback,
  43. promisified
  44. }