bridge.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. (function () {
  2. 'use strict';
  3. var invoke = window.__TAURI__.core.invoke;
  4. var listen = window.__TAURI__.event.listen;
  5. // ── Rust → JS ──────────────────────────────
  6. listen('pet://state', function (e) {
  7. if (window.cfcPetAPI) window.cfcPetAPI.notifyState(e.payload);
  8. });
  9. listen('pet://bubble', function (e) {
  10. if (window.cfcPetAPI) window.cfcPetAPI.showBubble(e.payload.text, e.payload.durationMs);
  11. });
  12. listen('pet://config', function (e) {
  13. if (window.cfcPetAPI) window.cfcPetAPI.loadConfig(e.payload);
  14. });
  15. function applyCustomImage(url, dataUrl) {
  16. if (!window.cfcPetAPI) return;
  17. if (!dataUrl && url && /^https?:/i.test(url)) {
  18. // 远程图片:先取 data URL(规避 canvas 跨域污染)再生成动作;失败则仍显示原图
  19. try {
  20. invoke('data_url_from_url', { url: url }).then(function (d) {
  21. window.cfcPetAPI.setCustomImage(url, d);
  22. }).catch(function () {
  23. window.cfcPetAPI.setCustomImage(url, null);
  24. });
  25. } catch (_) {
  26. window.cfcPetAPI.setCustomImage(url, null);
  27. }
  28. } else {
  29. window.cfcPetAPI.setCustomImage(url, dataUrl);
  30. }
  31. }
  32. listen('pet://custom-image', function (e) {
  33. applyCustomImage(e.payload && e.payload.url, e.payload && e.payload.dataUrl);
  34. });
  35. // 启动时应用已保存的自定义形象
  36. try {
  37. invoke('get_settings').then(function (s) {
  38. window.__petHasToken = !!(s && s.hasToken);
  39. if (s && s.customMascotUrl) {
  40. applyCustomImage(s.customMascotUrl, null);
  41. }
  42. }).catch(function () {});
  43. } catch (_) { /* noop */ }
  44. // ── JS → Rust(替换 chrome.webview.hostObjects.sync.cfcHost)──
  45. window.cfcHost = {
  46. onInteract: function (action, dataJson) {
  47. try {
  48. invoke('on_interact', { action: action, data: dataJson });
  49. } catch (err) {
  50. console.log('[interaction]', action, dataJson);
  51. }
  52. },
  53. onDragStart: function () {
  54. try { invoke('drag_start'); } catch (e) { /* noop */ }
  55. },
  56. onDragEnd: function () {
  57. try { invoke('drag_end'); } catch (e) { /* noop */ }
  58. },
  59. startPerch: function () {
  60. try { invoke('start_perch'); } catch (e) { /* noop */ }
  61. },
  62. stopPerch: function () {
  63. try { invoke('stop_perch'); } catch (e) { /* noop */ }
  64. }
  65. };
  66. })();