From c99f4b763377b246319e76fb537d14317b8acb5f Mon Sep 17 00:00:00 2001 From: lencx Date: Sun, 8 Jan 2023 17:04:49 +0800 Subject: [PATCH] chore: scripts --- src-tauri/src/assets/cmd.js | 280 ---------------------- src-tauri/src/assets/core.js | 103 -------- src-tauri/src/assets/dalle2.js | 40 ---- src-tauri/src/assets/export.js | 287 ----------------------- src-tauri/src/assets/popup.core.js | 84 ------- src-tauri/src/scripts/core.js | 2 +- src-tauri/src/scripts/dalle2.js | 2 +- src-tauri/src/scripts/export.js | 108 ++++----- src-tauri/src/scripts/markdown.export.js | 8 +- src-tauri/src/vendors/turndown.js | 1 + 10 files changed, 63 insertions(+), 852 deletions(-) delete mode 100644 src-tauri/src/assets/cmd.js delete mode 100644 src-tauri/src/assets/core.js delete mode 100644 src-tauri/src/assets/dalle2.js delete mode 100644 src-tauri/src/assets/export.js delete mode 100644 src-tauri/src/assets/popup.core.js create mode 100644 src-tauri/src/vendors/turndown.js diff --git a/src-tauri/src/assets/cmd.js b/src-tauri/src/assets/cmd.js deleted file mode 100644 index 4588e5a..0000000 --- a/src-tauri/src/assets/cmd.js +++ /dev/null @@ -1,280 +0,0 @@ -// *** Core Script - CMD *** - -function init() { - const styleDom = document.createElement('style'); - styleDom.innerHTML = `form { - position: relative; - } - .chat-model-cmd-list { - position: absolute; - bottom: 60px; - max-height: 100px; - overflow: auto; - z-index: 9999; - } - .chat-model-cmd-list>div { - border: solid 2px rgba(80,80,80,.3); - border-radius: 5px; - background-color: #fff; - } - - html.dark .chat-model-cmd-list>div { - background-color: #4a4a4a; - } - html.dark .chat-model-cmd-list .cmd-item { - border-color: #666; - } - html.dark .chat-model-cmd-list .cmd-item b { - color: #e8e8e8; - } - html.dark .chat-model-cmd-list .cmd-item i { - color: #999; - } - html.dark .chat-model-cmd-list .cmd-item.selected { - background: rgba(59,130,246,.5); - } - - .chat-model-cmd-list .cmd-item { - font-size: 12px; - border-bottom: solid 1px rgba(80,80,80,.2); - padding: 2px 4px; - display: flex; - user-select: none; - cursor: pointer; - } - .chat-model-cmd-list .cmd-item:last-child { - border-bottom: none; - } - .chat-model-cmd-list .cmd-item.selected { - background: rgba(59,130,246,.3); - } - .chat-model-cmd-list .cmd-item b { - display: inline-block; - width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - border-radius: 4px; - margin-right: 10px; - color: #2a2a2a; - } - .chat-model-cmd-list .cmd-item i { - width: 100%; - max-width: 200px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - text-align: right; - color: #888; - } - .chatappico { - width: 20px; - height: 20px; - } - .chatappico.pdf { - width: 24px; - height: 24px; - } - @media screen and (max-width: 767px) { - #download-png-button, #download-pdf-button, #download-html-button { - display: none; - } - } - `; - document.head.append(styleDom); - - if (window.formInterval) { - clearInterval(window.formInterval); - } - window.formInterval = setInterval(() => { - const form = document.querySelector("form"); - if (!form) return; - clearInterval(window.formInterval); - cmdTip(); - }, 200); -} - -async function cmdTip() { - const chatModelJson = await invoke('get_chat_model_cmd') || {}; - const data = chatModelJson.data; - if (data.length <= 0) return; - - const modelDom = document.createElement('div'); - modelDom.classList.add('chat-model-cmd-list'); - - // fix: tray window - if (__TAURI_METADATA__.__currentWindow.label === 'tray') { - modelDom.style.bottom = '54px'; - } - - document.querySelector('form').appendChild(modelDom); - const itemDom = (v) => `
/${v.cmd}${v.act}
`; - const renderList = (v) => { - modelDom.innerHTML = `
${v.map(itemDom).join('')}
`; - window.__CHAT_MODEL_CMD_PROMPT__ = v[0]?.prompt.trim(); - window.__CHAT_MODEL_CMD__ = v[0]?.cmd.trim(); - window.__list = modelDom.querySelectorAll('.cmd-item'); - window.__index = 0; - window.__list[window.__index].classList.add('selected'); - }; - const setPrompt = (v = '') => { - if (v.trim()) { - window.__CHAT_MODEL_CMD_PROMPT__ = window.__CHAT_MODEL_CMD_PROMPT__?.replace(/\{([^{}]*)\}/, `{${v.trim()}}`); - } - } - const searchInput = document.querySelector('form textarea'); - - // Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`. - // If more than one command appears in the search results, the first one will be used by default. - searchInput.addEventListener('keydown', (event) => { - if (!window.__CHAT_MODEL_CMD_PROMPT__) { - return; - } - - // ------------------ Keyboard scrolling (ArrowUp | ArrowDown) -------------------------- - if (event.keyCode === 38 && window.__index > 0) { // ArrowUp - window.__list[window.__index].classList.remove('selected'); - window.__index = window.__index - 1; - window.__list[window.__index].classList.add('selected'); - window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__list[window.__index].getAttribute('data-prompt')); - searchInput.value = `/${window.__list[window.__index].getAttribute('data-cmd')}`; - event.preventDefault(); - } - - if (event.keyCode === 40 && window.__index < window.__list.length - 1) { // ArrowDown - window.__list[window.__index].classList.remove('selected'); - window.__index = window.__index + 1; - window.__list[window.__index].classList.add('selected'); - window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__list[window.__index].getAttribute('data-prompt')); - searchInput.value = `/${window.__list[window.__index].getAttribute('data-cmd')}`; - event.preventDefault(); - } - - const containerHeight = modelDom.offsetHeight; - const itemHeight = window.__list[0].offsetHeight + 1; - - const itemTop = window.__list[window.__index].offsetTop; - const itemBottom = itemTop + itemHeight; - if (itemTop < modelDom.scrollTop || itemBottom > modelDom.scrollTop + containerHeight) { - modelDom.scrollTop = itemTop; - } - - // ------------------ TAB key replaces `{q}` tag content ------------------------------- - // feat: https://github.com/lencx/ChatGPT/issues/54 - if (event.keyCode === 9 && !window.__CHAT_MODEL_STATUS__) { - const strGroup = window.__CHAT_MODEL_CMD_PROMPT__.match(/\{([^{}]*)\}/) || []; - - if (strGroup[1]) { - searchInput.value = `/${window.__CHAT_MODEL_CMD__}` + ` {${strGroup[1]}}` + ' |-> '; - window.__CHAT_MODEL_STATUS__ = 1; - } - event.preventDefault(); - } - - if (window.__CHAT_MODEL_STATUS__ === 1 && event.keyCode === 9) { // TAB - const data = searchInput.value.split('|->'); - if (data[1]?.trim()) { - setPrompt(data[1]); - window.__CHAT_MODEL_STATUS__ = 2; - } - event.preventDefault(); - } - - // input text - if (window.__CHAT_MODEL_STATUS__ === 2 && event.keyCode === 9) { // TAB - searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__; - modelDom.innerHTML = ''; - delete window.__CHAT_MODEL_STATUS__; - event.preventDefault(); - } - - // ------------------ type in a space to complete the fill ------------------------------------ - if (event.keyCode === 32) { - searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__; - modelDom.innerHTML = ''; - delete window.__CHAT_MODEL_CMD_PROMPT__; - } - - // ------------------ send -------------------------------------------------------------------- - if (event.keyCode === 13 && window.__CHAT_MODEL_CMD_PROMPT__) { // Enter - const data = searchInput.value.split('|->'); - setPrompt(data[1]); - - searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__; - modelDom.innerHTML = ''; - delete window.__CHAT_MODEL_CMD_PROMPT__; - delete window.__CHAT_MODEL_CMD__; - delete window.__CHAT_MODEL_STATUS__; - event.preventDefault(); - } - }); - - searchInput.addEventListener('input', () => { - if (searchInput.value === '') { - delete window.__CHAT_MODEL_CMD_PROMPT__; - delete window.__CHAT_MODEL_CMD__; - delete window.__CHAT_MODEL_STATUS__; - } - - if (window.__CHAT_MODEL_STATUS__) return; - - const query = searchInput.value; - if (!query || !/^\//.test(query)) { - modelDom.innerHTML = ''; - return; - } - - // all cmd result - if (query === '/') { - renderList(data); - return; - } - - const result = data.filter(i => new RegExp(query.substring(1)).test(i.cmd)); - if (result.length > 0) { - renderList(result); - } else { - modelDom.innerHTML = ''; - delete window.__CHAT_MODEL_CMD_PROMPT__; - delete window.__CHAT_MODEL_CMD__; - delete window.__CHAT_MODEL_STATUS__; - } - }, { - capture: false, - passive: true, - once: false - }); - - if (window.searchInterval) { - clearInterval(window.searchInterval); - } - window.searchInterval = setInterval(() => { - // The `chatgpt prompt` fill can be done by clicking on the event. - const searchDom = document.querySelector("form .chat-model-cmd-list>div"); - if (!searchDom) return; - searchDom.addEventListener('click', (event) => { - // .cmd-item - const item = event.target.closest("div"); - if (item) { - const val = decodeURIComponent(item.getAttribute('data-prompt')); - searchInput.value = val; - document.querySelector('form textarea').focus(); - window.__CHAT_MODEL_CMD_PROMPT__ = val; - modelDom.innerHTML = ''; - } - }, { - capture: false, - passive: true, - once: false - }); - }, 200); -} - -if ( - document.readyState === "complete" || - document.readyState === "interactive" -) { - init(); -} else { - document.addEventListener("DOMContentLoaded", init); -} \ No newline at end of file diff --git a/src-tauri/src/assets/core.js b/src-tauri/src/assets/core.js deleted file mode 100644 index 335daa8..0000000 --- a/src-tauri/src/assets/core.js +++ /dev/null @@ -1,103 +0,0 @@ -// *** Core Script - IPC *** - -const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0]; -function transformCallback(callback = () => {}, once = false) { - const identifier = uid(); - const prop = `_${identifier}`; - Object.defineProperty(window, prop, { - value: (result) => { - if (once) { - Reflect.deleteProperty(window, prop); - } - return callback(result) - }, - writable: false, - configurable: true, - }) - return identifier; -} -async function invoke(cmd, args) { - return new Promise((resolve, reject) => { - if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!'); - const callback = transformCallback((e) => { - resolve(e); - Reflect.deleteProperty(window, `_${error}`); - }, true) - const error = transformCallback((e) => { - reject(e); - Reflect.deleteProperty(window, `_${callback}`); - }, true) - window.__TAURI_POST_MESSAGE__({ - cmd, - callback, - error, - ...args - }); - }); -} - -window.uid = uid; -window.invoke = invoke; -window.transformCallback = transformCallback; - -async function init() { - if (__TAURI_METADATA__.__currentWindow.label === 'tray') { - document.getElementsByTagName('html')[0].style['font-size'] = '70%'; - } - - if (__TAURI_METADATA__.__currentWindow.label !== 'core') return; - - async function platform() { - return invoke('platform', { - __tauriModule: 'Os', - message: { cmd: 'platform' } - }); - } - - const _platform = await platform(); - const chatConf = await invoke('get_chat_conf') || {}; - if (/darwin/.test(_platform) && !chatConf.titlebar) { - const topStyleDom = document.createElement("style"); - topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`; - document.head.appendChild(topStyleDom); - const topDom = document.createElement("div"); - topDom.id = "chatgpt-app-window-top"; - document.body.appendChild(topDom); - - topDom.addEventListener("mousedown", () => invoke("drag_window")); - topDom.addEventListener("touchstart", () => invoke("drag_window")); - topDom.addEventListener("dblclick", () => invoke("fullscreen")); - } - - document.addEventListener("click", (e) => { - const origin = e.target.closest("a"); - if (!origin.target) return; - if (origin && origin.href && origin.target !== '_self') { - invoke('open_link', { url: origin.href }); - } - }); - - document.addEventListener('wheel', function(event) { - const deltaX = event.wheelDeltaX; - if (Math.abs(deltaX) >= 50) { - if (deltaX > 0) { - window.history.go(-1); - } else { - window.history.go(1); - } - } - }); - - window.__sync_prompts = async function() { - await invoke('sync_prompts', { time: Date.now() }); - } -} - -if ( - document.readyState === "complete" || - document.readyState === "interactive" -) { - init(); -} else { - document.addEventListener("DOMContentLoaded", init); -} \ No newline at end of file diff --git a/src-tauri/src/assets/dalle2.js b/src-tauri/src/assets/dalle2.js deleted file mode 100644 index e95d4c0..0000000 --- a/src-tauri/src/assets/dalle2.js +++ /dev/null @@ -1,40 +0,0 @@ -// *** Core Script - DALL·E 2 *** - -async function init() { - document.addEventListener("click", (e) => { - const origin = e.target.closest("a"); - if (!origin.target) return; - if (origin && origin.href && origin.target !== '_self') { - if (/\/(login|signup)$/.test(window.location.href)) { - origin.target = '_self'; - } else { - invoke('open_link', { url: origin.href }); - } - } - }); - - if (window.searchInterval) { - clearInterval(window.searchInterval); - } - - window.searchInterval = setInterval(() => { - const searchInput = document.querySelector('.image-prompt-form-wrapper form>.text-input'); - if (searchInput) { - clearInterval(window.searchInterval); - - if (!window.__CHATGPT_QUERY__) return; - const query = decodeURIComponent(window.__CHATGPT_QUERY__); - searchInput.focus(); - searchInput.value = query; - } - }, 200) -} - -if ( - document.readyState === "complete" || - document.readyState === "interactive" -) { - init(); -} else { - document.addEventListener("DOMContentLoaded", init); -} diff --git a/src-tauri/src/assets/export.js b/src-tauri/src/assets/export.js deleted file mode 100644 index 8c2a903..0000000 --- a/src-tauri/src/assets/export.js +++ /dev/null @@ -1,287 +0,0 @@ -// *** Core Script - Export *** -// @ref: https://github.com/liady/ChatGPT-pdf - -const buttonOuterHTMLFallback = ``; -async function init() { - if (window.innerWidth < 767) return; - const chatConf = await invoke('get_chat_conf') || {}; - if (window.buttonsInterval) { - clearInterval(window.buttonsInterval); - } - window.buttonsInterval = setInterval(() => { - const actionsArea = document.querySelector("form>div>div"); - if (!actionsArea) { - return; - } - if (shouldAddButtons(actionsArea)) { - let TryAgainButton = actionsArea.querySelector("button"); - if (!TryAgainButton) { - const parentNode = document.createElement("div"); - parentNode.innerHTML = buttonOuterHTMLFallback; - TryAgainButton = parentNode.querySelector("button"); - } - addActionsButtons(actionsArea, TryAgainButton, chatConf); - } else if (shouldRemoveButtons()) { - removeButtons(); - } - }, 200); -} - -const Format = { - PNG: "png", - PDF: "pdf", -}; - -function shouldRemoveButtons() { - const isOpenScreen = document.querySelector("h1.text-4xl"); - if(isOpenScreen){ - return true; - } - const inConversation = document.querySelector("form button>div"); - if(inConversation){ - return true; - } - return false; -} - -function shouldAddButtons(actionsArea) { - // first, check if there's a "Try Again" button and no other buttons - const buttons = actionsArea.querySelectorAll("button"); - const hasTryAgainButton = Array.from(buttons).some((button) => { - return !button.id?.includes("download"); - }); - if (hasTryAgainButton && buttons.length === 1) { - return true; - } - - // otherwise, check if open screen is not visible - const isOpenScreen = document.querySelector("h1.text-4xl"); - if (isOpenScreen) { - return false; - } - - // check if the conversation is finished and there are no share buttons - const finishedConversation = document.querySelector("form button>svg"); - const hasShareButtons = actionsArea.querySelectorAll("button[share-ext]"); - if (finishedConversation && !hasShareButtons.length) { - return true; - } - - return false; -} - -function removeButtons() { - const downloadButton = document.getElementById("download-png-button"); - const downloadPdfButton = document.getElementById("download-pdf-button"); - const downloadHtmlButton = document.getElementById("download-html-button"); - if (downloadButton) { - downloadButton.remove(); - } - if (downloadPdfButton) { - downloadPdfButton.remove(); - } - if (downloadHtmlButton) { - downloadHtmlButton.remove(); - } -} - -function addActionsButtons(actionsArea, TryAgainButton) { - const downloadButton = TryAgainButton.cloneNode(true); - downloadButton.id = "download-png-button"; - downloadButton.setAttribute("share-ext", "true"); - // downloadButton.innerText = "Generate PNG"; - downloadButton.title = "Generate PNG"; - downloadButton.innerHTML = setIcon('png'); - downloadButton.onclick = () => { - downloadThread(); - }; - actionsArea.appendChild(downloadButton); - const downloadPdfButton = TryAgainButton.cloneNode(true); - downloadPdfButton.id = "download-pdf-button"; - downloadButton.setAttribute("share-ext", "true"); - // downloadPdfButton.innerText = "Download PDF"; - downloadPdfButton.title = "Download PDF"; - downloadPdfButton.innerHTML = setIcon('pdf'); - downloadPdfButton.onclick = () => { - downloadThread({ as: Format.PDF }); - }; - actionsArea.appendChild(downloadPdfButton); - const exportHtml = TryAgainButton.cloneNode(true); - exportHtml.id = "download-html-button"; - downloadButton.setAttribute("share-ext", "true"); - // exportHtml.innerText = "Share Link"; - exportHtml.title = "Share Link"; - exportHtml.innerHTML = setIcon('link'); - exportHtml.onclick = () => { - sendRequest(); - }; - actionsArea.appendChild(exportHtml); -} - -function downloadThread({ as = Format.PNG } = {}) { - const elements = new Elements(); - elements.fixLocation(); - const pixelRatio = window.devicePixelRatio; - const minRatio = as === Format.PDF ? 2 : 2.5; - window.devicePixelRatio = Math.max(pixelRatio, minRatio); - - html2canvas(elements.thread, { - letterRendering: true, - }).then(async function (canvas) { - elements.restoreLocation(); - window.devicePixelRatio = pixelRatio; - const imgData = canvas.toDataURL("image/png"); - requestAnimationFrame(() => { - if (as === Format.PDF) { - return handlePdf(imgData, canvas, pixelRatio); - } else { - handleImg(imgData); - } - }); - }); -} - -function handleImg(imgData) { - const binaryData = atob(imgData.split("base64,")[1]); - const data = []; - for (let i = 0; i < binaryData.length; i++) { - data.push(binaryData.charCodeAt(i)); - } - invoke('download', { name: `chatgpt-${Date.now()}.png`, blob: Array.from(new Uint8Array(data)) }); -} - -function handlePdf(imgData, canvas, pixelRatio) { - const { jsPDF } = window.jspdf; - const orientation = canvas.width > canvas.height ? "l" : "p"; - var pdf = new jsPDF(orientation, "pt", [ - canvas.width / pixelRatio, - canvas.height / pixelRatio, - ]); - var pdfWidth = pdf.internal.pageSize.getWidth(); - var pdfHeight = pdf.internal.pageSize.getHeight(); - pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight, '', 'FAST'); - - const data = pdf.__private__.getArrayBuffer(pdf.__private__.buildDocument()); - invoke('download', { name: `chatgpt-${Date.now()}.pdf`, blob: Array.from(new Uint8Array(data)) }); -} - -class Elements { - constructor() { - this.init(); - } - init() { - // this.threadWrapper = document.querySelector(".cdfdFe"); - this.spacer = document.querySelector(".w-full.h-48.flex-shrink-0"); - this.thread = document.querySelector( - "[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div" - ); - this.positionForm = document.querySelector("form").parentNode; - // this.styledThread = document.querySelector("main"); - // this.threadContent = document.querySelector(".gAnhyd"); - this.scroller = Array.from( - document.querySelectorAll('[class*="react-scroll-to"]') - ).filter((el) => el.classList.contains("h-full"))[0]; - this.hiddens = Array.from(document.querySelectorAll(".overflow-hidden")); - this.images = Array.from(document.querySelectorAll("img[srcset]")); - } - fixLocation() { - this.hiddens.forEach((el) => { - el.classList.remove("overflow-hidden"); - }); - this.spacer.style.display = "none"; - this.thread.style.maxWidth = "960px"; - this.thread.style.marginInline = "auto"; - this.positionForm.style.display = "none"; - this.scroller.classList.remove("h-full"); - this.scroller.style.minHeight = "100vh"; - this.images.forEach((img) => { - const srcset = img.getAttribute("srcset"); - img.setAttribute("srcset_old", srcset); - img.setAttribute("srcset", ""); - }); - //Fix to the text shifting down when generating the canvas - document.body.style.lineHeight = "0.5"; - } - restoreLocation() { - this.hiddens.forEach((el) => { - el.classList.add("overflow-hidden"); - }); - this.spacer.style.display = null; - this.thread.style.maxWidth = null; - this.thread.style.marginInline = null; - this.positionForm.style.display = null; - this.scroller.classList.add("h-full"); - this.scroller.style.minHeight = null; - this.images.forEach((img) => { - const srcset = img.getAttribute("srcset_old"); - img.setAttribute("srcset", srcset); - img.setAttribute("srcset_old", ""); - }); - document.body.style.lineHeight = null; - } -} - -function selectElementByClassPrefix(classPrefix) { - const element = document.querySelector(`[class^='${classPrefix}']`); - return element; -} - -async function sendRequest() { - const data = getData(); - const uploadUrlResponse = await fetch( - "https://chatgpt-static.s3.amazonaws.com/url.txt" - ); - const uploadUrl = await uploadUrlResponse.text(); - fetch(uploadUrl, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(data), - }) - .then((response) => response.json()) - .then((data) => { - invoke('open_link', { url: data.url }); - }); -} - -function getData() { - const globalCss = getCssFromSheet( - document.querySelector("link[rel=stylesheet]").sheet - ); - const localCss = - getCssFromSheet( - document.querySelector(`style[data-styled][data-styled-version]`).sheet - ) || "body{}"; - const data = { - main: document.querySelector("main").outerHTML, - // css: `${globalCss} /* GLOBAL-LOCAL */ ${localCss}`, - globalCss, - localCss, - }; - return data; -} - -function getCssFromSheet(sheet) { - return Array.from(sheet.cssRules) - .map((rule) => rule.cssText) - .join(""); -} - -// run init -if ( - document.readyState === "complete" || - document.readyState === "interactive" -) { - init(); -} else { - document.addEventListener("DOMContentLoaded", init); -} - -function setIcon(type) { - return { - link: ``, - png: ``, - pdf: `` - }[type]; -} diff --git a/src-tauri/src/assets/popup.core.js b/src-tauri/src/assets/popup.core.js deleted file mode 100644 index 3eb7b02..0000000 --- a/src-tauri/src/assets/popup.core.js +++ /dev/null @@ -1,84 +0,0 @@ -// *** Core Script - DALL·E 2 Core *** - -async function init() { - const chatConf = await invoke('get_chat_conf') || {}; - if (!chatConf.popup_search) return; - if (!window.FloatingUIDOM) return; - - const styleDom = document.createElement('style'); - styleDom.innerHTML = ` - #chagpt-selection-menu { - display: none; - width: max-content; - position: absolute; - top: 0; - left: 0; - background: #4a4a4a; - color: white; - font-weight: bold; - padding: 5px 8px; - border-radius: 4px; - font-size: 12px; - cursor: pointer; - } - `; - document.head.append(styleDom); - - const selectionMenu = document.createElement('div'); - selectionMenu.id = 'chagpt-selection-menu'; - selectionMenu.innerHTML = 'DALL·E 2'; - document.body.appendChild(selectionMenu); - const { computePosition, flip, offset, shift } = window.FloatingUIDOM; - - document.body.addEventListener('mousedown', async (e) => { - if (e.target.id === 'chagpt-selection-menu') { - await invoke('dalle2_window', { query: encodeURIComponent(window.__DALLE2_CONTENT__) }); - } else { - delete window.__DALLE2_CONTENT__; - } - }); - - document.body.addEventListener("mouseup", async (e) => { - selectionMenu.style.display = 'none'; - const selection = window.getSelection(); - window.__DALLE2_CONTENT__ = selection.toString().trim(); - - if (!window.__DALLE2_CONTENT__) return; - - if (selection.rangeCount > 0) { - const range = selection.getRangeAt(0); - const rect = range.getClientRects()[0]; - - const rootEl = document.createElement('div'); - rootEl.style.top = `${rect.top}px`; - rootEl.style.position = 'fixed'; - rootEl.style.left = `${rect.left}px`; - document.body.appendChild(rootEl); - - selectionMenu.style.display = 'block'; - computePosition(rootEl, selectionMenu, { - placement: 'top', - middleware: [ - flip(), - offset(5), - shift({ padding: 5 }) - ] - }).then(({x, y}) => { - Object.assign(selectionMenu.style, { - left: `${x}px`, - top: `${y}px`, - }); - }); - } - }); - -} - -if ( - document.readyState === "complete" || - document.readyState === "interactive" -) { - init(); -} else { - document.addEventListener("DOMContentLoaded", init); -} \ No newline at end of file diff --git a/src-tauri/src/scripts/core.js b/src-tauri/src/scripts/core.js index ad8ed4b..d69f37e 100644 --- a/src-tauri/src/scripts/core.js +++ b/src-tauri/src/scripts/core.js @@ -71,7 +71,7 @@ $(async function () { document.addEventListener("click", (e) => { const origin = e.target.closest("a"); - if (!origin.target) return; + if (!origin || !origin.target) return; if (origin && origin.href && origin.target !== '_self') { invoke('open_link', { url: origin.href }); } diff --git a/src-tauri/src/scripts/dalle2.js b/src-tauri/src/scripts/dalle2.js index 1b77067..ca11cd4 100644 --- a/src-tauri/src/scripts/dalle2.js +++ b/src-tauri/src/scripts/dalle2.js @@ -3,7 +3,7 @@ $(function () { document.addEventListener("click", (e) => { const origin = e.target.closest("a"); - if (!origin.target) return; + if (!origin || !origin.target) return; if (origin && origin.href && origin.target !== '_self') { if (/\/(login|signup)$/.test(window.location.href)) { origin.target = '_self'; diff --git a/src-tauri/src/scripts/export.js b/src-tauri/src/scripts/export.js index b6633d2..c94a3a4 100644 --- a/src-tauri/src/scripts/export.js +++ b/src-tauri/src/scripts/export.js @@ -74,16 +74,16 @@ function shouldAddButtons(actionsArea) { function removeButtons() { const downloadButton = document.getElementById("download-png-button"); const downloadPdfButton = document.getElementById("download-pdf-button"); - const downloadHtmlButton = document.getElementById("download-html-button"); + // const downloadHtmlButton = document.getElementById("download-html-button"); if (downloadButton) { downloadButton.remove(); } if (downloadPdfButton) { downloadPdfButton.remove(); } - if (downloadHtmlButton) { - downloadHtmlButton.remove(); - } + // if (downloadHtmlButton) { + // downloadHtmlButton.remove(); + // } } function addActionsButtons(actionsArea, TryAgainButton) { @@ -107,16 +107,16 @@ function addActionsButtons(actionsArea, TryAgainButton) { downloadThread({ as: Format.PDF }); }; actionsArea.appendChild(downloadPdfButton); - const exportHtml = TryAgainButton.cloneNode(true); - exportHtml.id = "download-html-button"; - downloadButton.setAttribute("share-ext", "true"); - // exportHtml.innerText = "Share Link"; - exportHtml.title = "Share Link"; - exportHtml.innerHTML = setIcon('link'); - exportHtml.onclick = () => { - sendRequest(); - }; - actionsArea.appendChild(exportHtml); + // const exportHtml = TryAgainButton.cloneNode(true); + // exportHtml.id = "download-html-button"; + // downloadButton.setAttribute("share-ext", "true"); + // // exportHtml.innerText = "Share Link"; + // exportHtml.title = "Share Link"; + // exportHtml.innerHTML = setIcon('link'); + // exportHtml.onclick = () => { + // sendRequest(); + // }; + // actionsArea.appendChild(exportHtml); } function downloadThread({ as = Format.PNG } = {}) { @@ -227,51 +227,51 @@ function selectElementByClassPrefix(classPrefix) { return element; } -async function sendRequest() { - const data = getData(); - const uploadUrlResponse = await fetch( - "https://chatgpt-static.s3.amazonaws.com/url.txt" - ); - const uploadUrl = await uploadUrlResponse.text(); - fetch(uploadUrl, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(data), - }) - .then((response) => response.json()) - .then((data) => { - invoke('open_link', { url: data.url }); - }); -} +// async function sendRequest() { +// const data = getData(); +// const uploadUrlResponse = await fetch( +// "https://chatgpt-static.s3.amazonaws.com/url.txt" +// ); +// const uploadUrl = await uploadUrlResponse.text(); +// fetch(uploadUrl, { +// method: "POST", +// headers: { +// "Content-Type": "application/json", +// }, +// body: JSON.stringify(data), +// }) +// .then((response) => response.json()) +// .then((data) => { +// invoke('open_link', { url: data.url }); +// }); +// } -function getData() { - const globalCss = getCssFromSheet( - document.querySelector("link[rel=stylesheet]").sheet - ); - const localCss = - getCssFromSheet( - document.querySelector(`style[data-styled][data-styled-version]`).sheet - ) || "body{}"; - const data = { - main: document.querySelector("main").outerHTML, - // css: `${globalCss} /* GLOBAL-LOCAL */ ${localCss}`, - globalCss, - localCss, - }; - return data; -} +// function getData() { +// const globalCss = getCssFromSheet( +// document.querySelector("link[rel=stylesheet]").sheet +// ); +// const localCss = +// getCssFromSheet( +// document.querySelector(`style[data-styled][data-styled-version]`).sheet +// ) || "body{}"; +// const data = { +// main: document.querySelector("main").outerHTML, +// // css: `${globalCss} /* GLOBAL-LOCAL */ ${localCss}`, +// globalCss, +// localCss, +// }; +// return data; +// } -function getCssFromSheet(sheet) { - return Array.from(sheet.cssRules) - .map((rule) => rule.cssText) - .join(""); -} +// function getCssFromSheet(sheet) { +// return Array.from(sheet.cssRules) +// .map((rule) => rule.cssText) +// .join(""); +// } function setIcon(type) { return { - link: ``, + // link: ``, png: ``, pdf: `` }[type]; diff --git a/src-tauri/src/scripts/markdown.export.js b/src-tauri/src/scripts/markdown.export.js index eb46ac2..4137987 100644 --- a/src-tauri/src/scripts/markdown.export.js +++ b/src-tauri/src/scripts/markdown.export.js @@ -1,5 +1,9 @@ // *** Core Script - Markdown *** -$(function() { +(function () { console.log("markdown"); -}); \ No newline at end of file + const chatThread = $('main .items-center'); + const chatBlocks = $(chatThread, '>div'); + + console.log('«8» /src/scripts/markdown.export.js ~> ', chatBlocks); +})(window); \ No newline at end of file diff --git a/src-tauri/src/vendors/turndown.js b/src-tauri/src/vendors/turndown.js new file mode 100644 index 0000000..92acdf4 --- /dev/null +++ b/src-tauri/src/vendors/turndown.js @@ -0,0 +1 @@ +var TurndownService=function(){"use strict";function u(e,n){return Array(n+1).join(e)}var n=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function o(e){return l(e,n)}var r=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function i(e){return l(e,r)}var a=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function l(e,n){return 0<=n.indexOf(e.nodeName)}function c(n,e){return n.getElementsByTagName&&e.some(function(e){return n.getElementsByTagName(e).length})}var t={};function s(e){return e?e.replace(/(\n+\s*)+/g,"\n"):""}function f(e){for(var n in this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[],e.rules)this.array.push(e.rules[n])}function d(e,n,t){for(var r=0;r "))+"\n\n"}},t.list={filter:["ul","ol"],replacement:function(e,n){var t=n.parentNode;return"LI"===t.nodeName&&t.lastElementChild===n?"\n"+e:"\n\n"+e+"\n\n"}},t.listItem={filter:"li",replacement:function(e,n,t){e=e.replace(/^\n+/,"").replace(/\n+$/,"\n").replace(/\n/gm,"\n ");var r=t.bulletListMarker+" ",i=n.parentNode;return"OL"===i.nodeName&&(t=i.getAttribute("start"),i=Array.prototype.indexOf.call(i.children,n),r=(t?Number(t)+i:i+1)+". "),r+e+(n.nextSibling&&!/\n$/.test(e)?"\n":"")}},t.indentedCodeBlock={filter:function(e,n){return"indented"===n.codeBlockStyle&&"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName},replacement:function(e,n,t){return"\n\n "+n.firstChild.textContent.replace(/\n/g,"\n ")+"\n\n"}},t.fencedCodeBlock={filter:function(e,n){return"fenced"===n.codeBlockStyle&&"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName},replacement:function(e,n,t){for(var r,i=((n.firstChild.getAttribute("class")||"").match(/language-(\S+)/)||[null,""])[1],o=n.firstChild.textContent,t=t.fence.charAt(0),a=3,l=new RegExp("^"+t+"{3,}","gm");r=l.exec(o);)r[0].length>=a&&(a=r[0].length+1);t=u(t,a);return"\n\n"+t+i+"\n"+o.replace(/\n$/,"")+"\n"+t+"\n\n"}},t.horizontalRule={filter:"hr",replacement:function(e,n,t){return"\n\n"+t.hr+"\n\n"}},t.inlineLink={filter:function(e,n){return"inlined"===n.linkStyle&&"A"===e.nodeName&&e.getAttribute("href")},replacement:function(e,n){var t=n.getAttribute("href"),n=s(n.getAttribute("title"));return"["+e+"]("+t+(n=n&&' "'+n+'"')+")"}},t.referenceLink={filter:function(e,n){return"referenced"===n.linkStyle&&"A"===e.nodeName&&e.getAttribute("href")},replacement:function(e,n,t){var r=n.getAttribute("href"),i=(i=s(n.getAttribute("title")))&&' "'+i+'"';switch(t.linkReferenceStyle){case"collapsed":a="["+e+"][]",l="["+e+"]: "+r+i;break;case"shortcut":a="["+e+"]",l="["+e+"]: "+r+i;break;default:var o=this.references.length+1,a="["+e+"]["+o+"]",l="["+o+"]: "+r+i}return this.references.push(l),a},references:[],append:function(e){var n="";return this.references.length&&(n="\n\n"+this.references.join("\n")+"\n\n",this.references=[]),n}},t.emphasis={filter:["em","i"],replacement:function(e,n,t){return e.trim()?t.emDelimiter+e+t.emDelimiter:""}},t.strong={filter:["strong","b"],replacement:function(e,n,t){return e.trim()?t.strongDelimiter+e+t.strongDelimiter:""}},t.code={filter:function(e){var n=e.previousSibling||e.nextSibling,n="PRE"===e.parentNode.nodeName&&!n;return"CODE"===e.nodeName&&!n},replacement:function(e){if(!e)return"";e=e.replace(/\r?\n|\r/g," ");for(var n=/^`|^ .*?[^ ].* $|`$/.test(e)?" ":"",t="`",r=e.match(/`+/gm)||[];-1!==r.indexOf(t);)t+="`";return t+n+e+n+t}},t.image={filter:"img",replacement:function(e,n){var t=s(n.getAttribute("alt")),r=n.getAttribute("src")||"",n=s(n.getAttribute("title"));return r?"!["+t+"]("+r+(n?' "'+n+'"':"")+")":""}},f.prototype={add:function(e,n){this.array.unshift(n)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){return e.isBlank?this.blankRule:(n=d(this.array,e,this.options))||(n=d(this._keep,e,this.options))||(n=d(this._remove,e,this.options))?n:this.defaultRule;var n},forEach:function(e){for(var n=0;n'+e+"","text/html").getElementById("turndown-root"):e.cloneNode(!0),isBlock:o,isVoid:i,isPre:n.preformattedCode?y:null}),e}function y(e){return"PRE"===e.nodeName||"CODE"===e.nodeName}function N(e,n){var t;return e.isBlock=o(e),e.isCode="CODE"===e.nodeName||e.parentNode.isCode,e.isBlank=!i(t=e)&&!function(e){return l(e,a)}(t)&&/^\s*$/i.test(t.textContent)&&!function(e){return c(e,r)}(t)&&!function(e){return c(e,a)}(t),e.flankingWhitespace=function(e,n){if(e.isBlock||n.preformattedCode&&e.isCode)return{leading:"",trailing:""};var t=function(e){e=e.match(/^(([ \t\r\n]*)(\s*))[\s\S]*?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}(e.textContent);t.leadingAscii&&E("left",e,n)&&(t.leading=t.leadingNonAscii);t.trailingAscii&&E("right",e,n)&&(t.trailing=t.trailingNonAscii);return{leading:t.leading,trailing:t.trailing}}(e,n),e}function E(e,n,t){var r,i,n="left"===e?(r=n.previousSibling,/ $/):(r=n.nextSibling,/^ /);return r&&(3===r.nodeType?i=n.test(r.nodeValue):t.preformattedCode&&"CODE"===r.nodeName?i=!1:1!==r.nodeType||o(r)||(i=n.test(r.textContent))),i}var T=Array.prototype.reduce,R=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function C(e){if(!(this instanceof C))return new C(e);this.options=function(e){for(var n=1;n