popup.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. const API_URL = "http://127.0.0.1:19827";
  2. const statusBar = document.getElementById("statusBar");
  3. const titleInput = document.getElementById("titleInput");
  4. const urlPreview = document.getElementById("urlPreview");
  5. const contentPreview = document.getElementById("contentPreview");
  6. const clipBtn = document.getElementById("clipBtn");
  7. const projectSelect = document.getElementById("projectSelect");
  8. let extractedContent = "";
  9. let pageUrl = "";
  10. async function checkConnection() {
  11. try {
  12. const res = await fetch(`${API_URL}/status`, { method: "GET" });
  13. const data = await res.json();
  14. if (data.ok) {
  15. statusBar.className = "status connected";
  16. statusBar.textContent = "✓ Connected to LLM Wiki";
  17. await loadProjects();
  18. return true;
  19. }
  20. } catch {}
  21. statusBar.className = "status disconnected";
  22. statusBar.textContent = "✗ LLM Wiki app is not running";
  23. clipBtn.disabled = true;
  24. projectSelect.innerHTML = '<option value="">App not running</option>';
  25. return false;
  26. }
  27. async function loadProjects() {
  28. try {
  29. const res = await fetch(`${API_URL}/projects`, { method: "GET" });
  30. const data = await res.json();
  31. if (data.ok && data.projects?.length > 0) {
  32. projectSelect.innerHTML = "";
  33. for (const proj of data.projects) {
  34. const opt = document.createElement("option");
  35. opt.value = proj.path;
  36. opt.textContent = proj.name + (proj.current ? " (current)" : "");
  37. if (proj.current) opt.selected = true;
  38. projectSelect.appendChild(opt);
  39. }
  40. return;
  41. }
  42. } catch {}
  43. // Fallback to current project
  44. try {
  45. const res = await fetch(`${API_URL}/project`, { method: "GET" });
  46. const data = await res.json();
  47. if (data.ok && data.path) {
  48. const name = data.path.replace(/\\/g, "/").split("/").pop() || data.path;
  49. projectSelect.innerHTML = `<option value="${data.path}">${name}</option>`;
  50. }
  51. } catch {
  52. projectSelect.innerHTML = '<option value="">No projects</option>';
  53. }
  54. }
  55. async function extractContent() {
  56. try {
  57. const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  58. if (!tab?.id) return;
  59. pageUrl = tab.url || "";
  60. titleInput.value = tab.title || "Untitled";
  61. urlPreview.textContent = pageUrl;
  62. // First inject Readability.js and Turndown.js into the page
  63. await chrome.scripting.executeScript({
  64. target: { tabId: tab.id },
  65. files: ["Readability.js", "Turndown.js"],
  66. });
  67. // Then extract content using them
  68. const results = await chrome.scripting.executeScript({
  69. target: { tabId: tab.id },
  70. func: () => {
  71. try {
  72. // Use Readability to extract article content
  73. const documentClone = document.cloneNode(true);
  74. const reader = new window.Readability(documentClone);
  75. const article = reader.parse();
  76. if (!article || !article.content) {
  77. return { error: "Readability could not extract content" };
  78. }
  79. // Use Turndown to convert HTML to Markdown
  80. const turndown = new window.TurndownService({
  81. headingStyle: "atx",
  82. codeBlockStyle: "fenced",
  83. bulletListMarker: "-",
  84. });
  85. // Add table support
  86. turndown.addRule("tableCell", {
  87. filter: ["th", "td"],
  88. replacement: (content) => ` ${content.trim()} |`,
  89. });
  90. turndown.addRule("tableRow", {
  91. filter: "tr",
  92. replacement: (content) => `|${content}\n`,
  93. });
  94. turndown.addRule("table", {
  95. filter: "table",
  96. replacement: (content) => {
  97. // Add header separator after first row
  98. const lines = content.trim().split("\n");
  99. if (lines.length > 0) {
  100. const cols = (lines[0].match(/\|/g) || []).length - 1;
  101. const separator = "|" + " --- |".repeat(cols);
  102. lines.splice(1, 0, separator);
  103. }
  104. return "\n\n" + lines.join("\n") + "\n\n";
  105. },
  106. });
  107. // Remove images that are tracking pixels or tiny
  108. turndown.addRule("removeSmallImages", {
  109. filter: (node) => {
  110. if (node.nodeName !== "IMG") return false;
  111. const w = parseInt(node.getAttribute("width") || "999");
  112. const h = parseInt(node.getAttribute("height") || "999");
  113. return w < 10 || h < 10;
  114. },
  115. replacement: () => "",
  116. });
  117. const markdown = turndown.turndown(article.content);
  118. return {
  119. title: article.title,
  120. content: markdown,
  121. excerpt: article.excerpt || "",
  122. siteName: article.siteName || "",
  123. length: article.length || 0,
  124. };
  125. } catch (err) {
  126. return { error: err.message };
  127. }
  128. },
  129. });
  130. if (results?.[0]?.result) {
  131. const result = results[0].result;
  132. if (result.error) {
  133. contentPreview.textContent = `Extraction failed: ${result.error}. Falling back...`;
  134. await fallbackExtract(tab.id);
  135. return;
  136. }
  137. // Use Readability's title if better
  138. if (result.title && result.title.length > 5) {
  139. titleInput.value = result.title;
  140. }
  141. extractedContent = result.content;
  142. contentPreview.textContent = extractedContent;
  143. if (result.excerpt) {
  144. contentPreview.textContent = "📝 " + result.excerpt + "\n\n---\n\n" + extractedContent;
  145. }
  146. clipBtn.disabled = false;
  147. } else {
  148. await fallbackExtract(tab.id);
  149. }
  150. } catch (err) {
  151. contentPreview.textContent = `Error: ${err.message}`;
  152. }
  153. }
  154. // Fallback: simple DOM extraction if Readability fails
  155. async function fallbackExtract(tabId) {
  156. const results = await chrome.scripting.executeScript({
  157. target: { tabId },
  158. func: () => {
  159. const clone = document.body.cloneNode(true);
  160. ["script", "style", "nav", "header", "footer", ".sidebar", ".ad", ".comments"]
  161. .forEach((sel) => clone.querySelectorAll(sel).forEach((el) => el.remove()));
  162. return clone.innerText
  163. .split("\n")
  164. .map((l) => l.trim())
  165. .filter((l) => l.length > 0)
  166. .join("\n\n")
  167. .slice(0, 50000);
  168. },
  169. });
  170. if (results?.[0]?.result) {
  171. extractedContent = results[0].result;
  172. contentPreview.textContent = extractedContent;
  173. clipBtn.disabled = false;
  174. } else {
  175. contentPreview.textContent = "Failed to extract content";
  176. }
  177. }
  178. async function sendClip() {
  179. const selectedProject = projectSelect.value;
  180. if (!selectedProject) {
  181. statusBar.className = "status error";
  182. statusBar.textContent = "✗ Please select a project";
  183. return;
  184. }
  185. clipBtn.disabled = true;
  186. statusBar.className = "status sending";
  187. statusBar.textContent = "⏳ Sending to LLM Wiki...";
  188. try {
  189. const res = await fetch(`${API_URL}/clip`, {
  190. method: "POST",
  191. headers: { "Content-Type": "application/json" },
  192. body: JSON.stringify({
  193. title: titleInput.value,
  194. url: pageUrl,
  195. content: extractedContent,
  196. projectPath: selectedProject,
  197. }),
  198. });
  199. const data = await res.json();
  200. if (data.ok) {
  201. const projectName = projectSelect.options[projectSelect.selectedIndex]?.textContent || "project";
  202. statusBar.className = "status success";
  203. statusBar.textContent = `✓ Saved to ${projectName}`;
  204. clipBtn.textContent = "✓ Clipped!";
  205. } else {
  206. statusBar.className = "status error";
  207. statusBar.textContent = `✗ Error: ${data.error}`;
  208. clipBtn.disabled = false;
  209. }
  210. } catch (err) {
  211. statusBar.className = "status error";
  212. statusBar.textContent = `✗ Connection failed: ${err.message}`;
  213. clipBtn.disabled = false;
  214. }
  215. }
  216. clipBtn.addEventListener("click", sendClip);
  217. // Resize content preview to fill available space without causing popup scroll
  218. function resizePreview() {
  219. const totalHeight = 500; // matches html/body height
  220. const preview = document.getElementById("contentPreview");
  221. if (!preview) return;
  222. // Calculate space used by everything except the preview
  223. const previewRect = preview.getBoundingClientRect();
  224. const bottomSpace = totalHeight - previewRect.top - 60; // 60px for button + footer
  225. const maxH = Math.max(100, Math.min(300, bottomSpace));
  226. preview.style.maxHeight = maxH + "px";
  227. }
  228. (async () => {
  229. const connected = await checkConnection();
  230. // Always extract content so user can preview, even if app not running
  231. await extractContent();
  232. if (!connected) {
  233. clipBtn.disabled = true;
  234. clipBtn.textContent = "📎 App not running — cannot save";
  235. }
  236. setTimeout(resizePreview, 100);
  237. })();