content.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /**
  2. * 侧边栏管理类
  3. */
  4. class SidebarManager {
  5. /**
  6. * @constant {Object} 配置常量
  7. */
  8. static CONFIG = {
  9. SIDEBAR_ID: "paiwise-sidebar",
  10. WRAPPER_ID: "paiwise-main-wrapper",
  11. STORAGE_KEY: "sidebarOpen",
  12. };
  13. constructor() {
  14. this.sidebarId = SidebarManager.CONFIG.SIDEBAR_ID;
  15. this.wrapperId = SidebarManager.CONFIG.WRAPPER_ID;
  16. this.isOpen = false;
  17. this.init();
  18. }
  19. /**
  20. * 初始化侧边栏
  21. */
  22. async init() {
  23. try {
  24. await this.checkAndRestoreState();
  25. this.setupEventListeners();
  26. } catch (error) {
  27. console.error("Sidebar initialization failed:", error);
  28. }
  29. }
  30. /**
  31. * 设置事件监听器
  32. */
  33. setupEventListeners() {
  34. // 监听页面加载完成事件
  35. window.addEventListener("load", () => this.checkAndRestoreState());
  36. // 监听来自 sidebar 的消息
  37. window.addEventListener("message", this.handleMessage.bind(this));
  38. // 监听窗口大小变化
  39. window.addEventListener(
  40. "resize",
  41. Utils.debounce(() => this.handleResize(), 100)
  42. );
  43. // 监听页面可见性变化
  44. document.addEventListener("visibilitychange", () => {
  45. if (!document.hidden) {
  46. this.checkAndRestoreState();
  47. }
  48. });
  49. // 监听 history 变化
  50. window.addEventListener("popstate", () => {
  51. this.checkAndRestoreState();
  52. });
  53. // 监听页面 URL 变化
  54. let lastUrl = location.href;
  55. new MutationObserver(() => {
  56. const url = location.href;
  57. if (url !== lastUrl) {
  58. lastUrl = url;
  59. this.checkAndRestoreState();
  60. }
  61. }).observe(document, { subtree: true, childList: true });
  62. }
  63. /**
  64. * 处理接收到的消息
  65. * @param {MessageEvent} event
  66. */
  67. handleMessage(event) {
  68. if (event.data.action === "closeSidebar") {
  69. this.removeSidebar();
  70. }
  71. }
  72. /**
  73. * 处理窗口大小变化
  74. */
  75. handleResize() {
  76. const sidebar = document.getElementById(this.sidebarId);
  77. if (sidebar && this.isOpen) {
  78. sidebar.style.height = `${window.innerHeight}px`;
  79. }
  80. }
  81. /**
  82. * 检查并恢复侧边栏状态
  83. */
  84. async checkAndRestoreState() {
  85. try {
  86. const isOpen = await Utils.getStorageData(
  87. SidebarManager.CONFIG.STORAGE_KEY
  88. );
  89. if (isOpen && !this.isOpen) {
  90. // 只有当应该打开且当前未打开时才创建
  91. this.createSidebar();
  92. } else if (!isOpen && this.isOpen) {
  93. // 只有当应该关闭且当前打开时才移除
  94. this.removeSidebar();
  95. }
  96. } catch (error) {
  97. console.error("Failed to restore sidebar state:", error);
  98. }
  99. }
  100. /**
  101. * 包装页面内容
  102. */
  103. wrapPageContent() {
  104. if (document.getElementById(this.wrapperId)) return;
  105. const wrapper = document.createElement("div");
  106. wrapper.id = this.wrapperId;
  107. // 添加初始样式
  108. wrapper.style.width = "100%";
  109. while (document.body.firstChild) {
  110. if (document.body.firstChild.id !== this.sidebarId) {
  111. wrapper.appendChild(document.body.firstChild);
  112. } else {
  113. document.body.removeChild(document.body.firstChild);
  114. }
  115. }
  116. document.body.appendChild(wrapper);
  117. }
  118. /**
  119. * 解除页面内容包装
  120. */
  121. unwrapPageContent() {
  122. const wrapper = document.getElementById(this.wrapperId);
  123. if (!wrapper) return;
  124. while (wrapper.firstChild) {
  125. document.body.insertBefore(wrapper.firstChild, wrapper);
  126. }
  127. wrapper.remove();
  128. }
  129. /**
  130. * 创建侧边栏
  131. */
  132. async createSidebar() {
  133. if (document.getElementById(this.sidebarId)) return;
  134. try {
  135. this.wrapPageContent();
  136. const iframe = document.createElement("iframe");
  137. iframe.id = this.sidebarId;
  138. iframe.src = chrome.runtime.getURL("sidebar.html");
  139. document.body.appendChild(iframe);
  140. // 使用 RAF 确保 DOM 更新后再添加动画类
  141. requestAnimationFrame(() => {
  142. const wrapper = document.getElementById(this.wrapperId);
  143. const sidebar = document.getElementById(this.sidebarId);
  144. // 先触发重排
  145. sidebar.getBoundingClientRect();
  146. // 添加动画类
  147. if (wrapper) wrapper.classList.add("sidebar-open");
  148. if (sidebar) sidebar.classList.add("show");
  149. });
  150. this.isOpen = true;
  151. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, true);
  152. } catch (error) {
  153. console.error("Failed to create sidebar:", error);
  154. this.unwrapPageContent();
  155. }
  156. }
  157. /**
  158. * 移除侧边栏
  159. */
  160. async removeSidebar() {
  161. if (!this.isOpen) return;
  162. try {
  163. const sidebar = document.getElementById(this.sidebarId);
  164. const wrapper = document.getElementById(this.wrapperId);
  165. if (sidebar && wrapper) {
  166. // 移除动画类
  167. wrapper.classList.remove("sidebar-open");
  168. sidebar.classList.remove("show");
  169. // 等待动画完成后再移除元素
  170. await new Promise((resolve) => {
  171. sidebar.addEventListener(
  172. "transitionend",
  173. () => {
  174. this.unwrapPageContent();
  175. sidebar.remove();
  176. resolve();
  177. },
  178. { once: true }
  179. );
  180. });
  181. }
  182. this.isOpen = false;
  183. await Utils.setStorageData(SidebarManager.CONFIG.STORAGE_KEY, false);
  184. } catch (error) {
  185. console.error("Failed to remove sidebar:", error);
  186. }
  187. }
  188. /**
  189. * 切换侧边栏显示状态
  190. */
  191. toggle() {
  192. if (this.isOpen) {
  193. this.removeSidebar();
  194. } else {
  195. this.createSidebar();
  196. }
  197. }
  198. }
  199. // 初始化侧边栏管理器
  200. const sidebarManager = new SidebarManager();
  201. // 监听来自背景脚本的消息
  202. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  203. if (message.action === "toggleSidebar") {
  204. sidebarManager.toggle();
  205. sendResponse({ success: true });
  206. }
  207. });
  208. // 创建一个新的js文件用于处理侧边栏内部的关闭按钮事件