42 lines
17 KiB
JavaScript
42 lines
17 KiB
JavaScript
import{c as z,j as e,R as b}from"./client-DnQyoB4h.js";import{g as J,b as d,s as D}from"./settings-mco8QK8Y.js";import{n as M}from"./clipTypes-C_ha5Ash.js";function B(...i){console.log("[gomdown-helper][clip][popup]",...i)}function G(i){return String(i).replace(/\s*[|\-–—]\s*(qiita|medium|youtube|x|twitter|tistory|velog|github)\s*$/i,"").replace(/\s*[-–—|]\s*(edge|chrome|firefox)\s*$/i,"").replace(/\[[^\]]{1,30}\]\s*$/g,"").trim().replace(/[\\/:*?"<>|]/g,"_").replace(/[(){}[\]]/g,"").replace(/\s+/g," ").replace(/[._-]{2,}/g,"-").replace(/^[._\-\s]+|[._\-\s]+$/g,"").slice(0,80)||"clips"}function V(i,x=""){if(!i.trim())return"";const f=new DOMParser().parseFromString(`<div>${i}</div>`,"text/html").body.firstElementChild;if(!f)return"";const N=r=>{const s=String(r||"").trim();if(!s)return"";if(!x)return s;try{return new URL(s,x).toString()}catch{return s}},C=r=>String(r||"").replace(/\s+/g," ").trim(),E=r=>{const s=[r.getAttribute("src"),r.getAttribute("data-src"),r.getAttribute("data-original"),r.getAttribute("data-url"),r.currentSrc];for(const o of s){const l=N(String(o||"").trim());if(l)return l}return""},u=r=>r.replace(/\|/g,"\\|").replace(/\n+/g," ").replace(/\s+/g," ").trim(),H=r=>{const s=Array.from(r.querySelectorAll("tr"));if(s.length===0)return"";const o=s.map(j=>Array.from(j.querySelectorAll("th,td")).map(v=>{const P=Array.from(v.childNodes).map(O=>O instanceof HTMLElement&&["pre","ul","ol","table"].includes(O.tagName.toLowerCase())?C(y(O)):g(O)).join("");return u(P)})).filter(j=>j.length>0);if(o.length===0)return"";const l=o.reduce((j,v)=>Math.max(j,v.length),0),p=o.map(j=>{const v=[...j];for(;v.length<l;)v.push("");return v}),h=s[0],S=h?Array.from(h.querySelectorAll("th")).length>0:!1,A=S?p[0]:p[0].map((j,v)=>`col${v+1}`),w=S?p.slice(1):p,T=`| ${A.join(" | ")} |`,U=`| ${A.map(()=>"---").join(" | ")} |`,q=w.map(j=>`| ${j.join(" | ")} |`);return[T,U,...q].join(`
|
|
`)},g=r=>{if(r.nodeType===Node.TEXT_NODE)return(r.nodeValue||"").replace(/\s+/g," ");if(!(r instanceof HTMLElement))return"";const s=r.tagName.toLowerCase();if(s==="br")return`
|
|
`;if(s==="strong"||s==="b")return`**${Array.from(r.childNodes).map(g).join("")}**`;if(s==="em"||s==="i")return`*${Array.from(r.childNodes).map(g).join("")}*`;if(s==="img"){const o=E(r),l=String(r.getAttribute("alt")||"").trim(),p=C(r.getAttribute("title")||""),h=p?` "${p.replace(/"/g,'\\"')}"`:"";return o?``:""}if(s==="a"){const o=N(r.getAttribute("href")||""),l=Array.from(r.childNodes).map(g).join("").trim()||o;return o?`[${l}](${o})`:l}if(s==="code"){if(r.parentElement?.tagName.toLowerCase()==="pre")return r.textContent||"";const o=Array.from(r.childNodes).map(g).join("").replace(/\n+/g," ").trim();return o?`\`${o}\``:""}return Array.from(r.childNodes).map(g).join("")},y=r=>{if(r.nodeType===Node.TEXT_NODE)return(r.nodeValue||"").replace(/\s+/g," ").trim();if(!(r instanceof HTMLElement))return"";const s=r.tagName.toLowerCase();if(s==="pre"){const o=r.querySelector("code"),l=(o?.textContent||r.textContent||"").replace(/\r\n/g,`
|
|
`).replace(/\n+$/,""),S=String(o?.className||"").match(/language-([a-z0-9_-]+)/i)?.[1]||"";return l?`\`\`\`${S}
|
|
${l}
|
|
\`\`\`
|
|
|
|
`:""}if(s==="img"){const o=E(r),l=String(r.getAttribute("alt")||"").trim(),p=C(r.getAttribute("title")||""),h=p?` "${p.replace(/"/g,'\\"')}"`:"";return o?`
|
|
|
|
`:""}if(s==="figure"){const o=r.querySelector("img"),l=C(r.querySelector("figcaption")?.textContent||"");if(o instanceof HTMLElement){const h=y(o).trim();if(h&&l)return`${h}
|
|
*${l}*
|
|
|
|
`;if(h)return`${h}
|
|
|
|
`}const p=C(Array.from(r.childNodes).map(g).join(""));return p?`${p}
|
|
|
|
`:""}if(s==="ul"||s==="ol"){const o=Array.from(r.children).map((l,p)=>{if(!(l instanceof HTMLElement)||l.tagName.toLowerCase()!=="li")return"";const h=Array.from(l.childNodes).map(w=>w instanceof HTMLElement&&(w.tagName.toLowerCase()==="ul"||w.tagName.toLowerCase()==="ol")?"":g(w)).join("").trim(),S=s==="ol"?`${p+1}. `:"- ",A=Array.from(l.children).filter(w=>w.tagName&&["ul","ol"].includes(w.tagName.toLowerCase())).map(w=>y(w).trimEnd().split(`
|
|
`).map(T=>T&&` ${T}`).join(`
|
|
`)).filter(Boolean).join(`
|
|
`);return`${S}${h}${A?`
|
|
${A}`:""}`}).filter(Boolean).join(`
|
|
`);return o?`${o}
|
|
|
|
`:""}if(s==="table"){const o=H(r);return o?`${o}
|
|
|
|
`:""}if(s==="p"||s==="div"||s==="section"||s==="article"||s==="blockquote"){const o=Array.from(r.childNodes).map(l=>l instanceof HTMLElement&&["pre","ul","ol","img","table","figure"].includes(l.tagName.toLowerCase())?`
|
|
${y(l)}`:g(l)).join("").trim();return o?s==="blockquote"?`${o.split(`
|
|
`).map(l=>l?`> ${l}`:">").join(`
|
|
`)}
|
|
|
|
`:`${o}
|
|
|
|
`:""}return s==="code"?"":`${Array.from(r.childNodes).map(y).join("")}`};return y(f).replace(/\n{3,}/g,`
|
|
|
|
`).trim()}function W(i,x){if(i.length===0)return"";const n=[`# ${i[0]?.pageTitle||x||"Untitled"}`,`- source: ${x}`,`- exportedAt: ${new Date().toISOString()}`,`- clips: ${i.length}`,"","---",""];for(let f=0;f<i.length;f+=1)n.push(X(i[f],f)),n.push("");return n.join(`
|
|
`)}function X(i,x){const n=(V(String(i.quoteHtml||""),i.pageUrl||"")||i.quote||i.anchor.exact||"").replace(/\r\n/g,`
|
|
`).trim(),f=n.length>4e3?`${n.slice(0,4e3)}
|
|
...(truncated)`:n,N=f.split(`
|
|
`).map(u=>u.trimEnd()).filter((u,H,g)=>!(u===""&&g[H-1]==="")),E=/(^|\n)\|.*\|\n\|[-:| ]+\||(^|\n)```|!\[[^\]]*\]\(|(^|\n)(- |\d+\. )/.test(f)?f:N.length===0?"> ":N.map(u=>`> ${u}`).join(`
|
|
`);return[`### ${x+1}. Clip`,E,"",`- created: ${i.createdAt}`,`- status: ${i.resolveStatus||"ok"}`].join(`
|
|
`)}function I({kind:i}){return i==="save"?e.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[e.jsx("path",{d:"M4 4h13l3 3v13H4z",fill:"none",stroke:"currentColor",strokeWidth:"1.8"}),e.jsx("path",{d:"M8 4h8v5H8zM8 14h8v6H8z",fill:"none",stroke:"currentColor",strokeWidth:"1.8"})]}):i==="settings"?e.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[e.jsx("path",{d:"M12 3l2 1 2-1 2 3-1 2 1 2 2 1v2l-2 1-1 2 1 2-2 3-2-1-2 1-2-1-2 1-2-3 1-2-1-2-2-1v-2l2-1 1-2-1-2 2-3 2 1z",fill:"none",stroke:"currentColor",strokeWidth:"1.4"}),e.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"none",stroke:"currentColor",strokeWidth:"1.8"})]}):i==="history"?e.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[e.jsx("path",{d:"M5 12a7 7 0 1 0 2-5",fill:"none",stroke:"currentColor",strokeWidth:"1.8"}),e.jsx("path",{d:"M5 4v4h4M12 8v5l3 2",fill:"none",stroke:"currentColor",strokeWidth:"1.8"})]}):i==="send"?e.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:e.jsx("path",{d:"M3 12h14M13 6l6 6-6 6",fill:"none",stroke:"currentColor",strokeWidth:"1.8"})}):e.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[e.jsx("path",{d:"M4 5h16v12H8l-4 3z",fill:"none",stroke:"currentColor",strokeWidth:"1.8"}),e.jsx("path",{d:"M8 9h8M8 12h6",fill:"none",stroke:"currentColor",strokeWidth:"1.8"})]})}function K(){const[i,x]=b.useState(null),[L,n]=b.useState(""),[f,N]=b.useState([]),[C,E]=b.useState(null),[u,H]=b.useState(""),[g,y]=b.useState([]),r=b.useRef(null);b.useEffect(()=>{J().then(x)},[]),b.useEffect(()=>{let t=null;const a=async()=>{const c=await d.runtime.sendMessage({type:"media:list"});c?.ok&&Array.isArray(c.items)&&N(c.items.slice(0,10))};return a(),t=window.setInterval(()=>{a()},2e3),()=>{t!==null&&window.clearInterval(t)}},[]),b.useEffect(()=>{const t=async()=>{const m=(await d.tabs.query({active:!0,currentWindow:!0}))[0],k=M(String(m?.url||""));if(E(Number.isInteger(m?.id)?m?.id:null),H(k),!k){y([]);return}const $=await d.runtime.sendMessage({type:"clip:list",pageUrl:k});$?.ok&&Array.isArray($.items)&&y($.items)};t();const a=window.setInterval(()=>{t()},2500);return()=>{window.clearInterval(a)}},[]);const s=(t,a)=>{x(c=>c&&{...c,[t]:a})},o=async t=>{if(!i)return;const a={...i,extensionStatus:t};x(a),await D({extensionStatus:t}),n(t?"Extension ON":"Extension OFF"),window.setTimeout(()=>n(""),1200)},l=async()=>{i&&(await D(i),n("Saved"),window.setTimeout(()=>n(""),1200))},p=async()=>{const t=d.runtime.getURL("src/config/index.html");await d.tabs.create({url:t})},h=async()=>{const t=d.runtime.getURL("src/history/index.html");await d.tabs.create({url:t})},S=async()=>{const t=await d.runtime.sendMessage({type:"page:enqueue-ytdlp"});n(t?.ok?"Active tab sent to gdown (yt-dlp)":`Send failed: ${t?.error||"unknown error"}`),window.setTimeout(()=>n(""),1800)},A=async t=>{const a=await d.runtime.sendMessage({type:"media:enqueue",url:t.url,referer:t.referer||"",kind:t.kind,suggestedOut:t.suggestedOut||"",cookie:t.cookie||"",userAgent:t.userAgent||""});n(a?.ok?"Media sent to gdown":`Send failed: ${a?.error||"unknown error"}`),window.setTimeout(()=>n(""),1600)},w=async()=>{await d.runtime.sendMessage({type:"media:clear"}),N([]),n("Captured media cleared"),window.setTimeout(()=>n(""),1200)},T=async()=>{B("onCreateClipFromSelection:clicked",{activeTabId:C,activePageUrl:u});const t=await d.runtime.sendMessage({type:"clip:create-active-tab"});if(B("onCreateClipFromSelection:result",t),!t?.ok){n(`클립 생성 실패: ${t?.error||"active tab unavailable"}`),window.setTimeout(()=>n(""),2e3);return}n("클립 저장 완료"),window.setTimeout(()=>n(""),1400);const a=await d.runtime.sendMessage({type:"clip:list",pageUrl:u});a?.ok&&Array.isArray(a.items)&&y(a.items)},U=async t=>{const a=await d.runtime.sendMessage({type:"clip:reveal",id:t});n(a?.ok?a.opened?"클립 페이지를 열었습니다":"클립 위치로 이동":`이동 실패: ${a?.error||"unknown error"}`),window.setTimeout(()=>n(""),1700)},q=async t=>{const a=await d.runtime.sendMessage({type:"clip:delete",id:t});if(!a?.ok){n(`삭제 실패: ${a?.error||"unknown error"}`),window.setTimeout(()=>n(""),1600);return}y(c=>c.filter(m=>m.id!==t)),n("클립 삭제 완료"),window.setTimeout(()=>n(""),1200)},j=async()=>{const t=await d.runtime.sendMessage({type:"clip:export"});if(!t?.ok||!Array.isArray(t.items)){n(`내보내기 실패: ${t?.error||"unknown error"}`),window.setTimeout(()=>n(""),1800);return}const a={exportedAt:new Date().toISOString(),version:1,count:t.items.length,clips:t.items},m=`gomdown-clips-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,k=await d.runtime.sendMessage({type:"file:download-text",filename:m,mime:"application/json;charset=utf-8",content:JSON.stringify(a,null,2)});if(!k?.ok){n(`내보내기 실패: ${k?.error||"download error"}`),window.setTimeout(()=>n(""),1800);return}n(`클립 ${t.items.length}개 내보내기 완료`),window.setTimeout(()=>n(""),1500)},v=()=>{r.current?.click()},P=async()=>{const t=g.filter(k=>M(k.pageUrl)===M(u));if(t.length===0){n("내보낼 클립이 없습니다."),window.setTimeout(()=>n(""),1500);return}const a=t[0]?.pageTitle||u||"Untitled",c=W(t,u),m=await d.runtime.sendMessage({type:"file:download-text",filename:`${G(a)}-clips.md`,mime:"text/markdown;charset=utf-8",content:c});if(!m?.ok){n(`Markdown 내보내기 실패: ${m?.error||"download error"}`),window.setTimeout(()=>n(""),1900);return}n(`Markdown 내보내기 완료 (${t.length}개)`),window.setTimeout(()=>n(""),1700)},O=async()=>{const t=g.filter(c=>M(c.pageUrl)===M(u));if(t.length===0){n("복사할 클립이 없습니다."),window.setTimeout(()=>n(""),1500);return}const a=W(t,u);try{await navigator.clipboard.writeText(a),n(`Markdown 복사 완료 (${t.length}개)`),window.setTimeout(()=>n(""),1700)}catch(c){n(`복사 실패: ${String(c)}`),window.setTimeout(()=>n(""),1700)}},F=async()=>{const t=g.filter(c=>M(c.pageUrl)===M(u));if(t.length===0){n("보낼 클립이 없습니다."),window.setTimeout(()=>n(""),1500);return}const a=t[0]?.pageTitle||u||"Untitled";try{const c=await d.runtime.sendMessage({type:"clip:send-obsidian-current-page",pageUrl:u,pageTitle:a});if(!c?.ok||!c?.uri){n(`Obsidian 전송 실패: ${c?.error||"unknown error"}`),window.setTimeout(()=>n(""),2200);return}window.open(String(c.uri),"_blank"),n("Obsidian 새 노트 전송 시도 완료")}catch(c){n(`Obsidian 전송 실패: ${String(c)}`);try{const m=await d.runtime.sendMessage({type:"clip:send-obsidian-current-page",pageUrl:u,pageTitle:a});m?.ok&&m.uri&&(window.location.href=String(m.uri),n("Obsidian 새 노트 전송 시도 완료"))}catch{}}finally{window.setTimeout(()=>n(""),1900)}},_=async t=>{const a=t.target.files?.[0];if(t.target.value="",!!a)try{const c=await a.text(),m=JSON.parse(c),k=Array.isArray(m)?m:Array.isArray(m?.clips)?m.clips:[];if(!Array.isArray(k)){n("가져오기 실패: JSON 형식이 올바르지 않습니다."),window.setTimeout(()=>n(""),1900);return}const $=await d.runtime.sendMessage({type:"clip:import",items:k});if(!$?.ok){n(`가져오기 실패: ${$?.error||"unknown error"}`),window.setTimeout(()=>n(""),1900);return}n(`가져오기 완료: ${$.imported||0}/${$.total||k.length}`),window.setTimeout(()=>n(""),1900);const R=await d.runtime.sendMessage({type:"clip:list",pageUrl:u});R?.ok&&Array.isArray(R.items)&&y(R.items)}catch(c){n(`가져오기 실패: ${String(c)}`),window.setTimeout(()=>n(""),1900)}};return i?e.jsxs("div",{className:"container",children:[e.jsxs("div",{className:"top-row",children:[e.jsx("h1",{children:"Gomdown Helper"}),e.jsxs("button",{className:`power-toggle ${i.extensionStatus?"on":"off"}`,onClick:()=>{o(!i.extensionStatus)},children:[e.jsx("span",{className:"power-dot"}),i.extensionStatus?"ON":"OFF"]})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:"RPC Secret"}),e.jsx("input",{type:"text",value:i.motrixAPIkey,onChange:t=>s("motrixAPIkey",t.target.value),placeholder:"aria2 rpc secret"})]}),e.jsxs("div",{className:"field",children:[e.jsx("label",{children:"RPC Port"}),e.jsx("input",{type:"number",value:i.motrixPort,onChange:t=>s("motrixPort",Number(t.target.value||16800))})]}),e.jsxs("label",{className:"toggle",children:["Use Native Host",e.jsx("input",{type:"checkbox",checked:i.useNativeHost,onChange:t=>s("useNativeHost",t.target.checked)})]}),e.jsxs("label",{className:"toggle",children:["Activate gdown App",e.jsx("input",{type:"checkbox",checked:i.activateAppOnDownload,onChange:t=>s("activateAppOnDownload",t.target.checked)})]}),e.jsxs("div",{className:"media-panel",children:[e.jsxs("div",{className:"media-head",children:[e.jsx("strong",{children:"Captured Media"}),e.jsx("button",{className:"mini ghost",onClick:w,children:"Clear"})]}),f.length===0?e.jsx("div",{className:"empty",children:"No media captured yet"}):e.jsx("div",{className:"media-list",children:f.map(t=>e.jsxs("div",{className:"media-item",children:[e.jsxs("div",{className:"media-meta",children:[e.jsx("span",{className:"kind",children:t.kind.toUpperCase()}),t.pageTitle?e.jsx("span",{className:"url",children:t.pageTitle}):null,e.jsx("span",{className:"url",children:t.url})]}),e.jsx("button",{className:"mini",onClick:()=>{A(t)},children:"Add"})]},t.id))})]}),e.jsxs("div",{className:"media-panel",children:[e.jsxs("div",{className:"page-clips-head",children:[e.jsxs("div",{className:"page-clips-title-row",children:[e.jsx("strong",{children:"Page Clips"}),e.jsx("span",{className:"hint",children:"Alt+Shift+C"})]}),e.jsxs("div",{className:"page-clips-actions",children:[e.jsx("button",{className:"mini ghost page-action-btn",onClick:()=>{F()},children:"Obsidian"}),e.jsx("button",{className:"mini ghost page-action-btn",onClick:()=>{O()},children:"Copy MD"}),e.jsx("button",{className:"mini ghost page-action-btn",onClick:()=>{P()},children:"MD"}),e.jsx("button",{className:"mini ghost page-action-btn",onClick:()=>{j()},children:"Export"}),e.jsx("button",{className:"mini ghost page-action-btn page-action-btn-wide",onClick:v,children:"Import"})]})]}),e.jsx("input",{ref:r,type:"file",accept:"application/json,.json",style:{display:"none"},onChange:_}),g.length===0?e.jsx("div",{className:"empty",children:"No clips for this page"}):e.jsx("div",{className:"media-list",children:g.map(t=>e.jsxs("div",{className:"clip-item",children:[e.jsxs("div",{className:"media-meta",children:[t.resolveStatus==="broken"?e.jsx("span",{className:"broken-badge",children:"BROKEN"}):null,e.jsx("span",{className:"url",children:t.quote||t.anchor.exact})]}),e.jsxs("div",{className:"clip-actions",children:[e.jsx("button",{className:"mini",onClick:()=>{U(t.id)},children:"Go"}),e.jsx("button",{className:"mini ghost",onClick:()=>{q(t.id)},children:"Del"})]})]},t.id))})]}),e.jsx("div",{className:"status",children:L}),e.jsxs("div",{className:"action-dock",children:[e.jsxs("button",{className:"action-btn",onClick:l,title:"Save",children:[e.jsx(I,{kind:"save"}),e.jsx("span",{children:"Save"})]}),e.jsxs("button",{className:"action-btn",onClick:p,title:"Settings",children:[e.jsx(I,{kind:"settings"}),e.jsx("span",{children:"Settings"})]}),e.jsxs("button",{className:"action-btn",onClick:h,title:"History",children:[e.jsx(I,{kind:"history"}),e.jsx("span",{children:"History"})]}),e.jsxs("button",{className:"action-btn",onClick:()=>{S()},title:"Send Active",children:[e.jsx(I,{kind:"send"}),e.jsx("span",{children:"Send"})]}),e.jsxs("button",{className:"action-btn",onClick:()=>{T()},title:"Capture Selection",children:[e.jsx(I,{kind:"clip"}),e.jsx("span",{children:"Capture"})]})]})]}):e.jsx("div",{className:"container",children:"Loading..."})}z.createRoot(document.getElementById("root")).render(e.jsx(b.StrictMode,{children:e.jsx(K,{})}));
|