diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5114dd5..579bafd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,21 +9,30 @@ By submitting a pull request, issue attachment or prompt, you confirm that you w ## Ways to contribute - **Bug reports and ideas:** use the issue forms. -- **Community prompts:** use the "Prompt submission" form, or open a pull request that adds an entry to `better-perplexity/prompts/library.json`. +- **Community prompts:** use the "Prompt submission" form, or open a pull request that adds an entry to `ai/perplexity/prompts/library.json`. - **Code:** open an issue first for anything larger than a small fix. +## Repository layout + +| Folder | Package | Purpose | +| --------------- | ---------------------- | ---------------------------------------------------- | +| `core/` | `@nolly/core` | Runtime, storage, DOM, HTTP, build tooling | +| `core/ai` | `@nolly/ai` | Platform-agnostic code shared by AI-chat userscripts | +| `ai/perplexity` | `@nolly/ai-perplexity` | Better Perplexity | +| `ai/chatgpt` | `@nolly/ai-chatgpt` | Better ChatGPT | + ## Development setup ```bash bun install # at the repository root (Bun workspace) -cd better-perplexity +cd ai/perplexity # or ai/chatgpt bun run dev # unminified, rebuilds on change bun run typecheck bun run validate:prompts bun run build # minified output in dist/ ``` -Install `dist/better-perplexity.user.js` in your userscript manager to test. Shared code lives in `core/` and is published as the workspace package `@nolly/core`; script-specific code stays in the script's own folder. Start a new script with `bun scripts/new-userscript.ts ""`. +Install the file in `dist/` in your userscript manager to test. Code that does not depend on one site belongs in `core/ai`; site-specific selectors and modules stay in the script's folder. Start a new script with `bun scripts/new-userscript.ts "" [parent-folder]`, for example `bun scripts/new-userscript.ts better-claude "Better Claude" ai`. ## Code style @@ -33,7 +42,7 @@ Install `dist/better-perplexity.user.js` in your userscript manager to test. Sha ## Releasing -1. Bump `version` in the script's `package.json`. +1. Bump `version` in the script's `package.json`. Each script also declares its `userscript.slug` there, which names its tag and its folder on the `dist` branch. 2. Add a section to its `CHANGELOG.md` in the form `## [x.y.z] - YYYY-MM-DD`. 3. Merge to `master`. The release workflow does the rest. diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md new file mode 100644 index 0000000..94cb540 --- /dev/null +++ b/ai/chatgpt/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## [1.0.0] - 2026-11-10 + +- Exporter built from the conversation view (Markdown, text, Word, PDF, JSON) and update checker. +- Batch Runner, Selection Toolbar (Ask, Explain, Summarize, Fact-check, Quote) and Max Width. +- Initial skeleton: composer and header detection, response observer, session state and diagnostics. +- Starts only after the page has loaded and the composer has rendered, so it doesn't interfere with ChatGPT's own startup. +- Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. +- Draft Guard: autosaved drafts, size meter and unsent-text warning. +- Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). +- Code Block Pro: language badges, highlighting, line numbers, wrap, fold, copy and download. +- Prompt Library (shared community prompts), Command Palette, Message Queue and Recall. +- Usage Status: remaining reasoning, upload, image and research limits with reset times, plan and rolling window, and alerts. diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md new file mode 100644 index 0000000..def4524 --- /dev/null +++ b/ai/chatgpt/README.md @@ -0,0 +1,71 @@ +# Better ChatGPT + +A modular userscript that adds the missing parts of ChatGPT: limits at a glance, better code blocks, long-message handling, a prompt library, batch runs and real exports. + +[Changelog](CHANGELOG.md) · [Report a bug](https://github.com/thenolle/userscripts/issues/new?template=bug_report.yml) + +## Install + +1. Install [Violentmonkey](https://violentmonkey.github.io/) or [Tampermonkey](https://www.tampermonkey.net/). +2. Open the **Install** link on the project website and confirm. +3. Open chatgpt.com. The settings button sits in the header next to ChatGPT's own buttons. + +Updates arrive automatically. The script also checks on its own and offers to update. + +## Features + +| Feature | What you get | +| ----------------- | ---------------------------------------------------------------------------------------------------- | +| Usage Status | Remaining reasoning, upload, image and research limits with reset times, your plan, low/empty alerts | +| Code Block Pro | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe copy | +| Message Splitter | Paste any amount of text; split into parts or attach as a file only when needed | +| Prompt Library | Your prompts plus community prompts, with a form for placeholders | +| Batch Runner | Run one template over a list, with pause, resume and reload recovery | +| Selection Toolbar | Ask, explain, summarize, fact-check or quote highlighted text | +| Exporter | Markdown, text, Word, PDF and JSON | +| Draft Guard | Drafts survive reloads; size meter; warning before closing with unsent text | +| Command Palette | Search every action | +| Enter as Newline | Enter adds a line, a shortcut sends | +| Message Queue | Queue follow-ups while an answer generates; they send one by one | +| Recall | Search everything you sent and reuse it | +| Max Width | Full-width conversations, optional sidebar removal | +| Update Checker | Checks on load and every few minutes, tells you once per version | + +## Shortcuts + +| Action | Default | +| --------------- | --------------------------- | +| Command palette | Alt + Shift + P | +| Prompt library | Alt + Shift + L | +| Recall | Alt + Shift + H | +| Send message | Ctrl + Enter or Cmd + Enter | + +All of them can be changed from the settings dialog. + +## Privacy + +No analytics and no server of its own. The script reads ChatGPT's own responses in your session (for limits and the model in use) and talks to `raw.githubusercontent.com` for update checks and community prompts. Drafts, prompts and settings stay in your userscript manager's storage. + +## Troubleshooting + +- **A button is missing:** open the settings dialog and check the module is on. In the browser console, `betterChatgptDump()` prints what the script found on the page; attach it to a bug report. +- **Export says no messages found:** ChatGPT changed its layout. Run `betterChatgptDump()` and attach it. +- **Limits look empty:** they come from ChatGPT's own responses and appear after the page loads or a message is sent. + +## Built on the shared packages + +Better ChatGPT is built on [`@nolly/core`](../../core/README.md) and [`@nolly/ai`](../../core/ai/README.md). Both are bundled into `better-chatgpt.user.js` at build time. Only what is specific to ChatGPT lives here: selectors, the network observer, limits, the exporter source and the header placement. + +## Development + +```bash +bun install # at the repository root +cd ai/chatgpt +bun run dev # unminified, rebuilds on change +bun run typecheck +bun run build # minified userscript in dist/ +``` + +## License + +[PolyForm Strict License 1.0.0](../../LICENSE). diff --git a/ai/chatgpt/docs/architecture.md b/ai/chatgpt/docs/architecture.md new file mode 100644 index 0000000..ec118a2 --- /dev/null +++ b/ai/chatgpt/docs/architecture.md @@ -0,0 +1,22 @@ +--- +title: Architecture +description: How Better ChatGPT is built on the shared packages. +section: Reference +order: 900 +--- + +# Architecture + +Better ChatGPT is a thin layer on top of two shared packages, both bundled into the final `.user.js`. + +- **`@nolly/core`** is the runtime: features, storage, logging, DOM helpers and the build. +- **`@nolly/ai`** holds everything that is not specific to one site: the composer, prompt and generation handling, the UI kit and the features themselves. A site fills in a small registry once at startup. + +What stays in this folder: + +- selectors and the page locators (message box, header, messages); +- the network observer that reads limits, the model in use and when an answer starts and ends; +- the exporter source, which converts the conversation view to Markdown; +- the usage feature and the header placement. + +The script starts only after the page has loaded and the message box has rendered, so it never touches the page while ChatGPT is still starting up. diff --git a/ai/chatgpt/docs/exporting.md b/ai/chatgpt/docs/exporting.md new file mode 100644 index 0000000..18235ee --- /dev/null +++ b/ai/chatgpt/docs/exporting.md @@ -0,0 +1,17 @@ +--- +title: Exporting a conversation +description: Markdown, text, Word, PDF and JSON. +section: Guides +order: 30 +--- + +# Exporting a conversation + +Open a conversation and click the download icon in the header. Pick a format: + +- **Markdown** keeps headings, lists, tables and code blocks with their language. +- **Plain text** strips the formatting. +- **Word** and **PDF** are generated in your browser from the Markdown. +- **JSON** lists each message with its role and Markdown. + +The export is built from what is on the page, so scroll to load a very long conversation first. diff --git a/ai/chatgpt/docs/getting-started.md b/ai/chatgpt/docs/getting-started.md new file mode 100644 index 0000000..09941c6 --- /dev/null +++ b/ai/chatgpt/docs/getting-started.md @@ -0,0 +1,17 @@ +--- +title: Getting started +description: Install Better ChatGPT and find your way around. +section: Guides +order: 10 +--- + +# Getting started + +Install a userscript manager, then the script, and open chatgpt.com. After the page has loaded you will see: + +- **Settings** (sliders icon) in the header: turn modules on or off and open each module's own settings. +- **Usage** pill: your remaining reasoning messages. Hover for every limit, click for details. +- **Download** icon inside a conversation: exports it. +- Extra buttons next to the message box for big messages, prompts, batches, queue and recall. + +Press Alt + Shift + P at any time to search every action. diff --git a/ai/chatgpt/docs/troubleshooting.md b/ai/chatgpt/docs/troubleshooting.md new file mode 100644 index 0000000..13d5cf0 --- /dev/null +++ b/ai/chatgpt/docs/troubleshooting.md @@ -0,0 +1,15 @@ +--- +title: Troubleshooting +description: Fixes for missing buttons, empty limits and failed exports. +section: Reference +order: 800 +--- + +# Troubleshooting + +Open the browser console on chatgpt.com and run `betterChatgptDump()`. It prints what the script found: the composer, the header, your messages and the current limits. Attach it to any bug report. + +- **No header buttons:** the script waits for the page and the message box to finish loading. Wait a few seconds, or check the module is on in settings. +- **Export finds no messages:** ChatGPT changed how it marks messages. The dump shows `page.turns`; if both counts are 0 while messages are on screen, report it. +- **Limits are empty:** send a message or reload the page. +- **Update check failed (404):** the first release has not been published yet. diff --git a/ai/chatgpt/docs/usage-tracking.md b/ai/chatgpt/docs/usage-tracking.md new file mode 100644 index 0000000..7b5e036 --- /dev/null +++ b/ai/chatgpt/docs/usage-tracking.md @@ -0,0 +1,14 @@ +--- +title: Usage tracking +description: Where the numbers come from and when they refresh. +section: Guides +order: 20 +--- + +# Usage tracking + +ChatGPT reports your remaining limits itself. Better ChatGPT reads those responses in your session: file uploads, pasted text turned into files, image generation, deep research and reasoning messages, each with its reset time. It also shows your plan and the rolling window. + +The numbers refresh when ChatGPT refreshes them: when you load a page and after each message. There are no totals or refill estimates, because ChatGPT only reports what is left. + +Alerts appear when a limit runs out, runs low, or becomes available again. Choose which limit the header pill shows from the settings dialog. diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index d55ee97..8c7de1f 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -1,9 +1,10 @@ { "name": "@nolly/ai-chatgpt", - "version": "0.1.0", + "version": "1.0.0", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", + "userscript": { "slug": "better-chatgpt" }, "repository": { "type": "git", "url": "git+https://github.com/thenolle/userscripts.git", diff --git a/ai/chatgpt/src/adapter.ts b/ai/chatgpt/src/adapter.ts index c92b70c..bfc462f 100644 --- a/ai/chatgpt/src/adapter.ts +++ b/ai/chatgpt/src/adapter.ts @@ -1,6 +1,7 @@ import type { ConversationRef, PlatformAdapter } from '@nolly/ai' import { isOwnUi } from './dom' import { findAttachButton, findComposerForm, findHeaderSlot, findModeToggles, findPrimaryAction, findSendButton, findSidebar, findStopButton, labelOf, locateEditable, rejectEditable } from './locate' +import { countTurns } from './messages' const CHAT_PATH = /^\/(?:g\/g-p-[0-9a-f]+[^/]*\/)?c\/([^/?#]+)/ const PROJECT_PATH = /^\/g\/(g-p-[0-9a-f]+)/ @@ -43,6 +44,7 @@ export const chatgptAdapter: PlatformAdapter = { attach: brief(findAttachButton()), modeToggles: findModeToggles().map(({ element }) => brief(element)), headerSlot: findHeaderSlot() !== null, - sidebar: findSidebar() !== null + sidebar: findSidebar() !== null, + turns: countTurns(), }) } diff --git a/ai/chatgpt/src/app.ts b/ai/chatgpt/src/app.ts index 7be1f40..25f6188 100644 --- a/ai/chatgpt/src/app.ts +++ b/ai/chatgpt/src/app.ts @@ -1,8 +1,8 @@ -import { Userscript, createLogger } from '@nolly/core' +import { toggleSettingsDialog } from '@nolly/ai' +import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from './config' import { uiMarker } from './dom' - -const logger = createLogger('better-chatgpt') +import { findComposerForm } from './locate' export class App extends Userscript { constructor() { @@ -16,8 +16,8 @@ export class App extends Userscript { initializationDelay: CONFIG.initializationDelay, safetyInterval: CONFIG.safetyInterval, clearConsole: false, - isReady: () => Boolean(document.querySelector('main')), - openSettings: () => logger.info('The settings dialog arrives in step 2.') + isReady: () => document.readyState === 'complete' && findComposerForm() !== null, + openSettings: (script) => toggleSettingsDialog(script) }) } } diff --git a/ai/chatgpt/src/budget.ts b/ai/chatgpt/src/budget.ts new file mode 100644 index 0000000..f137297 --- /dev/null +++ b/ai/chatgpt/src/budget.ts @@ -0,0 +1,25 @@ +import type { ChatSession } from './session' + +export const FILES_PER_MESSAGE = 20 + +export interface FileBudget { + readonly perMessage: number + readonly remainingUploads: number | null + readonly uploadResetsAt: string | null + readonly remainingPasteToFile: number | null + readonly pasteResetsAt: string | null + readonly maxFileMb: number | null +} + +export const fileBudget = (session: ChatSession): FileBudget => { + const upload = session.limit('file_upload') + const paste = session.limit('paste_text_to_file') + return { + perMessage: FILES_PER_MESSAGE, + remainingUploads: upload?.remaining ?? null, + uploadResetsAt: upload?.resetAfter ?? null, + remainingPasteToFile: paste?.remaining ?? null, + pasteResetsAt: paste?.resetAfter ?? null, + maxFileMb: session.maxFileMb + } +} diff --git a/ai/chatgpt/src/config.ts b/ai/chatgpt/src/config.ts index 57bd58a..eb54e00 100644 --- a/ai/chatgpt/src/config.ts +++ b/ai/chatgpt/src/config.ts @@ -1,8 +1,12 @@ +import type { SplitterSettings } from '@nolly/ai' + export const CONFIG = { - initializationDelay: 500, + initializationDelay: 1_500, safetyInterval: 2_000 } as const +export const SPLITTER_DEFAULTS: Partial = { limit: 30_000 } + export const OBSERVER_OPTIONS: MutationObserverInit = { childList: true, subtree: true, diff --git a/ai/chatgpt/src/dom-markdown.ts b/ai/chatgpt/src/dom-markdown.ts new file mode 100644 index 0000000..bbb0a45 --- /dev/null +++ b/ai/chatgpt/src/dom-markdown.ts @@ -0,0 +1,133 @@ +import { isOwnUi } from './dom' + +const HEADING = /^H([1-6])$/ +const SKIPPED = 'script, style, svg, [data-markdown-copy="exclude"], [data-conversation-role], .katex-html' +const BLOCKS = new Set(['P', 'DIV', 'UL', 'OL', 'PRE', 'TABLE', 'BLOCKQUOTE', 'HR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'SECTION', 'ARTICLE']) + +const skipped = (element: HTMLElement): boolean => isOwnUi(element) || element.matches(SKIPPED) || (element.tagName === 'BUTTON' && !element.querySelector('img')) + +const tex = (element: HTMLElement): string => element.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim() ?? element.textContent ?? '' + +const wrap = (mark: string, value: string): string => (value.trim() ? `${mark}${value.trim()}${mark}` : value) + +const inline = (node: Node): string => { + if (node.nodeType === Node.TEXT_NODE) return (node.textContent ?? '').replace(/\s+/g, ' ') + if (!(node instanceof HTMLElement) || skipped(node)) return '' + if (node.classList.contains('katex-display')) return `\n\n$$${tex(node)}$$\n\n` + if (node.classList.contains('katex')) return `$${tex(node)}$` + if (node.hasAttribute('data-pill')) { + const href = node.querySelector('a[href]')?.getAttribute('href') + const label = (node.textContent ?? '').trim() + return href && label ? ` [${label}](${href})` : '' + } + const inner = (): string => [...node.childNodes].map(inline).join('') + if (node.hasAttribute('data-d-default-strong')) return wrap('**', inner()) + switch (node.tagName) { + case 'BR': + return ' \n' + case 'STRONG': + case 'B': + return wrap('**', inner()) + case 'EM': + case 'I': + return wrap('*', inner()) + case 'DEL': + case 'S': + return wrap('~~', inner()) + case 'CODE': + return `\`${node.textContent ?? ''}\`` + case 'A': { + const href = node.getAttribute('href') + const label = inner().trim() + return href && label ? `[${label}](${href})` : label + } + case 'IMG': { + const source = node.getAttribute('src') + return source ? `![${node.getAttribute('alt') ?? ''}](${source})` : '' + } + default: + return inner() + } +} + +const fence = (pre: HTMLElement): string => { + const raw = pre.closest('[data-chatgpt-copy-code]')?.getAttribute('data-chatgpt-copy-code') ?? (pre.querySelector('code') ?? pre).textContent ?? '' + const label = pre.closest('[data-code-block]')?.querySelector('[data-markdown-copy="exclude"] .truncate')?.textContent ?? '' + const language = label.trim().toLowerCase().replace(/\s+/g, '-') + return `\`\`\`${language}\n${raw.replace(/\n$/, '')}\n\`\`\`` +} + +const table = (element: HTMLElement): string => { + const rows = [...element.querySelectorAll('tr')].map((row) => [...row.children].map((cell) => inline(cell).replace(/\|/g, '\\|').replace(/\s+/g, ' ').trim())) + if (!rows.length) return '' + const width = Math.max(...rows.map((row) => row.length)) + const line = (row: string[]): string => `| ${Array.from({ length: width }, (_, index) => row[index] ?? '').join(' | ')} |` + const [head, ...body] = rows + return [line(head ?? []), `| ${Array.from({ length: width }, () => '---').join(' | ')} |`, ...body.map(line)].join('\n') +} + +const flat = (node: Node): Node[] => (node instanceof HTMLElement && node.tagName === 'DIV' && !skipped(node) ? [...node.childNodes].flatMap(flat) : [node]) + +const list = (element: HTMLElement, depth: number): string => { + const ordered = element.tagName === 'OL' + let index = Number.parseInt(element.getAttribute('start') ?? '1', 10) || 1 + const indent = ' '.repeat(depth) + const lines: string[] = [] + for (const item of element.children) { + if (!(item instanceof HTMLElement) || item.tagName !== 'LI' || skipped(item)) continue + const own: string[] = [] + const nested: string[] = [] + for (const child of [...item.childNodes].flatMap(flat)) { + if (child instanceof HTMLElement && (child.tagName === 'UL' || child.tagName === 'OL')) nested.push(list(child, depth + 1)) + else if (child instanceof HTMLElement && child.tagName === 'PRE') nested.push(fence(child).split('\n').map((line) => `${indent} ${line}`).join('\n')) + else own.push(child instanceof HTMLElement && child.tagName === 'P' ? `${inline(child)} ` : inline(child)) + } + lines.push(`${indent}${ordered ? `${index++}.` : '-'} ${own.join('').trim()}`, ...nested.filter(Boolean)) + } + return lines.join('\n') +} + +const block = (element: HTMLElement): string => { + if (skipped(element)) return '' + const heading = HEADING.exec(element.tagName) + if (heading) return `${'#'.repeat(Number(heading[1]))} ${[...element.childNodes].map(inline).join('').trim()}` + switch (element.tagName) { + case 'P': + return [...element.childNodes].map(inline).join('').trim() + case 'UL': + case 'OL': + return list(element, 0) + case 'PRE': + return fence(element) + case 'HR': + return '---' + case 'TABLE': + return table(element) + case 'BLOCKQUOTE': + return children(element).split('\n').map((line) => `> ${line}`).join('\n') + default: + return children(element) + } +} + +const children = (element: HTMLElement): string => { + const parts: string[] = [] + let run = '' + const flush = (): void => { + if (run.trim()) parts.push(run.trim()) + run = '' + } + for (const child of element.childNodes) { + if (child instanceof HTMLElement && BLOCKS.has(child.tagName)) { + flush() + const value = block(child) + if (value) parts.push(value) + } else { + run += inline(child) + } + } + flush() + return parts.join('\n\n') +} + +export const toMarkdown = (root: HTMLElement): string => children(root).replace(/\n{3,}/g, '\n\n').trim() diff --git a/ai/chatgpt/src/dom.ts b/ai/chatgpt/src/dom.ts index ab00dee..c80ed52 100644 --- a/ai/chatgpt/src/dom.ts +++ b/ai/chatgpt/src/dom.ts @@ -1,6 +1,5 @@ import { createUiMarker } from '@nolly/core' export const uiMarker = createUiMarker('data-bc-root') -export const UI_ROOT_ATTRIBUTE = uiMarker.attribute export const markUi = uiMarker.mark export const isOwnUi = uiMarker.isOwn diff --git a/ai/chatgpt/src/export-source.ts b/ai/chatgpt/src/export-source.ts new file mode 100644 index 0000000..1891065 --- /dev/null +++ b/ai/chatgpt/src/export-source.ts @@ -0,0 +1,40 @@ +import type { ExportSource } from '@nolly/ai' +import { parseConversation } from './adapter' +import { toMarkdown } from './dom-markdown' +import { placeTool } from './header-tools' +import { findTurns } from './messages' +import type { Turn } from './messages' +import { ICON_BUTTON_CLASS } from './header-style' + +const ROLE_LABEL = { user: 'You', assistant: 'ChatGPT' } as const + +const turns = (): Turn[] => { + const found = findTurns() + if (!found.length) throw new Error('No messages found on this page.') + return found +} + +const render = (turn: Turn): string => (turn.role === 'user' ? turn.text() : toMarkdown(turn.element)) + +export const exportSource: ExportSource = { + name: 'ChatGPT', + citations: false, + slug: () => parseConversation(new URL(location.href)).id, + markdown: async () => turns().map((turn) => `**${ROLE_LABEL[turn.role]}**\n\n${render(turn)}`).join('\n\n---\n\n'), + json: async () => JSON.stringify( + { + app: 'better-chatgpt', + conversationId: parseConversation(new URL(location.href)).id, + title: document.title, + url: location.href, + exportedAt: new Date().toISOString(), + messages: turns().map((turn) => ({ role: turn.role, markdown: render(turn) })) + }, + null, + 2 + ), + place: (button) => { + if (button.className !== ICON_BUTTON_CLASS) button.className = ICON_BUTTON_CLASS + return placeTool(button, 'export') + } +} diff --git a/ai/chatgpt/src/features/diagnostics.ts b/ai/chatgpt/src/features/diagnostics.ts index cf01918..e8d5d21 100644 --- a/ai/chatgpt/src/features/diagnostics.ts +++ b/ai/chatgpt/src/features/diagnostics.ts @@ -1,30 +1,64 @@ import { Feature, getPageWindow } from '@nolly/core' -import type { FeatureCommand, ScriptContext } from '@nolly/core' +import type { FeatureCommand } from '@nolly/core' import { chatgptAdapter } from '../adapter' -import type { ChatSession } from '../session' +import { fileBudget } from '../budget' +import { exportSource } from '../export-source' +import { toolRow } from '../header-tools' +import { sendPrompt } from '../kit' +import { findHeaderSlot } from '../locate' +import { session } from '../runtime' -export class DiagnosticsFeature extends Feature { - readonly id = 'diagnostics' - readonly name = 'Diagnostics' - readonly description = 'Reports the detected ChatGPT layout and live session state in the console.' +const box = (element: Element): { x: number; y: number; w: number; h: number } => { + const { x, y, width, height } = element.getBoundingClientRect() + return { x: Math.round(x), y: Math.round(y), w: Math.round(width), h: Math.round(height) } +} - constructor(context: ScriptContext, private readonly session: ChatSession) { - super(context) - } +const brief = (element: Element): Record => ({ + tag: element.tagName.toLowerCase(), + tool: element.getAttribute('data-bc-tool') ?? undefined, + label: element.getAttribute('aria-label') ?? (element.textContent ?? '').trim().slice(0, 24), + id: element.id || undefined, + ...box(element) +}) + +export class DiagnosticsFeature extends Feature { + readonly id = 'diagnostics' + readonly name = 'Diagnostics' + readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' - run(): void { } + run(): void {} - override onEnable(): void { - const page = getPageWindow() as unknown as Record | null - if (page) page['betterChatgptDump'] = () => this.dump() - this.context.logger.info('Diagnostics ready. Run betterChatgptDump() in the console.') - } + override onEnable(): void { + const page = getPageWindow() as unknown as Record | null + if (page) { + page['betterChatgptDump'] = () => this.dump() + page['betterChatgptSend'] = (text: string) => sendPrompt(text) + } + this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') + } - override commands(): FeatureCommand[] { - return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => void this.context.logger.info(this.dump()) }] - } + override commands(): FeatureCommand[] { + return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] + } - private dump(): string { - return JSON.stringify({ page: chatgptAdapter.describePage(), session: this.session.snapshot() }, null, 2) - } + private dump(): string { + const slot = findHeaderSlot() + const row = toolRow() + return JSON.stringify( + { + page: chatgptAdapter.describePage(), + header: { + slot: slot ? box(slot) : null, + groups: slot ? [...slot.children].map(brief) : [], + row: row ? [...row.children].map(brief) : [], + tools: [...document.querySelectorAll('[data-bc-tool]')].map((tool) => ({ ...brief(tool), connected: tool.isConnected, display: getComputedStyle(tool).display })), + exportSlug: exportSource.slug() + }, + session: session.snapshot(), + fileBudget: fileBudget(session) + }, + null, + 2 + ) + } } diff --git a/ai/chatgpt/src/features/header-button.ts b/ai/chatgpt/src/features/header-button.ts new file mode 100644 index 0000000..06b7f3e --- /dev/null +++ b/ai/chatgpt/src/features/header-button.ts @@ -0,0 +1,37 @@ +import { Tooltip, createIcon, ensureUiStyles } from '@nolly/ai' +import { Feature, createElement } from '@nolly/core' +import { ICON_BUTTON_CLASS } from '../header-style' +import { placeTool } from '../header-tools' + +export class HeaderButtonFeature extends Feature { + readonly id = 'header-button' + readonly name = 'Header button' + readonly description = 'Adds the Better ChatGPT settings button to the header.' + + private button: HTMLButtonElement | null = null + private tooltip: Tooltip | null = null + + run(): void { + if (!this.enabled) return + if (!this.button) this.build() + if (this.button) placeTool(this.button, 'settings') + } + + override onDisable(): void { + this.tooltip?.destroy() + this.tooltip = null + this.button?.remove() + this.button = null + } + + private build(): void { + ensureUiStyles() + const button = createElement('button', ICON_BUTTON_CLASS) + button.type = 'button' + button.setAttribute('aria-label', 'Better ChatGPT settings') + button.appendChild(createIcon('sliders', 20)) + button.addEventListener('click', () => this.context.openSettings()) + this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) + this.button = button + } +} diff --git a/ai/chatgpt/src/features/usage.ts b/ai/chatgpt/src/features/usage.ts new file mode 100644 index 0000000..81fae8d --- /dev/null +++ b/ai/chatgpt/src/features/usage.ts @@ -0,0 +1,166 @@ +import { Tooltip, createButton, createDataRow, createDialog, createSection, ensureUiStyles, markUi, showToast, uiConfig } from '@nolly/ai' +import { Feature, createElement, injectStyle } from '@nolly/core' +import type { MenuEntry, ScriptContext } from '@nolly/core' +import { placeTool } from '../header-tools' +import { session } from '../runtime' +import { storage } from '../storage' +import { PILL_BUTTON_CLASS } from '../header-style' + +const PRIMARY_KEY = 'usage-status:primary' +const LAST_KEY = 'usage-status:last' +const LOW = 2 + +const LABELS: Readonly> = { + reason: 'Reasoning', + file_upload: 'File uploads', + paste_text_to_file: 'Pasted text as file', + image_gen: 'Image generation', + deep_research: 'Deep research' +} + +const CSS = ` +.bp-usage-pill[data-level='low'] { color: var(--bp-yellow); } +.bp-usage-pill[data-level='empty'] { color: var(--bp-red); } +` + +const labelOf = (feature: string): string => LABELS[feature] ?? feature.replace(/_/g, ' ').replace(/^\w/, (letter) => letter.toUpperCase()) + +const formatReset = (iso: string | null): string => { + const ms = iso ? Date.parse(iso) - Date.now() : Number.NaN + if (!Number.isFinite(ms)) return 'no reset time' + if (ms <= 0) return 'resetting now' + const minutes = Math.round(ms / 60_000) + if (minutes < 60) return `resets in ${minutes}m` + const hours = Math.floor(minutes / 60) + if (hours < 24) return `resets in ${hours}h ${minutes % 60}m` + return `resets ${new Date(iso as string).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}` +} + +const level = (remaining: number): 'ok' | 'low' | 'empty' => (remaining === 0 ? 'empty' : remaining <= LOW ? 'low' : 'ok') + +const titleCase = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1) + +export class UsageFeature extends Feature { + readonly id = 'usage-status' + readonly name = 'Usage Status' + readonly description = 'Shows your remaining limits (reasoning, uploads, images, research) and your plan.' + + private readonly pill = markUi(createElement('button', `${PILL_BUTTON_CLASS} bp-usage-pill bp-themed`)) + private readonly label = createElement('span') + private readonly tooltip: Tooltip + + constructor(context: ScriptContext) { + super(context) + ensureUiStyles() + injectStyle(`${uiConfig().id}-usage-styles`, CSS) + this.pill.type = 'button' + this.pill.setAttribute('aria-label', 'Usage status') + this.pill.appendChild(this.label) + this.pill.addEventListener('click', () => this.open()) + this.tooltip = new Tooltip(this.pill, (container) => container.append(this.rows()), { align: 'end' }) + } + + private get primary(): string { + return storage.get(PRIMARY_KEY, 'reason') + } + + override onEnable(): void { + this.scope.add( + session.subscribe((event) => { + if (event !== 'limits' && event !== 'usage' && event !== 'plan') return + if (event === 'limits') this.checkAlerts() + this.update() + this.context.refreshMenu() + }) + ) + } + + run(): void { + if (!this.enabled || !placeTool(this.pill, 'usage')) { + this.tooltip.hide() + this.pill.remove() + return + } + this.update() + } + + override menuEntries(): MenuEntry[] { + return [ + { id: 'details', label: 'Show Usage Details', action: () => this.open() }, + { id: 'metric', label: `Badge Shows: ${labelOf(this.primary)} (click to change)`, action: () => this.cycle() } + ] + } + + private update(): void { + const entry = session.limit(this.primary) + this.label.textContent = entry ? `${labelOf(entry.feature)} ${entry.remaining}` : session.plan ? `${titleCase(session.plan)} plan` : 'Usage' + this.pill.dataset['level'] = entry ? level(entry.remaining) : 'ok' + this.tooltip.refresh() + } + + private cycle(): void { + const features = session.limits.map((limit) => limit.feature) + if (!features.length) return + storage.set(PRIMARY_KEY, features[(features.indexOf(this.primary) + 1) % features.length] ?? 'reason') + this.context.refreshMenu() + this.update() + } + + private rows(): HTMLElement { + const list = createElement('div', 'bp-data-list') + const limits = session.limits + if (!limits.length) { + list.appendChild(createElement('div', 'bp-empty', 'No limit data yet. Send a message or reload the page.')) + return list + } + for (const limit of limits) list.appendChild(createDataRow(labelOf(limit.feature), `${limit.remaining} left · ${formatReset(limit.resetAfter)}`, limit.remaining === 0 ? 'negative' : '')) + return list + } + + private open(): void { + const dialogId = `${uiConfig().id}-usage-dialog` + const existing = document.getElementById(dialogId) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + const ui = createDialog({ id: dialogId, title: 'Usage', description: session.plan ? `${titleCase(session.plan)} plan` : 'Plan not detected yet', width: 480 }) + const limits = createSection('Limits') + limits.appendChild(this.rows()) + const body = [limits] + const { usage } = session + if (usage?.usedPercent !== null && usage?.usedPercent !== undefined) { + const window = createSection('Rolling window') + const bar = createElement('div', 'bp-progress') + const fill = createElement('div', `bp-progress-fill ${usage.limitReached ? 'empty' : ''}`.trim()) + fill.style.width = `${Math.min(100, usage.usedPercent)}%` + bar.appendChild(fill) + const reset = usage.resetAt ? new Date(usage.resetAt * 1000).toLocaleString() : 'unknown' + window.append(bar, createDataRow('Used', `${usage.usedPercent}%`), createDataRow('Resets', reset)) + body.push(window) + } + if (session.maxFileMb !== null) { + const files = createSection('Files') + files.appendChild(createDataRow('Largest file', `${session.maxFileMb} MB`)) + body.push(files) + } + ui.body.replaceChildren(...body) + ui.footer.append(createButton('Close', { primary: true, onClick: ui.close })) + ui.show() + } + + private checkAlerts(): void { + const last = storage.get>(LAST_KEY, {}) + const next = { ...last } + for (const { feature, remaining, resetAfter } of session.limits) { + const before = last[feature] + next[feature] = remaining + if (before === undefined) continue + const name = labelOf(feature) + if (before > 0 && remaining === 0) showToast(`${name}: none left, ${formatReset(resetAfter)}.`, [], 10_000) + else if (before === 0 && remaining > 0) showToast(`${name} is available again (${remaining} left).`, [], 8_000) + else if (before > LOW && remaining > 0 && remaining <= LOW) showToast(`${name}: only ${remaining} left, ${formatReset(resetAfter)}.`, [], 8_000) + } + storage.set(LAST_KEY, next) + } +} diff --git a/ai/chatgpt/src/header-style.ts b/ai/chatgpt/src/header-style.ts new file mode 100644 index 0000000..d624301 --- /dev/null +++ b/ai/chatgpt/src/header-style.ts @@ -0,0 +1,5 @@ +const BASE = 'no-drag cursor-interaction items-center select-none disabled:cursor-default aria-disabled:cursor-default focus:outline-hidden disabled:opacity-40 aria-disabled:opacity-40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-0 whitespace-nowrap flex border gap-1 rounded-lg text-default not-disabled:not-aria-disabled:hover:bg-secondary-ghost-hover data-[state=open]:bg-secondary-ghost-hover aria-pressed:bg-secondary-ghost-hover border-transparent button-toolbar py-0 text-sm leading-[18px]' + +export const ICON_BUTTON_CLASS = `${BASE} aspect-square shrink-0 items-center justify-center !px-0 bc-header-btn` +export const PILL_BUTTON_CLASS = `${BASE} shrink-0 items-center px-3 font-medium` +export const TOOLS_CLASS = 'pointer-events-auto flex items-center gap-toolbar-action no-drag shrink-0' diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts new file mode 100644 index 0000000..94f52ef --- /dev/null +++ b/ai/chatgpt/src/header-tools.ts @@ -0,0 +1,23 @@ +import { findHeaderSlot } from './locate' + +const ORDER = ['settings', 'usage', 'export'] as const + +export type ToolId = (typeof ORDER)[number] + +export const toolRow = (): HTMLElement | null => { + const slot = findHeaderSlot() + return slot?.querySelector('.contents > div') ?? slot +} + +export const placeTool = (button: HTMLElement, id: ToolId): boolean => { + const row = toolRow() + if (!row) return false + button.dataset['bcTool'] = id + if (button.parentElement !== row) row.prepend(button) + const ours = ORDER.flatMap((name) => row.querySelector(`:scope > [data-bc-tool="${name}"]`) ?? []) + ours.forEach((element, index) => { + const expected = row.children[index] ?? null + if (expected !== element) row.insertBefore(element, expected) + }) + return true +} diff --git a/ai/chatgpt/src/kit.ts b/ai/chatgpt/src/kit.ts new file mode 100644 index 0000000..3bee2a5 --- /dev/null +++ b/ai/chatgpt/src/kit.ts @@ -0,0 +1,7 @@ +import { createComposerKit, createGenerationKit, createPromptSender } from '@nolly/ai' +import { chatgptAdapter } from './adapter' +import { session } from './runtime' + +export const composerKit = createComposerKit(chatgptAdapter) +export const generationKit = createGenerationKit({ adapter: chatgptAdapter, isStreaming: () => session.generating }) +export const sendPrompt = createPromptSender(composerKit) diff --git a/ai/chatgpt/src/logger.ts b/ai/chatgpt/src/logger.ts new file mode 100644 index 0000000..70d2688 --- /dev/null +++ b/ai/chatgpt/src/logger.ts @@ -0,0 +1,3 @@ +import { createLogger } from '@nolly/core' + +export const logger = createLogger('Better ChatGPT') diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index cd25cb1..db6a199 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,12 +1,103 @@ +import { + BatchRunnerFeature, + CodeBlocksFeature, + CommandPaletteFeature, + DraftGuardFeature, + EnterAsNewlineFeature, + ExporterFeature, + MaxWidthFeature, + MessageSplitterFeature, + PromptLibraryFeature, + PromptQueueFeature, + RecallFeature, + SelectionToolbarFeature, + UpdatesFeature, + configurePlatform, + configureUi, + loadSplitterSettings +} from '@nolly/ai' import { App } from './app' +import { fileBudget } from './budget' +import { SPLITTER_DEFAULTS } from './config' +import { uiMarker } from './dom' +import { exportSource } from './export-source' import { DiagnosticsFeature } from './features/diagnostics' -import { responseSpy } from './network' -import { ChatSession } from './session' +import { HeaderButtonFeature } from './features/header-button' +import { UsageFeature } from './features/usage' +import { composerKit, generationKit, sendPrompt } from './kit' +import { logger } from './logger' +import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' +import { whenReady } from './ready' +import { SLUG, URLS } from './repo' +import { session } from './runtime' +import { storage } from './storage' +import { threadOf } from './threads' +import { installTheme } from './theme' -responseSpy.install() +const onSend = (listener: () => void): (() => void) => + session.subscribe((event) => { + if (event === 'generation-start') listener() + }) -const session = new ChatSession(responseSpy) +whenReady(() => { + configureUi({ + id: 'better-chatgpt', + title: 'Better ChatGPT', + version: __VERSION__, + marker: uiMarker, + composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) + }) -new App() - .register((context) => new DiagnosticsFeature(context, session)) - .start() + configurePlatform({ + id: 'better-chatgpt', + storage, + logger, + composer: composerKit, + generation: generationKit, + sendPrompt, + onSend, + threadOf, + promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better ChatGPT', slug: SLUG, version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, + codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]') + }) + + installTheme() + + new App() + .register((context) => new HeaderButtonFeature(context)) + .register((context) => new PromptLibraryFeature(context)) + .register((context) => new SelectionToolbarFeature(context)) + .register((context) => new MaxWidthFeature(context, { storage, sidebar: { rule: { id: 'left-sidebar', selector: 'aside' }, label: 'Left Sidebar', defaultRemoved: false } })) + .register((context) => new CodeBlocksFeature(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) + .register( + (context) => + new MessageSplitterFeature(context, { + storage, + composer: composerKit, + generation: generationKit, + defaults: SPLITTER_DEFAULTS, + attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) + }) + ) + .register((context) => new BatchRunnerFeature(context)) + .register( + (context) => + new DraftGuardFeature(context, { + storage, + composer: composerKit, + onSend, + tokenLimit: () => loadSplitterSettings(storage, SPLITTER_DEFAULTS).limit + }) + ) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) + .register((context) => new ExporterFeature(context)) + .register((context) => new UpdatesFeature(context)) + .register((context) => new UsageFeature(context)) + .register((context) => new DiagnosticsFeature(context)) + .start() +}) diff --git a/ai/chatgpt/src/messages.ts b/ai/chatgpt/src/messages.ts new file mode 100644 index 0000000..64b4d8e --- /dev/null +++ b/ai/chatgpt/src/messages.ts @@ -0,0 +1,46 @@ +import { isOwnUi } from './dom' + +export type Role = 'user' | 'assistant' + +export interface Turn { + readonly role: Role + readonly element: HTMLElement + readonly id: string | null + readonly text: () => string +} + +const UNIT = '[data-chatgpt-search-unit-key]' +const UNIT_ROLE = /:(user|assistant)$/ +const USER_CONTENT = '[data-user-message-bubble]' +const ASSISTANT_CONTENT = '[data-markdown-copy="contents"], [data-dil-response], [data-markdown-text-style]' +const LEGACY = '[data-message-author-role]' + +const make = (role: Role, container: HTMLElement, content: HTMLElement): Turn => ({ + role, + element: content, + id: container.getAttribute('data-chatgpt-search-message-ids')?.split(' ')[0] ?? null, + text: () => (content.innerText ?? '').trim() +}) + +const fromUnits = (): Turn[] => + [...document.querySelectorAll(UNIT)].flatMap((unit): Turn[] => { + const role = UNIT_ROLE.exec(unit.getAttribute('data-chatgpt-search-unit-key') ?? '')?.[1] + if (isOwnUi(unit) || (role !== 'user' && role !== 'assistant')) return [] + return [make(role, unit, unit.querySelector(role === 'user' ? USER_CONTENT : ASSISTANT_CONTENT) ?? unit)] + }) + +const fromLegacy = (): Turn[] => + [...document.querySelectorAll(LEGACY)].flatMap((element): Turn[] => { + const role = element.getAttribute('data-message-author-role') + return !isOwnUi(element) && (role === 'user' || role === 'assistant') ? [make(role, element, element)] : [] + }) + +export const findTurns = (): Turn[] => { + const units = fromUnits() + return units.length ? units : fromLegacy() +} + +export const countTurns = (): Record => { + const turns = findTurns() + return { user: turns.filter((turn) => turn.role === 'user').length, assistant: turns.filter((turn) => turn.role === 'assistant').length } +} diff --git a/ai/chatgpt/src/ready.ts b/ai/chatgpt/src/ready.ts new file mode 100644 index 0000000..bcd455a --- /dev/null +++ b/ai/chatgpt/src/ready.ts @@ -0,0 +1,18 @@ +import { findComposerForm } from './locate' + +const FALLBACK_MS = 15_000 + +const ready = (): boolean => document.readyState === 'complete' && findComposerForm() !== null + +export const whenReady = (run: () => void): void => { + if (ready()) { + run() + return + } + const started = Date.now() + const timer = window.setInterval(() => { + if (!ready() && Date.now() - started < FALLBACK_MS) return + window.clearInterval(timer) + run() + }, 250) +} diff --git a/ai/chatgpt/src/repo.ts b/ai/chatgpt/src/repo.ts index aef95f2..2049ef3 100644 --- a/ai/chatgpt/src/repo.ts +++ b/ai/chatgpt/src/repo.ts @@ -3,6 +3,7 @@ import { repoUrls } from '@nolly/core' export const SLUG = 'better-chatgpt' const urls = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG, dir: 'ai/chatgpt' }) +const sharedPrompts = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: 'better-perplexity', dir: 'ai/perplexity' }) export const URLS = { home: urls.home, @@ -11,5 +12,5 @@ export const URLS = { sponsor: urls.sponsor, meta: urls.meta, install: urls.install, - prompts: urls.rawFile('prompts/library.json') + prompts: sharedPrompts.rawFile('prompts/library.json') } as const diff --git a/ai/chatgpt/src/runtime.ts b/ai/chatgpt/src/runtime.ts new file mode 100644 index 0000000..bff6715 --- /dev/null +++ b/ai/chatgpt/src/runtime.ts @@ -0,0 +1,6 @@ +import { responseSpy } from './network' +import { ChatSession } from './session' + +responseSpy.install() + +export const session = new ChatSession(responseSpy) diff --git a/ai/chatgpt/src/selectors.ts b/ai/chatgpt/src/selectors.ts index 6b54bf0..85e4b36 100644 --- a/ai/chatgpt/src/selectors.ts +++ b/ai/chatgpt/src/selectors.ts @@ -5,11 +5,7 @@ export const SELECTORS = { attach: '[data-composer-navigation-target="add-context"]', modeToggle: 'button[aria-pressed]', headerSlot: '[data-app-shell-header-obstacle="true"]', - sidebar: 'aside', - sidebarNav: 'aside nav', - codeBlock: '[data-code-block="true"]', - codeControls: '[data-code-block-controls]', - codeSource: '[data-chatgpt-copy-code]' + sidebar: 'aside' } as const export const STOP_LABEL = /\b(stop|arr[eê]t\w*|stopp\w*|detener|parar)\b/i diff --git a/ai/chatgpt/src/session.ts b/ai/chatgpt/src/session.ts index 40a33fe..bc51ea2 100644 --- a/ai/chatgpt/src/session.ts +++ b/ai/chatgpt/src/session.ts @@ -30,6 +30,10 @@ export class ChatSession { return [...this.limitMap.values()] } + limit(feature: string): LimitProgress | null { + return this.limitMap.get(feature) ?? null + } + subscribe(listener: (event: SessionEvent) => void): () => void { this.listeners.add(listener) return () => this.listeners.delete(listener) diff --git a/ai/chatgpt/src/storage.ts b/ai/chatgpt/src/storage.ts new file mode 100644 index 0000000..1f37528 --- /dev/null +++ b/ai/chatgpt/src/storage.ts @@ -0,0 +1,3 @@ +import { createStorage } from '@nolly/core' + +export const storage = createStorage({ namespace: 'better-chatgpt', gmPrefix: '' }) diff --git a/ai/chatgpt/src/theme.ts b/ai/chatgpt/src/theme.ts new file mode 100644 index 0000000..e1b3d9b --- /dev/null +++ b/ai/chatgpt/src/theme.ts @@ -0,0 +1,37 @@ +import { injectStyle } from '@nolly/core' + +const CSS = ` +html.dark .bp-themed { + --bp-bg: hsl(0 0% 13%); + --bp-fg: hsl(0 0% 98%); + --bp-muted: hsl(0 0% 64%); + --bp-border: hsl(0 0% 24%); + --bp-accent: hsl(0 0% 18%); + --bp-track: hsl(0 0% 30%); + --bp-ring: hsl(0 0% 60%); + --bp-green: hsl(142 71% 45%); + --bp-yellow: hsl(38 92% 50%); + --bp-red: hsl(0 84% 60%); +} + +html.light .bp-themed { + --bp-bg: hsl(0 0% 100%); + --bp-fg: hsl(0 0% 6%); + --bp-muted: hsl(0 0% 42%); + --bp-border: hsl(0 0% 88%); + --bp-accent: hsl(0 0% 95%); + --bp-track: hsl(0 0% 78%); + --bp-ring: hsl(0 0% 60%); + --bp-green: hsl(142 71% 40%); + --bp-yellow: hsl(38 92% 45%); + --bp-red: hsl(0 84% 55%); +} + +.bp-tip-mode { font-weight: 600; } +.bp-tip-sub { color: var(--bp-muted); } +.bp-tip-foot { margin-top: 4px; color: var(--bp-muted); font-size: 11px; } + +.bc-header-btn svg { width: 20px; height: 20px; } +` + +export const installTheme = (): void => injectStyle('better-chatgpt-theme', CSS) diff --git a/ai/chatgpt/src/threads.ts b/ai/chatgpt/src/threads.ts new file mode 100644 index 0000000..86f102d --- /dev/null +++ b/ai/chatgpt/src/threads.ts @@ -0,0 +1,3 @@ +const THREAD_PATH = /^\/(?:g\/[^/]+\/)?c\/[^/]+/ + +export const threadOf = (pathname: string): string | null => (THREAD_PATH.test(pathname) ? pathname : null) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 1fe6548..f284f18 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes to Better Perplexity are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. +- Internal: Prompt Library, Command Palette, Message Queue and Recall now come from the shared package. +- Internal: Enter as Newline now comes from the shared package. +- Internal: Draft Guard now comes from the shared package. +- Internal: Message Splitter now comes from the shared package. +- Internal: Code Block Pro now comes from the shared package. +- Internal: Batch Runner, Selection Toolbar and Max Width now come from the shared package. +- Internal: Exporter and Update checker now come from the shared package. +- Internal: one shared settings dialog; Batch Runner uses the shared prompt sender. +- Fixed: the batch runner was registered twice. + ## [1.0.5-hotfix.1] - 2026-11-09 ### Fixed diff --git a/ai/perplexity/README.md b/ai/perplexity/README.md index 6df4e52..59ca78b 100644 --- a/ai/perplexity/README.md +++ b/ai/perplexity/README.md @@ -59,9 +59,9 @@ No analytics and no server of its own. The script talks to Perplexity from your ## Built on the shared core -Better Perplexity is built on [`@nolly/core`](../core/README.md), the shared runtime used by every userscript in this repository. The core provides the feature lifecycle, storage, logging, DOM helpers, HTTP, menus, style injection and the page request observer. Better Perplexity keeps only what is specific to Perplexity: the modules, the composer and selector logic, and the UI. +Better Perplexity is built on [`@nolly/core`](../../core/README.md), the shared runtime, and on [`@nolly/ai`](../../core/ai/README.md), the code shared with the other AI-chat scripts (composer handling, key synthesis, generation detection). Better Perplexity keeps only what is specific to Perplexity: the modules, the selectors and the UI. -You do not install the core separately. It is bundled into `better-perplexity.user.js` at build time, so the installed script has no extra dependencies. See [Architecture](docs/architecture/) for details. +You do not install either package separately. Both are bundled into `better-perplexity.user.js` at build time, so the installed script has no extra dependencies. See [Architecture](docs/architecture/) for details. ## Development @@ -69,14 +69,14 @@ The repository is a Bun workspace. Install once at the repository root, then wor ```bash bun install # at the repository root -cd better-perplexity +cd ai/perplexity bun run dev # unminified, rebuilds on change bun run typecheck bun run build # minified userscript in dist/ ``` -Building needs the `core/` folder next to `better-perplexity/`. See [CONTRIBUTING.md](../CONTRIBUTING.md). +Building needs the `core/` and `core/ai/` folders at the repository root. See [CONTRIBUTING.md](../../CONTRIBUTING.md). ## License -[PolyForm Strict License 1.0.0](../LICENSE). +[PolyForm Strict License 1.0.0](../../LICENSE). diff --git a/ai/perplexity/docs/architecture.md b/ai/perplexity/docs/architecture.md index d3fe04c..2d09542 100644 --- a/ai/perplexity/docs/architecture.md +++ b/ai/perplexity/docs/architecture.md @@ -16,12 +16,15 @@ Better Perplexity is a thin layer on top of `@nolly/core`, a small library share - **Utilities:** storage, logging, DOM helpers, waiting, HTTP, userscript-manager menus, style injection and the page `fetch` observer. - **Build:** the metadata header and the bundle are produced by `@nolly/core/build`. +## What comes from @nolly/ai + +`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The common UI kit lives here too: the dialogs, toasts, tooltips, controls, icons and settings dialog are all shared across the userscripts, and Better Perplexity configures them once in `main.ts`. Features that need storage, logging or the composer do not reach into global singletons; instead they read them from a runtime registry the platform fills once at startup. That registry is the bridge between the shared AI layer and the script-specific selectors, storage keys and root DOM marker. + ## What stays in Better Perplexity - **Modules:** one folder per feature under `src/modules`. -- **Perplexity logic:** composer handling, selectors, placeholders and the usage tracker. -- **UI kit:** dialogs, toasts, tooltips and controls. -- **Instances:** the logger name, the storage key mapping, the UI marker `data-bp-root`, and the extraction of the account header from page requests. +- **Perplexity logic:** selectors, placeholders and the usage tracker. +- **Instances:** the logger name, the storage key mapping, the UI marker `data-bp-root`, the bindings of the shared kits, and the extraction of the account header from page requests. ## Compatibility @@ -29,4 +32,4 @@ Settings and drafts use the same storage keys as version 1.0.0, so nothing is lo ## Building from source -The repository is a Bun workspace. Run `bun install` at the root, then `bun run build` in `better-perplexity`. The build fails if the `core/` folder is missing. +The repository is a Bun workspace. Run `bun install` at the root, then `bun run build` in `ai/perplexity`. The build fails if the `core/` or `core/ai/` folders are missing. diff --git a/ai/perplexity/package.json b/ai/perplexity/package.json index 8566245..45851ca 100644 --- a/ai/perplexity/package.json +++ b/ai/perplexity/package.json @@ -1,26 +1,27 @@ { - "name": "@nolly/ai-perplexity", - "version": "1.0.5-hotfix.1", - "private": true, - "type": "module", - "license": "PolyForm-Strict-1.0.0", - "repository": { - "type": "git", - "url": "git+https://github.com/thenolle/userscripts.git", - "directory": "ai/perplexity" - }, - "scripts": { - "build": "bun run scripts/build.ts", - "dev": "bun run scripts/build.ts --watch", - "typecheck": "tsc --noEmit", - "validate:prompts": "bun run scripts/validate-prompts.ts" - }, - "dependencies": { - "@nolly/ai": "workspace:*", - "@nolly/core": "workspace:*" - }, - "devDependencies": { - "@types/bun": "^1.4.4", - "typescript": "^7.0.2" - } + "name": "@nolly/ai-perplexity", + "version": "1.0.5-hotfix.1", + "private": true, + "type": "module", + "license": "PolyForm-Strict-1.0.0", + "userscript": { "slug": "better-perplexity" }, + "repository": { + "type": "git", + "url": "git+https://github.com/thenolle/userscripts.git", + "directory": "ai/perplexity" + }, + "scripts": { + "build": "bun run scripts/build.ts", + "dev": "bun run scripts/build.ts --watch", + "typecheck": "tsc --noEmit", + "validate:prompts": "bun run scripts/validate-prompts.ts" + }, + "dependencies": { + "@nolly/ai": "workspace:*", + "@nolly/core": "workspace:*" + }, + "devDependencies": { + "@types/bun": "^1.4.4", + "typescript": "^7.0.2" + } } diff --git a/ai/perplexity/src/core/app.ts b/ai/perplexity/src/core/app.ts index c53c1af..25f26b6 100644 --- a/ai/perplexity/src/core/app.ts +++ b/ai/perplexity/src/core/app.ts @@ -1,6 +1,6 @@ +import { toggleSettingsDialog } from '@nolly/ai' import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from '../config' -import { toggleSettingsDialog } from '../ui/settings-dialog' import { uiMarker } from './dom' export class App extends Userscript { @@ -16,11 +16,7 @@ export class App extends Userscript { safetyInterval: CONFIG.safetyInterval, clearConsole: true, isReady: () => Boolean(document.querySelector('main')?.children.length), - openSettings: (script) => - toggleSettingsDialog(script.getFeatures(), () => { - script.refreshMenu() - script.requestUpdate() - }) + openSettings: (script) => toggleSettingsDialog(script) }) } } diff --git a/ai/perplexity/src/core/composer.ts b/ai/perplexity/src/core/composer.ts index e848c96..2b0c20b 100644 --- a/ai/perplexity/src/core/composer.ts +++ b/ai/perplexity/src/core/composer.ts @@ -1,6 +1,5 @@ import { createComposerKit } from '@nolly/ai' import { isOwnUi } from './dom' -export { EDITABLE_SELECTOR, isComposerEmpty, isSendButton, readComposer } from '@nolly/ai' - -export const { editableFrom, findComposer, writeComposer, sendComposer, attachFile } = createComposerKit({ isOwnUi }) +export const composerKit = createComposerKit({ isOwnUi }) +export const { editableFrom, findComposer, writeComposer, sendComposer, attachFile } = composerKit diff --git a/ai/perplexity/src/core/dispatch.ts b/ai/perplexity/src/core/dispatch.ts index 4cfdf78..e68b97b 100644 --- a/ai/perplexity/src/core/dispatch.ts +++ b/ai/perplexity/src/core/dispatch.ts @@ -1,14 +1,4 @@ -import { sleep, waitFor } from '@nolly/core' -import { automate } from './automation' -import { findComposer, readComposer, sendComposer, writeComposer } from './composer' +import { createPromptSender } from '@nolly/ai' +import { findComposer, sendComposer, writeComposer } from './composer' -export const sendPrompt = (prompt: string, signal?: AbortSignal): Promise => automate(async () => { - for (let attempt = 0; attempt < 2; attempt++) { - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) - if (!composer) return false - if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true - if (readComposer(composer).trim() === '') return true - await sleep(1_500, signal) - } - return false -}) +export const sendPrompt = createPromptSender({ findComposer, writeComposer, sendComposer }) diff --git a/ai/perplexity/src/core/generation.ts b/ai/perplexity/src/core/generation.ts index 8379a17..8652a2a 100644 --- a/ai/perplexity/src/core/generation.ts +++ b/ai/perplexity/src/core/generation.ts @@ -1,6 +1,5 @@ import { createGenerationKit } from '@nolly/ai' import { isOwnUi } from './dom' -export type { ResponseWaitOptions } from '@nolly/ai' - -export const { isGenerating, waitForResponse } = createGenerationKit({ adapter: { isOwnUi } }) +export const generationKit = createGenerationKit({ adapter: { isOwnUi } }) +export const { isGenerating, waitForResponse } = generationKit diff --git a/ai/perplexity/src/core/synthetic-keys.ts b/ai/perplexity/src/core/synthetic-keys.ts deleted file mode 100644 index 038ba9d..0000000 --- a/ai/perplexity/src/core/synthetic-keys.ts +++ /dev/null @@ -1 +0,0 @@ -export { dispatchEnter, findGenericSendButton as findSendButton, isSynthetic } from '@nolly/ai' diff --git a/ai/perplexity/src/core/threads.ts b/ai/perplexity/src/core/threads.ts new file mode 100644 index 0000000..54e22b3 --- /dev/null +++ b/ai/perplexity/src/core/threads.ts @@ -0,0 +1,3 @@ +const ROOT_PATH = /^\/(?:computer|spaces|library|discover)?\/?$/ + +export const threadOf = (pathname: string): string | null => (ROOT_PATH.test(pathname) ? null : pathname) diff --git a/ai/perplexity/src/modules/exporter/api.ts b/ai/perplexity/src/export-source.ts similarity index 72% rename from ai/perplexity/src/modules/exporter/api.ts rename to ai/perplexity/src/export-source.ts index bb50e04..873b856 100644 --- a/ai/perplexity/src/modules/exporter/api.ts +++ b/ai/perplexity/src/export-source.ts @@ -1,7 +1,8 @@ -import { storage } from '../../core/storage' -import { readCookieAccountId } from '../usage-status/account-cookie' +import type { ExportSource } from '@nolly/ai' +import { storage } from './core/storage' +import { readCookieAccountId } from './modules/usage-status/account-cookie' -export interface ExportedFile { +interface ExportedFile { filename: string bytes: Uint8Array } @@ -21,7 +22,7 @@ const request = (path: string, init: RequestInit = {}): Promise => { }) } -export const currentThreadSlug = (): string | null => { +const currentThreadSlug = (): string | null => { const segments = location.pathname.split('/').filter(Boolean) return segments.length >= 2 && !NON_THREAD_ROOTS.has(segments[0]!) ? (segments.at(-1) ?? null) : null } @@ -52,7 +53,7 @@ const fetchThread = async (slug: string): Promise => { return response.json() } -export const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: string): Promise => { +const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: string): Promise => { const slug = currentThreadSlug() if (!slug) throw new Error('Open a thread first.') try { @@ -64,8 +65,25 @@ export const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: stri } } -export const fetchThreadJson = async (): Promise => { +const fetchThreadJson = async (): Promise => { const slug = currentThreadSlug() if (!slug) throw new Error('Open a thread first.') return JSON.stringify(await fetchThread(slug), null, 2) -} \ No newline at end of file +} + +const fileBase = (): string => (currentThreadSlug() ?? 'perplexity-thread').replace(/[^\w-]+/g, '-').slice(0, 60) || 'perplexity-thread' + +export const exportSource: ExportSource = { + name: 'Perplexity', + citations: true, + slug: currentThreadSlug, + markdown: async () => new TextDecoder().decode((await exportThread('md', fileBase())).bytes), + json: fetchThreadJson, + place: (button) => { + const indicator = document.querySelector('.bp-usage-indicator') + if (!indicator) return false + const gear = indicator.querySelector('.bp-gear') + if (button.parentElement !== indicator || (gear && button.nextElementSibling !== gear)) indicator.insertBefore(button, gear) + return true + } +} diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index 24bd66b..d0aa46f 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,39 +1,55 @@ +import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, ExporterFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, UpdatesFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' +import { composerKit, findComposer, writeComposer } from './core/composer' +import { sendPrompt } from './core/dispatch' +import { uiMarker } from './core/dom' import { fetchSpy } from './core/fetch-spy' -import { BatchRunnerModule } from './modules/batch-runner' -import { CodeBlocksModule } from './modules/code-blocks' -import { CommandPaletteModule } from './modules/command-palette' -import { DraftGuardModule } from './modules/draft-guard' -import { EnterAsNewlineModule } from './modules/enter-as-newline' -import { ExporterModule } from './modules/exporter' +import { generationKit } from './core/generation' +import { logger } from './core/logger' +import { isAskRequest } from './core/requests' +import { storage } from './core/storage' +import { threadOf } from './core/threads' +import { exportSource } from './export-source' +import { findComposerActions } from './locate' import { GlobalSettingsModule } from './modules/global-settings' -import { MaxWidthModule } from './modules/max-width' -import { MessageSplitterModule } from './modules/message-splitter' -import { PromptLibraryModule } from './modules/prompt-library' -import { SelectionToolbarModule } from './modules/selection-toolbar' +import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR } from './modules/max-width/rules' import { TutorialModule } from './modules/tutorial' -import { UpdatesModule } from './modules/updates' import { UsageStatusModule } from './modules/usage-status' -import { PromptQueueModule } from './modules/prompt-queue' -import { RecallModule } from './modules/recall' +import { URLS } from './repo' +const onSend = (listener: () => void): (() => void) => fetchSpy.subscribe(({ method, url }) => { if (isAskRequest(method, url)) listener() }) + +configureUi({ id: 'better-perplexity', title: 'Better Perplexity', version: __VERSION__, marker: uiMarker, composerActions: findComposerActions }) +configurePlatform({ + id: 'better-perplexity', + storage, + logger, + composer: composerKit, + generation: generationKit, + sendPrompt, + onSend, + threadOf, + promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better Perplexity', slug: 'better-perplexity', version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases } +}) fetchSpy.install() new App() - .register((context) => new PromptLibraryModule(context)) - .register((context) => new SelectionToolbarModule(context)) - .register((context) => new MaxWidthModule(context)) - .register((context) => new EnterAsNewlineModule(context)) - .register((context) => new CodeBlocksModule(context)) - .register((context) => new MessageSplitterModule(context)) - .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardModule(context)) - .register((context) => new CommandPaletteModule(context)) - .register((context) => new ExporterModule(context)) + .register((context) => new PromptLibraryFeature(context)) + .register((context) => new SelectionToolbarFeature(context)) + .register((context) => new MaxWidthFeature(context, { storage, hidden: ALWAYS_HIDDEN, layout: LAYOUT_RULES, sidebar: { rule: RIGHT_SIDEBAR, label: 'Right Sidebar', defaultRemoved: true } })) + .register((context) => new EnterAsNewlineFeature(context, { storage })) + .register((context) => new CodeBlocksFeature(context)) + .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit })) + .register((context) => new BatchRunnerFeature(context)) + .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend, tokenLimit: () => loadSplitterSettings(storage).limit })) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new ExporterFeature(context)) .register((context) => new UsageStatusModule(context)) .register((context) => new GlobalSettingsModule(context)) .register((context) => new TutorialModule(context)) - .register((context) => new UpdatesModule(context)) - .register((context) => new PromptQueueModule(context)) - .register((context) => new RecallModule(context)) + .register((context) => new UpdatesFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) .start() diff --git a/ai/perplexity/src/modules/draft-guard/index.ts b/ai/perplexity/src/modules/draft-guard/index.ts deleted file mode 100644 index 72189eb..0000000 --- a/ai/perplexity/src/modules/draft-guard/index.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { findComposer, isSendButton, readComposer, writeComposer } from '../../core/composer' -import { Feature, type MenuEntry, type ScriptContext, toElement } from '@nolly/core' -import { fetchSpy } from '../../core/fetch-spy' -import { storage } from '../../core/storage' -import { loadSplitterSettings } from '../message-splitter/settings' -import { DraftOverlay } from './overlay' -import { DraftStore, type Draft } from './store' -import { isAskRequest } from '../../core/requests' - -const SAVE_DELAY = 400 -const SEND_WINDOW = 3_000 -const GUARD_KEY = 'draft-guard:warn-on-close' -const SPLIT_COMMAND = 'message-splitter:split' - -const threadKey = (): string => location.pathname || '/' -const meaningful = (text: string): boolean => text.replace(/[\s\u200b]/g, '') !== '' - -export class DraftGuardModule extends Feature { - readonly id = 'draft-guard' - readonly name = 'Draft Guard' - readonly description = 'Autosaves drafts, shows a size meter and warns about unsent text.' - - private readonly store = new DraftStore() - private readonly overlay = new DraftOverlay() - private readonly wired = new WeakSet() - private readonly dismissed = new Set() - private readonly typed = new Set() - private readonly offered = new Map() - private key = threadKey() - private lastText = '' - private saveTimer = 0 - private sendIntentAt = 0 - private guardAttached = false - private composer: HTMLElement | null = null - - constructor(context: ScriptContext) { - super(context) - this.overlay.onSplit(() => this.context.runCommand(SPLIT_COMMAND)) - fetchSpy.subscribe(({ method, url }) => { - if (this.enabled && isAskRequest(method, url) && meaningful(this.lastText)) this.discard(this.key) - }) - document.addEventListener('click', this.handleClick, true) - document.addEventListener('keydown', this.handleKeydown, true) - window.addEventListener('scroll', this.reposition, true) - window.addEventListener('resize', this.reposition) - } - - get warnOnClose(): boolean { - return storage.get(GUARD_KEY, true) - } - - set warnOnClose(value: boolean) { - storage.set(GUARD_KEY, value) - } - - run(): void { - if (!this.enabled) { - this.teardown() - return - } - this.syncGuard() - const composer = findComposer() - this.composer = composer - if (!composer) { - this.overlay.hideAll() - return - } - this.wire(composer) - this.syncThread() - const text = readComposer(composer) - if (text !== this.lastText) this.handleChange(text) - this.refreshOverlay(composer, text) - } - - override menuEntries(): MenuEntry[] { - return [{ id: 'guard', label: `${this.warnOnClose ? 'Disable' : 'Enable'} Unsent-Text Warning`, action: () => this.toggleGuard() }] - } - - private wire(composer: HTMLElement): void { - if (this.wired.has(composer)) return - this.wired.add(composer) - composer.addEventListener('input', (event) => { - if (event.isTrusted) this.typed.add(this.key) - this.run() - }) - } - - private syncThread(): void { - const key = threadKey() - if (key === this.key) return - window.clearTimeout(this.saveTimer) - this.key = key - this.lastText = '' - } - - private handleChange(text: string): void { - const previous = this.lastText - this.lastText = text - window.clearTimeout(this.saveTimer) - if (!meaningful(text)) { - if (meaningful(previous) && Date.now() - this.sendIntentAt < SEND_WINDOW) this.discard(this.key) - return - } - const key = this.key - this.saveTimer = window.setTimeout(() => this.store.set(key, text), SAVE_DELAY) - } - - private discard(key: string): void { - window.clearTimeout(this.saveTimer) - this.store.remove(key) - this.offered.delete(key) - this.dismissed.add(key) - this.overlay.hideBanner() - } - - private refreshOverlay(composer: HTMLElement, text: string): void { - if (meaningful(text)) this.overlay.showMeter(composer, text, loadSplitterSettings().limit) - else this.overlay.hideMeter() - const key = this.key - if (this.dismissed.has(key) || this.typed.has(key)) { - this.offered.delete(key) - this.overlay.hideBanner() - return - } - const draft = this.offered.get(key) ?? this.store.get(key) - if (!draft) { - this.overlay.hideBanner() - return - } - this.offered.set(key, draft) - this.overlay.showBanner(composer, draft, () => { - this.offered.delete(key) - this.dismissed.add(key) - this.overlay.hideBanner() - void writeComposer(composer, draft.text) - }, () => this.discard(key)) - } - - private isComposerControl(button: HTMLElement): boolean { - const composer = this.composer - if (!composer) return false - const form = composer.closest('form') - if (form) return form.contains(button) - let scope: HTMLElement | null = composer - for (let depth = 0; scope && depth < 4; depth++) { - if (scope.contains(button)) return true - scope = scope.parentElement - } - return false - } - - private readonly handleClick = (event: MouseEvent): void => { - const button = toElement(event.target)?.closest('button') - if (!this.enabled || !button || !isSendButton(button) || !this.isComposerControl(button)) return - this.sendIntentAt = Date.now() - this.dismissed.add(this.key) - this.offered.delete(this.key) - this.overlay.hideBanner() - } - - private readonly handleKeydown = (event: KeyboardEvent): void => { - if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && meaningful(this.lastText)) this.sendIntentAt = Date.now() - } - - private readonly reposition = (): void => { - if (this.composer?.isConnected) this.overlay.position(this.composer) - } - - private readonly handleBeforeUnload = (event: BeforeUnloadEvent): void => { - const composer = this.composer ?? findComposer() - if (!composer || !meaningful(readComposer(composer))) return - event.preventDefault() - event.returnValue = '' - } - - private syncGuard(): void { - if (this.warnOnClose && !this.guardAttached) { - window.addEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = true - } else if (!this.warnOnClose && this.guardAttached) { - window.removeEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = false - } - } - - private toggleGuard(): void { - this.warnOnClose = !this.warnOnClose - this.context.refreshMenu() - this.context.requestUpdate() - } - - private teardown(): void { - this.overlay.hideAll() - if (this.guardAttached) window.removeEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = false - } -} diff --git a/ai/perplexity/src/modules/enter-as-newline/config-button.ts b/ai/perplexity/src/modules/enter-as-newline/config-button.ts deleted file mode 100644 index 0665bfe..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/config-button.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { findComposerActions } from '../../locate' -import { ensureUiStyles } from '../../ui/styles' -import { Tooltip } from '../../ui/tooltip' -import { ensureConfigButtonStyles } from './styles' - -const SVG_NS = 'http://www.w3.org/2000/svg' - -const createIcon = (): SVGSVGElement => { - const svg = document.createElementNS(SVG_NS, 'svg') - for (const [name, value] of Object.entries({ width: '16', height: '16', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(name, value) - const arrow = document.createElementNS(SVG_NS, 'polyline') - arrow.setAttribute('points', '9 10 4 15 9 20') - const line = document.createElementNS(SVG_NS, 'path') - line.setAttribute('d', 'M20 4v7a4 4 0 0 1-4 4H4') - svg.append(arrow, line) - return svg -} - -export class ConfigButton { - readonly element = markUi(createElement('button', 'bp-config-button')) - private readonly tooltip: Tooltip - private appliedClass = '' - - constructor(onClick: () => void, describe: () => string) { - ensureUiStyles() - ensureConfigButtonStyles() - this.element.type = 'button' - this.element.setAttribute('aria-label', 'Configure Enter as Newline') - this.element.appendChild(createIcon()) - this.element.addEventListener('click', (event) => { - event.preventDefault() - event.stopPropagation() - onClick() - }) - this.tooltip = new Tooltip(this.element, (container) => { - container.append(createElement('div', 'bp-tip-mode', 'Enter as Newline'), createElement('div', 'bp-tip-sub', describe()), createElement('div', 'bp-tip-foot', 'Click to configure')) - }) - } - - mount(): void { - const { first, submit } = findComposerActions() - if (!first && !submit) { - this.unmount() - return - } - if (first) this.syncClass(first) - const placed = first ? first.nextElementSibling === this.element : submit?.previousElementSibling === this.element - if (placed) return - if (first) first.insertAdjacentElement('afterend', this.element) - else submit?.insertAdjacentElement('beforebegin', this.element) - } - - unmount(): void { - this.tooltip.hide() - this.element.remove() - } - - private syncClass(reference: HTMLElement): void { - const next = `${reference.className} bp-config-button` - if (next === this.appliedClass) return - this.element.className = next - this.appliedClass = next - } -} diff --git a/ai/perplexity/src/modules/enter-as-newline/index.ts b/ai/perplexity/src/modules/enter-as-newline/index.ts deleted file mode 100644 index 656c0d8..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/index.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { logger } from '../../core/logger' -import { Feature, type MenuEntry } from '@nolly/core' -import { ConfigButton } from './config-button' -import { toggleShortcutsDialog } from './dialog' -import { getEditableTarget, insertNewline, isComposing, isSynthetic, sendMessage } from './keyboard' -import { describeShortcuts, hasModifier, loadShortcuts, matchesShortcut, saveShortcuts, type ShortcutSettings } from './shortcuts' - -export class EnterAsNewlineModule extends Feature { - readonly id = 'enter-as-newline' - readonly name = 'Enter as Newline' - readonly description = 'Use Enter for newlines and configurable shortcuts to send messages.' - - private shortcuts: ShortcutSettings = loadShortcuts() - private attached = false - private readonly configButton = new ConfigButton( - () => this.configure(), - () => describeShortcuts(this.shortcuts) - ) - - run(): void { - if (this.enabled) this.configButton.mount() - else this.configButton.unmount() - if (this.enabled && !this.attached) { - window.addEventListener('keydown', this.handleKeydown, true) - this.attached = true - logger.success('Enter as Newline listener registered.') - return - } - if (!this.enabled && this.attached) { - window.removeEventListener('keydown', this.handleKeydown, true) - this.attached = false - logger.info('Enter as Newline listener removed.') - } - } - - override menuEntries(): MenuEntry[] { - return [{ label: 'Configure Enter as Newline', action: () => this.configure() }] - } - - private configure(): void { - toggleShortcutsDialog(this.shortcuts, (settings) => { - this.shortcuts = settings - saveShortcuts(settings) - }) - } - - private readonly handleKeydown = (event: KeyboardEvent): void => { - if (event.key !== 'Enter' || isComposing(event) || isSynthetic(event)) return - const editable = getEditableTarget(event) - if (!editable) return - if (matchesShortcut(event, this.shortcuts)) { - event.preventDefault() - event.stopImmediatePropagation() - sendMessage(editable) - return - } - if (hasModifier(event)) return - event.preventDefault() - event.stopImmediatePropagation() - insertNewline(editable) - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/enter-as-newline/styles.ts b/ai/perplexity/src/modules/enter-as-newline/styles.ts deleted file mode 100644 index f1cbee9..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/styles.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { injectStyle } from '@nolly/core' - -const CSS = ` -.bp-config-button { - display: inline-flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - cursor: pointer; -} - -.bp-config-button svg { pointer-events: none; } -` - -export const ensureConfigButtonStyles = (): void => injectStyle('better-perplexity-enter-styles', CSS) \ No newline at end of file diff --git a/ai/perplexity/src/modules/global-settings/dialog.ts b/ai/perplexity/src/modules/global-settings/dialog.ts deleted file mode 100644 index fa17fa4..0000000 --- a/ai/perplexity/src/modules/global-settings/dialog.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { createElement, type ScriptContext } from '@nolly/core' -import { createButton, createSwitch } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' -import { ensureGearStyles } from './styles' - -const DIALOG_ID = 'better-perplexity-settings-dialog' - -export const toggleGlobalSettings = (context: ScriptContext): void => { - const existing = document.getElementById(DIALOG_ID) - if (existing instanceof HTMLDialogElement) { - existing.close() - return - } - ensureGearStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Better Perplexity', description: `Version ${__VERSION__}`, width: 560 }) - const render = (): void => { - ui.body.replaceChildren( - ...context.getFeatures().map((module) => { - const section = createElement('section', 'bp-section') - section.appendChild( - createSwitch({ - label: module.name, - hint: module.description, - checked: module.enabled, - onChange: () => { - module.toggle() - render() - } - }).wrapper - ) - if (module.enabled) { - const actions = createElement('div', 'bp-actions') - for (const entry of module.menuEntries()) { - actions.appendChild( - createButton(entry.label, { - onClick: () => { - ui.close() - window.setTimeout(entry.action, 0) - } - }) - ) - } - if (actions.childElementCount) section.appendChild(actions) - } - return section - }) - ) - } - render() - ui.footer.append( - createButton('Command palette', { - onClick: () => { - ui.close() - window.setTimeout(() => context.runCommand('command-palette:open'), 0) - } - }), - createButton('Close', { primary: true, onClick: ui.close }) - ) - ui.show() -} diff --git a/ai/perplexity/src/modules/global-settings/index.ts b/ai/perplexity/src/modules/global-settings/index.ts index 2bb100a..98bed3c 100644 --- a/ai/perplexity/src/modules/global-settings/index.ts +++ b/ai/perplexity/src/modules/global-settings/index.ts @@ -1,9 +1,6 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' -import { Tooltip } from '../../ui/tooltip' -import { toggleGlobalSettings } from './dialog' +import { createIcon, ensureUiStyles, toggleSettingsDialog, Tooltip } from '@nolly/ai' import { ensureGearStyles } from './styles' const INDICATOR_SELECTOR = '.bp-usage-indicator' @@ -42,6 +39,6 @@ export class GlobalSettingsModule extends Feature { } private open(): void { - toggleGlobalSettings(this.context) + toggleSettingsDialog(this.context) } } \ No newline at end of file diff --git a/ai/perplexity/src/modules/global-settings/styles.ts b/ai/perplexity/src/modules/global-settings/styles.ts index d346881..8d89da4 100644 --- a/ai/perplexity/src/modules/global-settings/styles.ts +++ b/ai/perplexity/src/modules/global-settings/styles.ts @@ -20,7 +20,6 @@ const CSS = ` .bp-gear:hover { background: var(--bp-accent); } .bp-gear:focus-visible { outline: 2px solid var(--bp-fg); outline-offset: 2px; } -.bp-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 2px; } ` -export const ensureGearStyles = (): void => injectStyle('better-perplexity-gear-styles', CSS) \ No newline at end of file +export const ensureGearStyles = (): void => injectStyle('better-perplexity-gear-styles', CSS) diff --git a/ai/perplexity/src/modules/max-width/index.ts b/ai/perplexity/src/modules/max-width/index.ts deleted file mode 100644 index 28dafaa..0000000 --- a/ai/perplexity/src/modules/max-width/index.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Feature, getElement, type MenuEntry } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR, type HideRule } from './rules' -import { StyleManager } from './style-manager' - -const SIDEBAR_KEY = 'max-width:remove-sidebar' -const CONSTRAINED = 'main [class*="max-w-"], main [style*="max-width"]' -const OVERLAYS = '[role="dialog"], [role="menu"], [role="listbox"], [role="tooltip"], dialog, [data-radix-popper-content-wrapper]' -const MIN_CONSTRAINT = 480 -const SCAN_INTERVAL = 1_200 - -export class MaxWidthModule extends Feature { - readonly id = 'max-width' - readonly name = 'Max Width' - readonly description = 'Remove width restrictions and expand the interface.' - - private readonly styles = new StyleManager() - private readonly touched = new Set() - private scannedAt = 0 - - get removeSidebar(): boolean { - return storage.get(SIDEBAR_KEY, true) - } - - set removeSidebar(value: boolean) { - storage.set(SIDEBAR_KEY, value) - } - - run(): void { - const active = this.enabled - for (const rule of ALWAYS_HIDDEN) this.syncHidden(rule, active) - this.syncHidden(RIGHT_SIDEBAR, active && this.removeSidebar) - for (const { xpath, styles } of LAYOUT_RULES) { - const element = getElement(xpath) - if (!element) continue - if (active) this.styles.apply(element, styles) - else this.styles.restore(element, Object.keys(styles)) - } - this.expand(active) - } - - override menuEntries(): MenuEntry[] { - return [{ label: `${this.removeSidebar ? 'Show' : 'Remove'} Right Sidebar`, action: () => this.toggleSidebar() }] - } - - private expand(active: boolean): void { - if (!active) { - for (const element of this.touched) this.styles.restore(element, ['max-width']) - this.touched.clear() - return - } - const now = Date.now() - if (now - this.scannedAt < SCAN_INTERVAL) return - this.scannedAt = now - for (const element of this.touched) if (!element.isConnected) this.touched.delete(element) - for (const element of document.querySelectorAll(CONSTRAINED)) { - if (this.touched.has(element) || isOwnUi(element) || element.closest(OVERLAYS)) continue - const limit = Number.parseFloat(getComputedStyle(element).maxWidth) - if (!Number.isFinite(limit) || limit < MIN_CONSTRAINT) continue - if (element.getBoundingClientRect().width < limit * 0.9) continue - this.styles.apply(element, { 'max-width': '100%' }) - this.touched.add(element) - } - } - - private syncHidden(rule: HideRule, hidden: boolean): void { - const element = getElement(rule.xpath) - if (element) this.styles.setHidden(element, hidden, rule.xpath) - } - - private toggleSidebar(): void { - this.removeSidebar = !this.removeSidebar - logger.info(`Right sidebar removal ${this.removeSidebar ? 'enabled' : 'disabled'}.`) - this.context.refreshMenu() - this.context.requestUpdate() - } -} diff --git a/ai/perplexity/src/modules/max-width/rules.ts b/ai/perplexity/src/modules/max-width/rules.ts index 1fbc518..94a63c3 100644 --- a/ai/perplexity/src/modules/max-width/rules.ts +++ b/ai/perplexity/src/modules/max-width/rules.ts @@ -1,15 +1,6 @@ +import type { HideRule, LayoutRule } from '@nolly/ai' import { CONTENT, ROOT } from '../../selectors' -export interface HideRule { - readonly id: string - readonly xpath: string -} - -export interface LayoutRule { - readonly xpath: string - readonly styles: Readonly> -} - const FULL = { width: '100%', 'max-width': '100%' } as const export const RIGHT_SIDEBAR: HideRule = { id: 'right-sidebar', xpath: `${CONTENT}[2]` } @@ -31,4 +22,4 @@ export const LAYOUT_RULES: readonly LayoutRule[] = [ { xpath: `${CONTENT}[4]/div`, styles: FULL }, { xpath: `${ROOT}/div[5]/div`, styles: { ...FULL, 'padding-left': '1rem', 'padding-right': '1rem' } }, { xpath: `${ROOT}/div[5]/div/div`, styles: { ...FULL, padding: '0' } } -] \ No newline at end of file +] diff --git a/ai/perplexity/src/modules/message-splitter/settings.ts b/ai/perplexity/src/modules/message-splitter/settings.ts deleted file mode 100644 index ecd1531..0000000 --- a/ai/perplexity/src/modules/message-splitter/settings.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { storage } from '../../core/storage' - -export interface SplitterSettings { - limit: number - autoIntercept: boolean - balanced: boolean - mode: 'parts' | 'file' -} - -const STORAGE_KEY = 'message-splitter:settings' - -export const DEFAULT_SPLITTER_SETTINGS: Readonly = { limit: 7_500, autoIntercept: true, balanced: true, mode: 'parts' } - -export const loadSplitterSettings = (): SplitterSettings => ({ ...DEFAULT_SPLITTER_SETTINGS, ...storage.get>(STORAGE_KEY, {}) }) - -export const saveSplitterSettings = (settings: SplitterSettings): void => storage.set(STORAGE_KEY, settings) \ No newline at end of file diff --git a/ai/perplexity/src/modules/tutorial/engine.ts b/ai/perplexity/src/modules/tutorial/engine.ts index a9992a9..d50576a 100644 --- a/ai/perplexity/src/modules/tutorial/engine.ts +++ b/ai/perplexity/src/modules/tutorial/engine.ts @@ -1,8 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton } from '../../ui/controls' -import { ensureUiStyles } from '../../ui/styles' -import { formatShortcut, matchesShortcut, type Shortcut } from '../command-palette/shortcut' +import { createButton, ensureUiStyles, formatShortcut, matchesShortcut, type Shortcut } from '@nolly/ai' import { ensureTourStyles } from './styles' export interface Step { diff --git a/ai/perplexity/src/modules/tutorial/index.ts b/ai/perplexity/src/modules/tutorial/index.ts index e7a9b80..d9ad0e8 100644 --- a/ai/perplexity/src/modules/tutorial/index.ts +++ b/ai/perplexity/src/modules/tutorial/index.ts @@ -1,12 +1,7 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' import { storage } from '../../core/storage' -import { createButton } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' -import { showToast } from '../../ui/toast' -import { Tooltip } from '../../ui/tooltip' +import { createButton, createDialog, createIcon, ensureUiStyles, showToast, Tooltip } from '@nolly/ai' import { TourRunner } from './engine' import { FULL_TOUR, TOURS, type Tour } from './tours' diff --git a/ai/perplexity/src/modules/tutorial/tours.ts b/ai/perplexity/src/modules/tutorial/tours.ts index d72187e..a885f5b 100644 --- a/ai/perplexity/src/modules/tutorial/tours.ts +++ b/ai/perplexity/src/modules/tutorial/tours.ts @@ -1,7 +1,5 @@ import { findComposer } from '../../core/composer' -import { loadShortcut } from '../command-palette/shortcut' -import { loadPromptShortcut } from '../prompt-library/shortcut' -import type { Shortcut } from '../command-palette/shortcut' +import { loadPromptShortcut, loadShortcut, type Shortcut } from '@nolly/ai' import type { Step } from './engine' export interface Tour { diff --git a/ai/perplexity/src/modules/usage-status/alerts.ts b/ai/perplexity/src/modules/usage-status/alerts.ts index a3c5902..73d418b 100644 --- a/ai/perplexity/src/modules/usage-status/alerts.ts +++ b/ai/perplexity/src/modules/usage-status/alerts.ts @@ -1,6 +1,6 @@ import { notify, notifyPermission } from '@nolly/core' import { storage } from '../../core/storage' -import { showToast } from '../../ui/toast' +import { showToast } from '@nolly/ai' import { LIMITS, LIMIT_KEYS } from './definitions' import type { UsageService } from './service' import type { LimitKey } from './types' diff --git a/ai/perplexity/src/modules/usage-status/dialog.ts b/ai/perplexity/src/modules/usage-status/dialog.ts index bf94a5a..15c4303 100644 --- a/ai/perplexity/src/modules/usage-status/dialog.ts +++ b/ai/perplexity/src/modules/usage-status/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton, createDataRow, createSection } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createDataRow, createSection, createDialog } from '@nolly/ai' import { createStatusBar, createTimerBlock } from './components' import { LIMITS, LIMIT_KEYS, SETTINGS_FIELDS, SOURCE_LABELS, STATUS_LABELS } from './definitions' import { getStatus } from './format' diff --git a/ai/perplexity/src/modules/usage-status/index.ts b/ai/perplexity/src/modules/usage-status/index.ts index 5662112..09a4739 100644 --- a/ai/perplexity/src/modules/usage-status/index.ts +++ b/ai/perplexity/src/modules/usage-status/index.ts @@ -4,7 +4,7 @@ import { fetchSpy } from '../../core/fetch-spy' import { logger } from '../../core/logger' import { isAskRequest } from '../../core/requests' import { describePage } from '../../locate' -import { showToast } from '../../ui/toast' +import { showToast } from '@nolly/ai' import { UsageAlerts } from './alerts' import { UsageDialog } from './dialog' import { UsageIndicator } from './indicator' diff --git a/ai/perplexity/src/modules/usage-status/indicator.ts b/ai/perplexity/src/modules/usage-status/indicator.ts index 40f19e4..2929037 100644 --- a/ai/perplexity/src/modules/usage-status/indicator.ts +++ b/ai/perplexity/src/modules/usage-status/indicator.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { Tooltip } from '../../ui/tooltip' -import { ensureUiStyles } from '../../ui/styles' +import { Tooltip, ensureUiStyles } from '@nolly/ai' import { Dock } from './dock' import { isPlaced, type Placement } from './placement' import type { UsageService } from './service' diff --git a/ai/perplexity/src/ui/controls.ts b/ai/perplexity/src/ui/controls.ts deleted file mode 100644 index a64379b..0000000 --- a/ai/perplexity/src/ui/controls.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { createElement } from '@nolly/core' - -export interface ButtonOptions { - primary?: boolean - onClick?: (event: MouseEvent) => void -} - -export interface SwitchOptions { - label: string - hint?: string - checked: boolean - onChange: (checked: boolean) => void -} - -export interface NumberFieldOptions { - label: string - hint?: string - value: number - min?: number - max?: number - step?: number - onChange: (value: number) => void -} - -export const createButton = (label: string, { primary = false, onClick }: ButtonOptions = {}): HTMLButtonElement => { - const button = createElement('button', primary ? 'bp-button bp-button-primary' : 'bp-button', label) - button.type = 'button' - if (onClick) button.addEventListener('click', onClick) - return button -} - -export const createSwitch = ({ label, hint, checked, onChange }: SwitchOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { - const wrapper = createElement('label', 'bp-switch') - const text = createElement('span', 'bp-switch-text') - text.appendChild(createElement('span', undefined, label)) - if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) - const input = createElement('input') - input.type = 'checkbox' - input.checked = checked - input.addEventListener('change', () => onChange(input.checked)) - wrapper.append(text, input, createElement('span', 'bp-switch-track')) - return { wrapper, input } -} - -export const createSection = (title: string, aside?: string): HTMLElement => { - const section = createElement('section', 'bp-section') - const heading = createElement('h3', 'bp-section-heading') - heading.appendChild(createElement('span', undefined, title)) - if (aside !== undefined) heading.appendChild(createElement('span', undefined, aside)) - section.appendChild(heading) - return section -} - -export const createDataRow = (label: string, value: string, className = ''): HTMLElement => { - const row = createElement('div', 'bp-data-row') - row.append(createElement('span', 'bp-data-label', label), createElement('span', `bp-data-value ${className}`.trim(), value)) - return row -} - -export const createNumberField = ({ label, hint, value, min, max, step = 1, onChange }: NumberFieldOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { - const wrapper = createElement('label', 'bp-field') - const text = createElement('span', 'bp-switch-text') - text.appendChild(createElement('span', undefined, label)) - if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) - const input = createElement('input', 'bp-input') - input.type = 'number' - input.value = String(value) - input.step = String(step) - if (min !== undefined) input.min = String(min) - if (max !== undefined) input.max = String(max) - input.addEventListener('change', () => { - const parsed = Number(input.value) - if (!Number.isFinite(parsed)) return - const clamped = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, parsed)) - input.value = String(clamped) - onChange(clamped) - }) - wrapper.append(text, input) - return { wrapper, input } -} - -export const createSelectField = (label: string, options: readonly { value: T; label: string }[], value: T, onChange: (value: T) => void): HTMLLabelElement => { - const wrapper = createElement('label', 'bp-field') - wrapper.appendChild(createElement('span', undefined, label)) - const select = createElement('select', 'bp-input') - for (const option of options) { - const element = createElement('option', undefined, option.label) - element.value = option.value - select.appendChild(element) - } - select.value = value - select.addEventListener('change', () => onChange(select.value as T)) - wrapper.appendChild(select) - return wrapper -} - -export const createTextArea = (placeholder: string, value: string, onInput: (value: string) => void): HTMLTextAreaElement => { - const area = createElement('textarea', 'bp-input') - area.placeholder = placeholder - area.value = value - area.rows = 3 - area.addEventListener('input', () => onInput(area.value)) - return area -} \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/dialog.ts b/ai/perplexity/src/ui/css/dialog.ts deleted file mode 100644 index 983465f..0000000 --- a/ai/perplexity/src/ui/css/dialog.ts +++ /dev/null @@ -1,75 +0,0 @@ -export const DIALOG_CSS = ` -.bp-dialog { - width: min(var(--bp-width, 560px), calc(100vw - 32px)); - max-width: none; - max-height: min(86vh, 820px); - padding: 0; - overflow: hidden; - border: 1px solid var(--bp-border); - border-radius: 14px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 24px 60px -12px rgb(0 0 0 / 35%); - font-family: inherit; - font-size: 13px; - line-height: 1.5; -} - -.bp-dialog[open] { display: flex; flex-direction: column; animation: bp-dialog-in 160ms ease-out; } -.bp-dialog::backdrop { background: rgb(0 0 0 / 55%); backdrop-filter: blur(6px); animation: bp-fade-in 160ms ease-out; } -.bp-dialog *, .bp-dialog *::before, .bp-dialog *::after { box-sizing: border-box; } - -@keyframes bp-dialog-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } } -@keyframes bp-fade-in { from { opacity: 0; } to { opacity: 1; } } - -@media (prefers-reduced-motion: reduce) { - .bp-dialog[open], .bp-dialog::backdrop { animation: none; } -} - -.bp-dialog-header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 16px; - padding: 18px 20px 14px; - border-bottom: 1px solid var(--bp-border); -} - -.bp-dialog-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -.02em; } -.bp-dialog-description { margin: 3px 0 0; color: var(--bp-muted); font-size: 12px; } -.bp-dialog-body { flex: 1; min-height: 0; padding: 16px 20px; overflow-y: auto; overscroll-behavior: contain; } - -.bp-dialog-footer { - display: flex; - align-items: center; - justify-content: flex-end; - gap: 8px; - padding: 12px 20px; - border-top: 1px solid var(--bp-border); -} - -.bp-dialog-footer:empty { display: none; } - -.bp-icon-button { - display: inline-flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - width: 28px; - height: 28px; - border: 0; - border-radius: 7px; - background: transparent; - color: var(--bp-muted); - font: inherit; - font-size: 18px; - line-height: 1; - cursor: pointer; -} - -.bp-icon-button:hover { background: var(--bp-accent); color: var(--bp-fg); } - -@media (max-width: 520px) { - .bp-dialog-header, .bp-dialog-body, .bp-dialog-footer { padding-right: 14px; padding-left: 14px; } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/theme.ts b/ai/perplexity/src/ui/css/theme.ts deleted file mode 100644 index 2700e94..0000000 --- a/ai/perplexity/src/ui/css/theme.ts +++ /dev/null @@ -1,28 +0,0 @@ -export const THEME_CSS = ` -.bp-themed { - --bp-bg: hsl(0 0% 100%); - --bp-fg: hsl(240 10% 3.9%); - --bp-muted: hsl(240 3.8% 46.1%); - --bp-border: hsl(240 5.9% 90%); - --bp-accent: hsl(240 4.8% 95.9%); - --bp-track: hsl(240 5% 78%); - --bp-ring: hsl(240 5% 64.9%); - --bp-green: hsl(142 71% 40%); - --bp-yellow: hsl(38 92% 45%); - --bp-red: hsl(0 84% 55%); -} - -@media (prefers-color-scheme: dark) { - .bp-themed { - --bp-bg: hsl(240 10% 5%); - --bp-fg: hsl(0 0% 98%); - --bp-muted: hsl(240 5% 64.9%); - --bp-border: hsl(240 3.7% 17%); - --bp-accent: hsl(240 3.7% 13%); - --bp-track: hsl(240 3.7% 28%); - --bp-green: hsl(142 71% 45%); - --bp-yellow: hsl(38 92% 50%); - --bp-red: hsl(0 84% 60%); - } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/tooltip.ts b/ai/perplexity/src/ui/css/tooltip.ts deleted file mode 100644 index 7e96384..0000000 --- a/ai/perplexity/src/ui/css/tooltip.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const TOOLTIP_CSS = ` -.bp-tooltip { - position: fixed; - inset: auto; - width: max-content; - max-width: min(300px, calc(100vw - 16px)); - margin: 0; - padding: 0; - overflow: visible; - border: 1px solid var(--bp-border); - border-radius: 12px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 12px 32px rgb(0 0 0 / 22%); - font: inherit; - font-size: 12px; - line-height: 1.5; - pointer-events: none; -} - -.bp-tooltip:popover-open { animation: bp-tooltip-in 120ms ease-out; } -.bp-tooltip *, .bp-tooltip *::before, .bp-tooltip *::after { box-sizing: border-box; } -.bp-tooltip-body { padding: 12px 14px; } - -@keyframes bp-tooltip-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } } - -@media (prefers-reduced-motion: reduce) { - .bp-tooltip:popover-open { animation: none; } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/icons.ts b/ai/perplexity/src/ui/icons.ts deleted file mode 100644 index 7fa686a..0000000 --- a/ai/perplexity/src/ui/icons.ts +++ /dev/null @@ -1,33 +0,0 @@ -type Shape = readonly [tag: string, attributes: Readonly>] - -const ICONS = { - copy: [['rect', { x: '9', y: '9', width: '13', height: '13', rx: '2' }], ['path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }]], - check: [['polyline', { points: '20 6 9 17 4 12' }]], - download: [['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }], ['polyline', { points: '7 10 12 15 17 10' }], ['line', { x1: '12', y1: '15', x2: '12', y2: '3' }]], - wrap: [['line', { x1: '3', y1: '6', x2: '21', y2: '6' }], ['path', { d: 'M3 12h15a3 3 0 1 1 0 6h-4' }], ['polyline', { points: '16 16 14 18 16 20' }], ['line', { x1: '3', y1: '18', x2: '10', y2: '18' }]], - lines: [['line', { x1: '10', y1: '6', x2: '21', y2: '6' }], ['line', { x1: '10', y1: '12', x2: '21', y2: '12' }], ['line', { x1: '10', y1: '18', x2: '21', y2: '18' }], ['path', { d: 'M4 6h1v4' }], ['path', { d: 'M4 10h2' }], ['path', { d: 'M6 18H4c0-1 2-2 2-3s-1-1.5-2-1' }]], - fold: [['polyline', { points: '7 20 12 15 17 20' }], ['polyline', { points: '7 4 12 9 17 4' }]], - file: [['path', { d: 'M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z' }], ['polyline', { points: '14 2 14 8 20 8' }], ['line', { x1: '16', y1: '13', x2: '8', y2: '13' }], ['line', { x1: '16', y1: '17', x2: '8', y2: '17' }]], - sliders: [['line', { x1: '21', y1: '4', x2: '14', y2: '4' }], ['line', { x1: '10', y1: '4', x2: '3', y2: '4' }], ['line', { x1: '21', y1: '12', x2: '12', y2: '12' }], ['line', { x1: '8', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '21', y1: '20', x2: '16', y2: '20' }], ['line', { x1: '12', y1: '20', x2: '3', y2: '20' }], ['line', { x1: '14', y1: '2', x2: '14', y2: '6' }], ['line', { x1: '8', y1: '10', x2: '8', y2: '14' }], ['line', { x1: '16', y1: '18', x2: '16', y2: '22' }]], - book: [['path', { d: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20' }]], - layers: [['polygon', { points: '12 2 2 7 12 12 22 7 12 2' }], ['polyline', { points: '2 17 12 22 22 17' }], ['polyline', { points: '2 12 12 17 22 12' }]], - help: [['circle', { cx: '12', cy: '12', r: '10' }], ['path', { d: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3' }], ['line', { x1: '12', y1: '17', x2: '12.01', y2: '17' }]], - clock: [['circle', { cx: '12', cy: '12', r: '10' }], ['polyline', { points: '12 6 12 12 16 14' }]], - queue: [['line', { x1: '11', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '16', y1: '6', x2: '3', y2: '6' }], ['line', { x1: '16', y1: '18', x2: '3', y2: '18' }], ['line', { x1: '18', y1: '9', x2: '18', y2: '15' }], ['line', { x1: '21', y1: '12', x2: '15', y2: '12' }]], -} as const satisfies Record - -export type IconName = keyof typeof ICONS - -const NS = 'http://www.w3.org/2000/svg' - -export const createIcon = (name: IconName, size = 16): SVGSVGElement => { - const svg = document.createElementNS(NS, 'svg') - const attributes = { width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' } - for (const [key, value] of Object.entries(attributes)) svg.setAttribute(key, value) - for (const [tag, props] of ICONS[name] as readonly Shape[]) { - const element = document.createElementNS(NS, tag) - for (const [key, value] of Object.entries(props)) element.setAttribute(key, value) - svg.appendChild(element) - } - return svg -} diff --git a/ai/perplexity/src/ui/settings-dialog.ts b/ai/perplexity/src/ui/settings-dialog.ts deleted file mode 100644 index e0f7e1e..0000000 --- a/ai/perplexity/src/ui/settings-dialog.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { createElement, type Feature } from '@nolly/core' -import { createButton, createSection, createSwitch } from './controls' -import { createDialog } from './dialog' - -const DIALOG_ID = 'better-perplexity-settings-dialog' - -export const toggleSettingsDialog = (modules: readonly Feature[], onChange: () => void): void => { - const existing = document.getElementById(DIALOG_ID) - if (existing instanceof HTMLDialogElement) { - existing.close() - return - } - const ui = createDialog({ id: DIALOG_ID, title: 'Better Perplexity', description: `Version ${__VERSION__}`, width: 480 }) - const render = (): void => { - const sections = modules.map((module) => { - const section = createSection(module.name) - const stack = createElement('div', 'bp-stack') - const toggle = createSwitch({ - label: 'Enabled', - hint: module.description, - checked: module.enabled, - onChange: (checked) => { - module.enabled = checked - onChange() - } - }) - stack.appendChild(toggle.wrapper) - for (const entry of module.menuEntries()) { - stack.appendChild( - createButton(entry.label, { - onClick: () => { - entry.action() - render() - } - }) - ) - } - section.appendChild(stack) - return section - }) - ui.body.replaceChildren(...sections) - } - render() - ui.footer.append(createButton('Done', { primary: true, onClick: ui.close })) - ui.show() -} \ No newline at end of file diff --git a/ai/perplexity/src/ui/styles.ts b/ai/perplexity/src/ui/styles.ts deleted file mode 100644 index eaf1972..0000000 --- a/ai/perplexity/src/ui/styles.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { injectStyle } from '@nolly/core' -import { CONTROLS_CSS } from './css/controls' -import { DIALOG_CSS } from './css/dialog' -import { THEME_CSS } from './css/theme' -import { TOOLTIP_CSS } from './css/tooltip' - -export const ensureUiStyles = (): void => { - injectStyle('better-perplexity-ui-base', [THEME_CSS, DIALOG_CSS, CONTROLS_CSS, TOOLTIP_CSS].join('\n')) -} \ No newline at end of file diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index ac8eb42..c606160 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [Unreleased] + +- `repoUrls` accepts an optional `dir` for scripts that live in a nested folder. + ## 1.0.2 ### Added diff --git a/core/README.md b/core/README.md index 28483ea..5db9df4 100644 --- a/core/README.md +++ b/core/README.md @@ -12,8 +12,11 @@ Shared runtime, utilities and build tooling for every userscript in this reposit This is a library. It is bundled into each userscript and is not installed on its own. ## Quick start + ```sh bun scripts/new-userscript.ts my-script "My Script" ``` +Pass a third argument to create it inside a parent folder, for example `ai`. + Then read [Getting started](getting-started/) and the [API reference](api/). diff --git a/core/ai/CHANGELOG.md b/core/ai/CHANGELOG.md new file mode 100644 index 0000000..d1ed819 --- /dev/null +++ b/core/ai/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## [0.1.0] - 2026-11-10 + +- Initial release: adapter contract, composer kit, generation kit, response spy and SSE parser. +- Added placeholders, tokens, selection, clipboard, download, prompt sender and the UI kit (moved from Better Perplexity). +- Added Enter as Newline with configurable send shortcuts and file budget in diagnostics. diff --git a/core/ai/README.md b/core/ai/README.md new file mode 100644 index 0000000..e905ebb --- /dev/null +++ b/core/ai/README.md @@ -0,0 +1,20 @@ +# AI Core + +Platform-agnostic building blocks for AI-chat userscripts such as Better Perplexity and Better ChatGPT. It sits on top of `@nolly/core`. + +## What you get + +- A platform registry: `configureUi` and `configurePlatform` are called once at startup with the site's storage, logger, composer, generation detection, thread rule, prompt library URL, export source and release information. +- Composer and generation kits: find the input, write text, send, attach files, wait for an answer. +- A streaming response observer and an incremental Server-Sent Events parser. +- A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. +- Features that need only the registry: Enter as Newline, Draft Guard, Message Splitter, Prompt Library, Command Palette, Message Queue, Recall, Batch Runner, Selection Toolbar, Max Width, Code Block Pro, Exporter and Update Checker. + +This is a library. It is bundled into each userscript and is not installed on its own. + +## Adding a platform + +1. Create `ai/` with `bun scripts/new-userscript.ts "" ai`. +2. Write the site's locators and a composer adapter. +3. Call `configureUi` and `configurePlatform`, then register the features you want. +4. Provide an export source if you want the exporter, and a `codeBlockRoot` hook if you want Code Block Pro. diff --git a/core/ai/package.json b/core/ai/package.json index 529dcb0..95111e9 100644 --- a/core/ai/package.json +++ b/core/ai/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", - "userscript": { "kind": "library" }, + "userscript": { "kind": "library", "slug": "core-ai" }, "repository": { "type": "git", "url": "git+https://github.com/thenolle/userscripts.git", diff --git a/core/ai/src/adapter.ts b/core/ai/src/adapter.ts index 546eb0d..7a6131d 100644 --- a/core/ai/src/adapter.ts +++ b/core/ai/src/adapter.ts @@ -10,7 +10,6 @@ export interface ComposerAdapter { readonly rejectEditable?: (element: HTMLElement) => boolean readonly findSendButton?: (editable: HTMLElement) => HTMLElement | null readonly findStopButton?: () => HTMLElement | null - readonly findFileInput?: () => HTMLInputElement | null readonly sendWith?: 'enter' | 'button' } diff --git a/ai/perplexity/src/core/automation.ts b/core/ai/src/automation.ts similarity index 99% rename from ai/perplexity/src/core/automation.ts rename to core/ai/src/automation.ts index 498e6b7..8f7dfaa 100644 --- a/ai/perplexity/src/core/automation.ts +++ b/core/ai/src/automation.ts @@ -9,4 +9,4 @@ export const automate = async (task: () => Promise): Promise => { } finally { depth-- } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/core/clipboard.ts b/core/ai/src/clipboard.ts similarity index 99% rename from ai/perplexity/src/core/clipboard.ts rename to core/ai/src/clipboard.ts index f6942f6..3af8260 100644 --- a/ai/perplexity/src/core/clipboard.ts +++ b/core/ai/src/clipboard.ts @@ -12,4 +12,4 @@ export const copyText = async (text: string): Promise => { area.remove() return copied } -} \ No newline at end of file +} diff --git a/core/ai/src/composer.ts b/core/ai/src/composer.ts index 7fe2198..9768f94 100644 --- a/core/ai/src/composer.ts +++ b/core/ai/src/composer.ts @@ -1,6 +1,6 @@ import { sleep, toElement } from '@nolly/core' import type { ComposerAdapter } from './adapter' -import { dispatchEnter, findGenericSendButton } from './keys' +import { dispatchEnter, findSendButton } from './keys' export const EDITABLE_SELECTOR = [ 'textarea', @@ -111,7 +111,6 @@ const waitForComposer = async (editable: HTMLElement, text: string, timeout = 30 export interface ComposerKit { editableFrom(target: EventTarget | null): HTMLElement | null findComposer(): HTMLElement | null - findSend(editable: HTMLElement): HTMLElement | null writeComposer(editable: HTMLElement, text: string): Promise sendComposer(editable: HTMLElement): Promise attachFile(editable: HTMLElement, file: File): boolean @@ -138,7 +137,7 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { return candidates.at(-1) ?? null } - const findSend = (editable: HTMLElement): HTMLElement | null => (adapter.findSendButton ? adapter.findSendButton(editable) : findGenericSendButton(editable)) + const findSend = (editable: HTMLElement): HTMLElement | null => (adapter.findSendButton ? adapter.findSendButton(editable) : findSendButton(editable)) const writeComposer = async (editable: HTMLElement, text: string): Promise => { if (!editable.isConnected) return false @@ -182,7 +181,7 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { const attachFile = (editable: HTMLElement, file: File): boolean => { const transfer = new DataTransfer() transfer.items.add(file) - const input = adapter.findFileInput?.() ?? [...document.querySelectorAll('input[type="file"]')].find((candidate) => !isOwnUi(candidate) && !candidate.disabled) + const input = [...document.querySelectorAll('input[type="file"]')].find((candidate) => !isOwnUi(candidate) && !candidate.disabled) if (input) { input.files = transfer.files input.dispatchEvent(new Event('change', { bubbles: true, composed: true })) @@ -193,5 +192,5 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { return event.defaultPrevented } - return { editableFrom, findComposer, findSend, writeComposer, sendComposer, attachFile } + return { editableFrom, findComposer, writeComposer, sendComposer, attachFile } } diff --git a/ai/perplexity/src/core/download.ts b/core/ai/src/download.ts similarity index 99% rename from ai/perplexity/src/core/download.ts rename to core/ai/src/download.ts index ef0aa17..e36cd39 100644 --- a/ai/perplexity/src/core/download.ts +++ b/core/ai/src/download.ts @@ -5,4 +5,4 @@ export const saveFile = (name: string, data: BlobPart, type = 'text/plain'): voi link.download = name link.click() URL.revokeObjectURL(url) -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/batch-runner/dialog.ts b/core/ai/src/features/batch-runner/dialog.ts similarity index 94% rename from ai/perplexity/src/modules/batch-runner/dialog.ts rename to core/ai/src/features/batch-runner/dialog.ts index 32858fb..b7c0e51 100644 --- a/ai/perplexity/src/modules/batch-runner/dialog.ts +++ b/core/ai/src/features/batch-runner/dialog.ts @@ -2,8 +2,9 @@ import { createElement } from '@nolly/core' import { createButton, createNumberField, createSwitch, createTextArea } from '../../ui/controls' import { createDialog } from '../../ui/dialog' import { parseItems, renderTemplate } from './template' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-batch-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-batch-dialog` const MAX_ITEMS = 200 const PREVIEWS = 3 @@ -36,8 +37,8 @@ const section = (step: number, title: string, help: string, tour: string): { roo } export const openBatchDialog = (onStart: (input: BatchInput) => void): void => { - if (document.getElementById(DIALOG_ID)) return - const ui = createDialog({ id: DIALOG_ID, title: 'Batch Runner', description: 'Send the same kind of message many times, one after another, in this conversation.', width: 700 }) + if (document.getElementById(DIALOG_ID())) return + const ui = createDialog({ id: DIALOG_ID(), title: 'Batch Runner', description: 'Send the same kind of message many times, one after another, in this conversation.', width: 700 }) let template = '' let items = '' let delay = 2 diff --git a/ai/perplexity/src/modules/batch-runner/index.ts b/core/ai/src/features/batch-runner/index.ts similarity index 95% rename from ai/perplexity/src/modules/batch-runner/index.ts rename to core/ai/src/features/batch-runner/index.ts index 5e562e1..da75c25 100644 --- a/ai/perplexity/src/modules/batch-runner/index.ts +++ b/core/ai/src/features/batch-runner/index.ts @@ -1,13 +1,13 @@ import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { ComposerButton } from '../../ui/composer-button' -import { applyValues, findFields } from '../../core/placeholders' +import { applyValues, findFields } from '../../placeholders' import { askFields } from '../../ui/placeholder-dialog' import { openBatchDialog, type BatchInput } from './dialog' import { renderTemplate } from './template' import { BatchPanel } from './panel' import { BatchRunner, clearState, loadState, type BatchState } from './runner' -export class BatchRunnerModule extends Feature { +export class BatchRunnerFeature extends Feature { readonly id = 'batch-runner' readonly name = 'Batch Runner' readonly description = 'Send one templated message per item, one after another.' diff --git a/ai/perplexity/src/modules/batch-runner/panel.ts b/core/ai/src/features/batch-runner/panel.ts similarity index 94% rename from ai/perplexity/src/modules/batch-runner/panel.ts rename to core/ai/src/features/batch-runner/panel.ts index 90f7871..863ec1d 100644 --- a/ai/perplexity/src/modules/batch-runner/panel.ts +++ b/core/ai/src/features/batch-runner/panel.ts @@ -1,10 +1,10 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' +import { markUi, uiConfig } from '../../ui/config' import { createButton } from '../../ui/controls' import { ensureUiStyles } from '../../ui/styles' import type { BatchPhase, BatchResult } from './runner' -const CSS_ID = 'better-perplexity-batch-styles' +const CSS_ID = (): string => `${uiConfig().id}-batch-styles` const PHASE_TEXT: Readonly> = { sending: 'sending', waiting: 'waiting for the answer', paused: 'paused', resting: 'resting' } @@ -16,9 +16,9 @@ export class BatchPanel { constructor() { ensureUiStyles() - if (!document.getElementById(CSS_ID)) { + if (!document.getElementById(CSS_ID())) { const style = createElement('style') - style.id = CSS_ID + style.id = CSS_ID() style.textContent = ` .bp-batch-panel { position: fixed; right: 20px; bottom: 20px; z-index: 100000; display: flex; flex-direction: column; gap: 8px; width: 300px; padding: 12px 14px; border: 1px solid var(--bp-border); border-radius: 12px; background: var(--bp-bg); color: var(--bp-fg); box-shadow: 0 12px 32px rgb(0 0 0 / 22%); font-size: 12px; } .bp-batch-actions { display: flex; gap: 6px; flex-wrap: wrap; } diff --git a/ai/perplexity/src/modules/batch-runner/runner.ts b/core/ai/src/features/batch-runner/runner.ts similarity index 73% rename from ai/perplexity/src/modules/batch-runner/runner.ts rename to core/ai/src/features/batch-runner/runner.ts index a8ac846..0bba29c 100644 --- a/ai/perplexity/src/modules/batch-runner/runner.ts +++ b/core/ai/src/features/batch-runner/runner.ts @@ -1,9 +1,6 @@ -import { automate } from '../../core/automation' -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' -import { waitForResponse } from '../../core/generation' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { isAbort, sleep, waitFor } from '@nolly/core' +import { isAbort, sleep } from '@nolly/core' +import { automate } from '../../automation' +import { logger, sendPrompt, storage, waitForResponse } from '../../platform' export interface BatchState { prompts: string[] @@ -70,7 +67,7 @@ export class BatchRunner { } signal.throwIfAborted() onProgress(index, total, 'sending') - if (!(await this.send(state.prompts[index]!, signal))) return 'failed' + if (!(await sendPrompt(state.prompts[index]!, signal))) return 'failed' onProgress(index, total, 'waiting') await waitForResponse({ signal }) storage.set(STORAGE_KEY, { ...state, next: index + 1, at: Date.now() }) @@ -91,15 +88,4 @@ export class BatchRunner { this.paused = false } } - - private async send(prompt: string, signal: AbortSignal): Promise { - for (let attempt = 0; attempt < 2; attempt++) { - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) - if (!composer) return false - if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true - if (readComposer(composer).trim() === '') return true - await sleep(1_500, signal) - } - return false - } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/batch-runner/template.ts b/core/ai/src/features/batch-runner/template.ts similarity index 100% rename from ai/perplexity/src/modules/batch-runner/template.ts rename to core/ai/src/features/batch-runner/template.ts diff --git a/ai/perplexity/src/modules/code-blocks/badges.ts b/core/ai/src/features/code-blocks/badges.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/badges.ts rename to core/ai/src/features/code-blocks/badges.ts diff --git a/ai/perplexity/src/modules/code-blocks/block.ts b/core/ai/src/features/code-blocks/block.ts similarity index 98% rename from ai/perplexity/src/modules/code-blocks/block.ts rename to core/ai/src/features/code-blocks/block.ts index b6e515a..1c32602 100644 --- a/ai/perplexity/src/modules/code-blocks/block.ts +++ b/core/ai/src/features/code-blocks/block.ts @@ -1,7 +1,7 @@ -import { copyText } from '../../core/clipboard' -import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' +import { copyText } from '../../clipboard' import { createIcon, type IconName } from '../../ui/icons' +import { createElement } from '@nolly/core' +import { markUi } from '../../ui/config' import type { BlockInfo } from './detect' import { highlightLines } from './highlight' import { languageInfo } from './languages' diff --git a/ai/perplexity/src/modules/code-blocks/detect.ts b/core/ai/src/features/code-blocks/detect.ts similarity index 96% rename from ai/perplexity/src/modules/code-blocks/detect.ts rename to core/ai/src/features/code-blocks/detect.ts index 1fd3946..f56f084 100644 --- a/ai/perplexity/src/modules/code-blocks/detect.ts +++ b/core/ai/src/features/code-blocks/detect.ts @@ -1,3 +1,4 @@ +import { platform } from '../../platform' import { guessLanguage } from './guess' import { isKnownLanguage, languageForFilename, normalizeLanguage } from './languages' @@ -46,6 +47,8 @@ export const detectLanguage = (pre: HTMLElement, root: HTMLElement, text: string export const findBlockRoot = (pre: HTMLElement, includeChrome: boolean): HTMLElement => { if (!includeChrome) return pre + const custom = platform().codeBlockRoot?.(pre) + if (custom) return custom const codeLength = (pre.textContent ?? '').length let root = pre for (let depth = 0; depth < 3; depth++) { @@ -60,4 +63,4 @@ export const findBlockRoot = (pre: HTMLElement, includeChrome: boolean): HTMLEle export const analyze = (pre: HTMLElement, root: HTMLElement, text: string): BlockInfo => { const filename = guessFilename(text, root, pre) return { language: detectLanguage(pre, root, text, filename), filename, text } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/code-blocks/dialog.ts b/core/ai/src/features/code-blocks/dialog.ts similarity index 85% rename from ai/perplexity/src/modules/code-blocks/dialog.ts rename to core/ai/src/features/code-blocks/dialog.ts index c128f9a..0821ca3 100644 --- a/ai/perplexity/src/modules/code-blocks/dialog.ts +++ b/core/ai/src/features/code-blocks/dialog.ts @@ -2,16 +2,17 @@ import { createElement } from '@nolly/core' import { createButton, createNumberField, createSelectField, createSwitch } from '../../ui/controls' import { createDialog } from '../../ui/dialog' import { DEFAULT_CODE_SETTINGS, type CodeBlockSettings } from './settings' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-code-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-code-dialog` export const toggleCodeSettingsDialog = (current: CodeBlockSettings, onSave: (settings: CodeBlockSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Code Block Pro', description: 'Applies to code blocks as soon as an answer finishes.', width: 460 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Code Block Pro', description: 'Applies to code blocks as soon as an answer finishes.', width: 460 }) const draft: CodeBlockSettings = { ...current } const stack = createElement('div', 'bp-stack') stack.append( diff --git a/ai/perplexity/src/modules/code-blocks/guess.ts b/core/ai/src/features/code-blocks/guess.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/guess.ts rename to core/ai/src/features/code-blocks/guess.ts diff --git a/ai/perplexity/src/modules/code-blocks/highlight.ts b/core/ai/src/features/code-blocks/highlight.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/highlight.ts rename to core/ai/src/features/code-blocks/highlight.ts diff --git a/ai/perplexity/src/modules/code-blocks/index.ts b/core/ai/src/features/code-blocks/index.ts similarity index 93% rename from ai/perplexity/src/modules/code-blocks/index.ts rename to core/ai/src/features/code-blocks/index.ts index 6e3546a..72318d0 100644 --- a/ai/perplexity/src/modules/code-blocks/index.ts +++ b/core/ai/src/features/code-blocks/index.ts @@ -1,8 +1,7 @@ -import { copyText } from '../../core/clipboard' +import { copyText } from '../../clipboard' import { Feature, type MenuEntry } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { isGenerating } from '../../core/generation' -import { logger } from '../../core/logger' +import { isOwnUi } from '../../ui/config' +import { isGenerating, logger } from '../../platform' import { EnhancedBlock } from './block' import { toggleCodeSettingsDialog } from './dialog' import { analyze, findBlockRoot, readCode } from './detect' @@ -12,7 +11,7 @@ const STABLE_MS = 900 const FORCE_MS = 6_000 const RESCAN_MS = 500 -export class CodeBlocksModule extends Feature { +export class CodeBlocksFeature extends Feature { readonly id = 'code-blocks' readonly name = 'Code Block Pro' readonly description = 'Replaces code blocks with copy, wrap, line numbers, folding and download.' diff --git a/ai/perplexity/src/modules/code-blocks/languages.ts b/core/ai/src/features/code-blocks/languages.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/languages.ts rename to core/ai/src/features/code-blocks/languages.ts diff --git a/ai/perplexity/src/modules/code-blocks/lines.ts b/core/ai/src/features/code-blocks/lines.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/lines.ts rename to core/ai/src/features/code-blocks/lines.ts diff --git a/ai/perplexity/src/modules/code-blocks/settings.ts b/core/ai/src/features/code-blocks/settings.ts similarity index 93% rename from ai/perplexity/src/modules/code-blocks/settings.ts rename to core/ai/src/features/code-blocks/settings.ts index 5663b15..57a0d19 100644 --- a/ai/perplexity/src/modules/code-blocks/settings.ts +++ b/core/ai/src/features/code-blocks/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface CodeBlockSettings { collapseAfter: number diff --git a/ai/perplexity/src/modules/code-blocks/styles.ts b/core/ai/src/features/code-blocks/styles.ts similarity index 97% rename from ai/perplexity/src/modules/code-blocks/styles.ts rename to core/ai/src/features/code-blocks/styles.ts index fd2ff4e..9510f61 100644 --- a/ai/perplexity/src/modules/code-blocks/styles.ts +++ b/core/ai/src/features/code-blocks/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-code { @@ -142,4 +143,4 @@ const CSS = ` .bp-lang-plain { color: var(--bp-muted); } ` -export const ensureCodeStyles = (): void => injectStyle('better-perplexity-code-styles', CSS) \ No newline at end of file +export const ensureCodeStyles = (): void => injectStyle(`${uiConfig().id}-code-styles`, CSS) \ No newline at end of file diff --git a/ai/perplexity/src/modules/command-palette/dialog.ts b/core/ai/src/features/command-palette/dialog.ts similarity index 85% rename from ai/perplexity/src/modules/command-palette/dialog.ts rename to core/ai/src/features/command-palette/dialog.ts index a3c73f8..5fba0ea 100644 --- a/ai/perplexity/src/modules/command-palette/dialog.ts +++ b/core/ai/src/features/command-palette/dialog.ts @@ -3,17 +3,18 @@ import { createButton } from '../../ui/controls' import { createDialog } from '../../ui/dialog' import { DEFAULT_SHORTCUT, formatShortcut, shortcutFromEvent, type Shortcut } from './shortcut' import { ensurePaletteStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-shortcut-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-shortcut-dialog` export const toggleShortcutDialog = (current: Shortcut, onSave: (shortcut: Shortcut) => void, title = 'Palette shortcut', defaults: Shortcut = DEFAULT_SHORTCUT): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title, description: 'Use at least one of Ctrl, Alt or Meta.', width: 420 }) + const ui = createDialog({ id: DIALOG_ID(), title, description: 'Use at least one of Ctrl, Alt or Meta.', width: 420 }) let draft: Shortcut = { ...current } let recording = false const box = createElement('div', 'bp-shortcut-box', formatShortcut(draft)) diff --git a/ai/perplexity/src/modules/command-palette/fuzzy.ts b/core/ai/src/features/command-palette/fuzzy.ts similarity index 100% rename from ai/perplexity/src/modules/command-palette/fuzzy.ts rename to core/ai/src/features/command-palette/fuzzy.ts diff --git a/ai/perplexity/src/modules/command-palette/index.ts b/core/ai/src/features/command-palette/index.ts similarity index 93% rename from ai/perplexity/src/modules/command-palette/index.ts rename to core/ai/src/features/command-palette/index.ts index afa8502..2d4ecf3 100644 --- a/ai/perplexity/src/modules/command-palette/index.ts +++ b/core/ai/src/features/command-palette/index.ts @@ -1,11 +1,11 @@ -import { findComposer, writeComposer } from '../../core/composer' -import { copyText } from '../../core/clipboard' +import { findComposer, writeComposer } from '../../platform' +import { copyText } from '../../clipboard' import { Feature, type FeatureCommand, type MenuEntry } from '@nolly/core' import { toggleShortcutDialog } from './dialog' import { togglePalette } from './palette' import { loadShortcut, matchesShortcut, saveShortcut, type Shortcut } from './shortcut' -export class CommandPaletteModule extends Feature { +export class CommandPaletteFeature extends Feature { readonly id = 'command-palette' readonly name = 'Command Palette' readonly description = 'Search and run any action with a keyboard shortcut.' diff --git a/ai/perplexity/src/modules/command-palette/palette.ts b/core/ai/src/features/command-palette/palette.ts similarity index 92% rename from ai/perplexity/src/modules/command-palette/palette.ts rename to core/ai/src/features/command-palette/palette.ts index 8a81ea4..cfd549d 100644 --- a/ai/perplexity/src/modules/command-palette/palette.ts +++ b/core/ai/src/features/command-palette/palette.ts @@ -1,10 +1,11 @@ import { type Command, createElement } from '@nolly/core' -import { storage } from '../../core/storage' +import { storage } from '../../platform' import { createDialog } from '../../ui/dialog' import { fuzzyScore } from './fuzzy' import { ensurePaletteStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-palette' +const DIALOG_ID = (): string => `${uiConfig().id}-palette` const RECENT_KEY = 'command-palette:recent' const MAX_RECENT = 6 const MAX_RESULTS = 60 @@ -21,13 +22,13 @@ const rank = (commands: readonly Command[], query: string, recent: readonly stri } export const togglePalette = (getCommands: () => Command[]): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Command palette', width: 560 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Command palette', width: 560 }) ui.dialog.classList.add('bp-palette') const commands = getCommands() const input = createElement('input', 'bp-palette-input') diff --git a/ai/perplexity/src/modules/command-palette/shortcut.ts b/core/ai/src/features/command-palette/shortcut.ts similarity index 96% rename from ai/perplexity/src/modules/command-palette/shortcut.ts rename to core/ai/src/features/command-palette/shortcut.ts index 3a42ee4..fa16e6d 100644 --- a/ai/perplexity/src/modules/command-palette/shortcut.ts +++ b/core/ai/src/features/command-palette/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface Shortcut { ctrl: boolean diff --git a/ai/perplexity/src/modules/command-palette/styles.ts b/core/ai/src/features/command-palette/styles.ts similarity index 88% rename from ai/perplexity/src/modules/command-palette/styles.ts rename to core/ai/src/features/command-palette/styles.ts index ba8c809..b28efe6 100644 --- a/ai/perplexity/src/modules/command-palette/styles.ts +++ b/core/ai/src/features/command-palette/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-palette { max-height: min(70vh, 480px); } @@ -36,4 +37,4 @@ const CSS = ` .bp-shortcut-box { padding: 14px; border: 1px dashed var(--bp-border); border-radius: 10px; font-size: 15px; font-weight: 600; text-align: center; } ` -export const ensurePaletteStyles = (): void => injectStyle('better-perplexity-palette-styles', CSS) \ No newline at end of file +export const ensurePaletteStyles = (): void => injectStyle(`${uiConfig().id}-palette-styles`, CSS) \ No newline at end of file diff --git a/core/ai/src/features/draft-guard/feature.ts b/core/ai/src/features/draft-guard/feature.ts new file mode 100644 index 0000000..cbe254e --- /dev/null +++ b/core/ai/src/features/draft-guard/feature.ts @@ -0,0 +1,216 @@ +import { Feature, toElement } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import type { ComposerKit } from '../../composer' +import { isSendButton, readComposer } from '../../composer' +import { DraftOverlay } from './overlay' +import { DraftStore } from './store' +import type { Draft } from './store' + +const SAVE_DELAY = 400 +const SEND_WINDOW = 3_000 +const GUARD_KEY = 'draft-guard:warn-on-close' +const DEFAULT_SPLIT_COMMAND = 'message-splitter:split' + +const defaultThreadKey = (): string => location.pathname || '/' +const meaningful = (text: string): boolean => text.replace(/[\s\u200b]/g, '') !== '' + +export interface DraftGuardOptions { + readonly storage: ScriptStorage + readonly composer: Pick + readonly onSend: (listener: () => void) => () => void + readonly tokenLimit: () => number + readonly threadKey?: () => string + readonly splitCommand?: string +} + +export class DraftGuardFeature extends Feature { + readonly id = 'draft-guard' + readonly name = 'Draft Guard' + readonly description = 'Autosaves drafts, shows a size meter and warns about unsent text.' + + private readonly store: DraftStore + private readonly overlay = new DraftOverlay() + private readonly wired = new WeakSet() + private readonly dismissed = new Set() + private readonly typed = new Set() + private readonly offered = new Map() + private key: string + private lastText = '' + private saveTimer = 0 + private sendIntentAt = 0 + private guardAttached = false + private composer: HTMLElement | null = null + + constructor(context: ScriptContext, private readonly options: DraftGuardOptions) { + super(context) + this.store = new DraftStore(options.storage) + this.key = this.threadKey() + this.overlay.onSplit(() => this.context.runCommand(options.splitCommand ?? DEFAULT_SPLIT_COMMAND)) + options.onSend(() => { + if (this.enabled && meaningful(this.lastText)) this.discard(this.key) + }) + document.addEventListener('click', this.handleClick, true) + document.addEventListener('keydown', this.handleKeydown, true) + window.addEventListener('scroll', this.reposition, true) + window.addEventListener('resize', this.reposition) + } + + get warnOnClose(): boolean { + return this.options.storage.get(GUARD_KEY, true) + } + + set warnOnClose(value: boolean) { + this.options.storage.set(GUARD_KEY, value) + } + + run(): void { + if (!this.enabled) { + this.teardown() + return + } + this.syncGuard() + const composer = this.options.composer.findComposer() + this.composer = composer + if (!composer) { + this.overlay.hideAll() + return + } + this.wire(composer) + this.syncThread() + const text = readComposer(composer) + if (text !== this.lastText) this.handleChange(text) + this.refreshOverlay(composer, text) + } + + override menuEntries(): MenuEntry[] { + return [{ id: 'guard', label: `${this.warnOnClose ? 'Disable' : 'Enable'} Unsent-Text Warning`, action: () => this.toggleGuard() }] + } + + private threadKey(): string { + return (this.options.threadKey ?? defaultThreadKey)() + } + + private wire(composer: HTMLElement): void { + if (this.wired.has(composer)) return + this.wired.add(composer) + composer.addEventListener('input', (event) => { + if (event.isTrusted) this.typed.add(this.key) + this.run() + }) + } + + private syncThread(): void { + const key = this.threadKey() + if (key === this.key) return + window.clearTimeout(this.saveTimer) + this.key = key + this.lastText = '' + } + + private handleChange(text: string): void { + const previous = this.lastText + this.lastText = text + window.clearTimeout(this.saveTimer) + if (!meaningful(text)) { + if (meaningful(previous) && Date.now() - this.sendIntentAt < SEND_WINDOW) this.discard(this.key) + return + } + const key = this.key + this.saveTimer = window.setTimeout(() => this.store.set(key, text), SAVE_DELAY) + } + + private discard(key: string): void { + window.clearTimeout(this.saveTimer) + this.store.remove(key) + this.offered.delete(key) + this.dismissed.add(key) + this.overlay.hideBanner() + } + + private refreshOverlay(composer: HTMLElement, text: string): void { + if (meaningful(text)) this.overlay.showMeter(composer, text, this.options.tokenLimit()) + else this.overlay.hideMeter() + const key = this.key + if (this.dismissed.has(key) || this.typed.has(key)) { + this.offered.delete(key) + this.overlay.hideBanner() + return + } + const draft = this.offered.get(key) ?? this.store.get(key) + if (!draft) { + this.overlay.hideBanner() + return + } + this.offered.set(key, draft) + this.overlay.showBanner( + composer, + draft, + () => { + this.offered.delete(key) + this.dismissed.add(key) + this.overlay.hideBanner() + void this.options.composer.writeComposer(composer, draft.text) + }, + () => this.discard(key) + ) + } + + private isComposerControl(button: HTMLElement): boolean { + const composer = this.composer + if (!composer) return false + const form = composer.closest('form') + if (form) return form.contains(button) + let scope: HTMLElement | null = composer + for (let depth = 0; scope && depth < 4; depth++) { + if (scope.contains(button)) return true + scope = scope.parentElement + } + return false + } + + private readonly handleClick = (event: MouseEvent): void => { + const button = toElement(event.target)?.closest('button') + if (!this.enabled || !button || !isSendButton(button) || !this.isComposerControl(button)) return + this.sendIntentAt = Date.now() + this.dismissed.add(this.key) + this.offered.delete(this.key) + this.overlay.hideBanner() + } + + private readonly handleKeydown = (event: KeyboardEvent): void => { + if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && meaningful(this.lastText)) this.sendIntentAt = Date.now() + } + + private readonly reposition = (): void => { + if (this.composer?.isConnected) this.overlay.position(this.composer) + } + + private readonly handleBeforeUnload = (event: BeforeUnloadEvent): void => { + const composer = this.composer ?? this.options.composer.findComposer() + if (!composer || !meaningful(readComposer(composer))) return + event.preventDefault() + event.returnValue = '' + } + + private syncGuard(): void { + if (this.warnOnClose && !this.guardAttached) { + window.addEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = true + } else if (!this.warnOnClose && this.guardAttached) { + window.removeEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = false + } + } + + private toggleGuard(): void { + this.warnOnClose = !this.warnOnClose + this.context.refreshMenu() + this.context.requestUpdate() + } + + private teardown(): void { + this.overlay.hideAll() + if (this.guardAttached) window.removeEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = false + } +} diff --git a/core/ai/src/features/draft-guard/index.ts b/core/ai/src/features/draft-guard/index.ts new file mode 100644 index 0000000..c7b92f5 --- /dev/null +++ b/core/ai/src/features/draft-guard/index.ts @@ -0,0 +1,2 @@ +export { DraftGuardFeature } from './feature' +export type { DraftGuardOptions } from './feature' diff --git a/ai/perplexity/src/modules/draft-guard/overlay.ts b/core/ai/src/features/draft-guard/overlay.ts similarity index 97% rename from ai/perplexity/src/modules/draft-guard/overlay.ts rename to core/ai/src/features/draft-guard/overlay.ts index 75403b7..a1ffc60 100644 --- a/ai/perplexity/src/modules/draft-guard/overlay.ts +++ b/core/ai/src/features/draft-guard/overlay.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '../../tokens' +import { markUi } from '../../ui/config' import { ensureUiStyles } from '../../ui/styles' import type { Draft } from './store' import { ensureDraftStyles } from './styles' @@ -87,4 +87,4 @@ export class DraftOverlay { private mount(element: HTMLElement): void { if (!element.isConnected) document.body.appendChild(element) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/draft-guard/store.ts b/core/ai/src/features/draft-guard/store.ts similarity index 83% rename from ai/perplexity/src/modules/draft-guard/store.ts rename to core/ai/src/features/draft-guard/store.ts index 6d3c961..c2add94 100644 --- a/ai/perplexity/src/modules/draft-guard/store.ts +++ b/core/ai/src/features/draft-guard/store.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import type { ScriptStorage } from '@nolly/core' export interface Draft { text: string @@ -13,6 +13,8 @@ const MAX_DRAFTS = 50 const MAX_CHARS = 200_000 export class DraftStore { + constructor(private readonly storage: ScriptStorage) {} + get(key: string): Draft | null { const draft = this.read()[key] return draft && Date.now() - draft.at < TTL ? draft : null @@ -33,11 +35,11 @@ export class DraftStore { } private read(): Drafts { - return storage.get(STORAGE_KEY, {}) + return this.storage.get(STORAGE_KEY, {}) } private write(drafts: Drafts): void { - storage.set(STORAGE_KEY, drafts) + this.storage.set(STORAGE_KEY, drafts) } private prune(drafts: Drafts): Drafts { @@ -45,4 +47,4 @@ export class DraftStore { live.sort((a, b) => b[1].at - a[1].at) return Object.fromEntries(live.slice(0, MAX_DRAFTS)) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/draft-guard/styles.ts b/core/ai/src/features/draft-guard/styles.ts similarity index 88% rename from ai/perplexity/src/modules/draft-guard/styles.ts rename to core/ai/src/features/draft-guard/styles.ts index 33e119c..457e3db 100644 --- a/ai/perplexity/src/modules/draft-guard/styles.ts +++ b/core/ai/src/features/draft-guard/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-draft-meter, @@ -39,4 +40,4 @@ const CSS = ` .bp-draft-meter button[hidden] { display: none; } ` -export const ensureDraftStyles = (): void => injectStyle('better-perplexity-draft-styles', CSS) \ No newline at end of file +export const ensureDraftStyles = (): void => injectStyle(`${uiConfig().id}-draft-styles`, CSS) diff --git a/core/ai/src/features/enter-as-newline/config-button.ts b/core/ai/src/features/enter-as-newline/config-button.ts new file mode 100644 index 0000000..2c1609e --- /dev/null +++ b/core/ai/src/features/enter-as-newline/config-button.ts @@ -0,0 +1,76 @@ +import { createElement, injectStyle } from '@nolly/core' +import { markUi, uiConfig } from '../../ui/config' +import { ensureUiStyles } from '../../ui/styles' +import { Tooltip } from '../../ui/tooltip' + +const SVG_NS = 'http://www.w3.org/2000/svg' + +const CSS = ` +.bp-config-button { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + cursor: pointer; +} + +.bp-config-button svg { pointer-events: none; } +` + +const createIcon = (): SVGSVGElement => { + const svg = document.createElementNS(SVG_NS, 'svg') + for (const [name, value] of Object.entries({ width: '16', height: '16', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(name, value) + const arrow = document.createElementNS(SVG_NS, 'polyline') + arrow.setAttribute('points', '9 10 4 15 9 20') + const line = document.createElementNS(SVG_NS, 'path') + line.setAttribute('d', 'M20 4v7a4 4 0 0 1-4 4H4') + svg.append(arrow, line) + return svg +} + +export class ConfigButton { + readonly element = markUi(createElement('button', 'bp-config-button')) + private readonly tooltip: Tooltip + private appliedClass = '' + + constructor(onClick: () => void, describe: () => string) { + ensureUiStyles() + injectStyle(`${uiConfig().id}-enter-styles`, CSS) + this.element.type = 'button' + this.element.setAttribute('aria-label', 'Configure Enter as Newline') + this.element.appendChild(createIcon()) + this.element.addEventListener('click', (event) => { + event.preventDefault() + event.stopPropagation() + onClick() + }) + this.tooltip = new Tooltip(this.element, (container) => { + container.append(createElement('div', 'bp-tip-mode', 'Enter as Newline'), createElement('div', 'bp-tip-sub', describe()), createElement('div', 'bp-tip-foot', 'Click to configure')) + }) + } + + mount(): void { + const { first, submit } = uiConfig().composerActions?.() ?? { first: null, submit: null } + if (!first && !submit) { + this.unmount() + return + } + if (first) this.syncClass(first) + const placed = first ? first.nextElementSibling === this.element : submit?.previousElementSibling === this.element + if (placed) return + if (first) first.insertAdjacentElement('afterend', this.element) + else submit?.insertAdjacentElement('beforebegin', this.element) + } + + unmount(): void { + this.tooltip.hide() + this.element.remove() + } + + private syncClass(reference: HTMLElement): void { + const next = `${reference.className} bp-config-button` + if (next === this.appliedClass) return + this.element.className = next + this.appliedClass = next + } +} diff --git a/ai/perplexity/src/modules/enter-as-newline/dialog.ts b/core/ai/src/features/enter-as-newline/dialog.ts similarity index 71% rename from ai/perplexity/src/modules/enter-as-newline/dialog.ts rename to core/ai/src/features/enter-as-newline/dialog.ts index 0e3a939..41aa62b 100644 --- a/ai/perplexity/src/modules/enter-as-newline/dialog.ts +++ b/core/ai/src/features/enter-as-newline/dialog.ts @@ -1,18 +1,19 @@ import { createElement } from '@nolly/core' -import { logger } from '../../core/logger' +import type { Logger } from '@nolly/core' import { createButton, createSwitch } from '../../ui/controls' +import { uiConfig } from '../../ui/config' import { createDialog } from '../../ui/dialog' -import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts, type Modifier, type ShortcutSettings } from './shortcuts' +import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts } from './shortcuts' +import type { Modifier, ShortcutSettings } from './shortcuts' -const DIALOG_ID = 'better-perplexity-enter-dialog' - -export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settings: ShortcutSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) +export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settings: ShortcutSettings) => void, logger: Logger): void => { + const dialogId = `${uiConfig().id}-enter-dialog` + const existing = document.getElementById(dialogId) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Enter as Newline', description: 'Choose which keyboard shortcuts send your message.', width: 440 }) + const ui = createDialog({ id: dialogId, title: 'Enter as Newline', description: 'Choose which keyboard shortcuts send your message.', width: 440 }) const draft: ShortcutSettings = { ...current } const summary = createElement('p', 'bp-hint', describeShortcuts(draft)) const stack = createElement('div', 'bp-stack') @@ -44,4 +45,4 @@ export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settin } ui.footer.append(createButton('Cancel', { onClick: ui.close }), createButton('Reset', { onClick: reset }), createButton('Save', { primary: true, onClick: save })) ui.show() -} \ No newline at end of file +} diff --git a/core/ai/src/features/enter-as-newline/feature.ts b/core/ai/src/features/enter-as-newline/feature.ts new file mode 100644 index 0000000..b07b105 --- /dev/null +++ b/core/ai/src/features/enter-as-newline/feature.ts @@ -0,0 +1,82 @@ +import { Feature } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isSynthetic } from '../../keys' +import { ConfigButton } from './config-button' +import { toggleShortcutsDialog } from './dialog' +import { defaultSend, getEditableTarget, insertNewline, isComposing } from './keyboard' +import type { EditableFilter } from './keyboard' +import { describeShortcuts, hasModifier, loadShortcuts, matchesShortcut, saveShortcuts } from './shortcuts' +import type { ShortcutSettings } from './shortcuts' + +export interface EnterAsNewlineOptions { + readonly storage: ScriptStorage + readonly reject?: EditableFilter + readonly send?: (editable: HTMLElement) => void +} + +export class EnterAsNewlineFeature extends Feature { + readonly id = 'enter-as-newline' + readonly name = 'Enter as Newline' + readonly description = 'Use Enter for newlines and configurable shortcuts to send messages.' + + private shortcuts: ShortcutSettings + private attached = false + private readonly configButton: ConfigButton + + constructor(context: ScriptContext, private readonly options: EnterAsNewlineOptions) { + super(context) + this.shortcuts = loadShortcuts(options.storage) + this.configButton = new ConfigButton( + () => this.configure(), + () => describeShortcuts(this.shortcuts) + ) + } + + run(): void { + if (this.enabled) this.configButton.mount() + else this.configButton.unmount() + if (this.enabled && !this.attached) { + window.addEventListener('keydown', this.handleKeydown, true) + this.attached = true + this.context.logger.success('Enter as Newline listener registered.') + return + } + if (!this.enabled && this.attached) { + window.removeEventListener('keydown', this.handleKeydown, true) + this.attached = false + this.context.logger.info('Enter as Newline listener removed.') + } + } + + override menuEntries(): MenuEntry[] { + return [{ label: 'Configure Enter as Newline', action: () => this.configure() }] + } + + private configure(): void { + toggleShortcutsDialog( + this.shortcuts, + (settings) => { + this.shortcuts = settings + saveShortcuts(this.options.storage, settings) + }, + this.context.logger + ) + } + + private readonly handleKeydown = (event: KeyboardEvent): void => { + if (event.key !== 'Enter' || isComposing(event) || isSynthetic(event)) return + const editable = getEditableTarget(event, this.options.reject) + if (!editable) return + if (matchesShortcut(event, this.shortcuts)) { + event.preventDefault() + event.stopImmediatePropagation() + const sendDefault = this.options.send ?? defaultSend + sendDefault(editable) + return + } + if (hasModifier(event)) return + event.preventDefault() + event.stopImmediatePropagation() + insertNewline(editable) + } +} diff --git a/core/ai/src/features/enter-as-newline/index.ts b/core/ai/src/features/enter-as-newline/index.ts new file mode 100644 index 0000000..19e2a59 --- /dev/null +++ b/core/ai/src/features/enter-as-newline/index.ts @@ -0,0 +1,2 @@ +export { EnterAsNewlineFeature } from './feature' +export type { EnterAsNewlineOptions } from './feature' diff --git a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts b/core/ai/src/features/enter-as-newline/keyboard.ts similarity index 82% rename from ai/perplexity/src/modules/enter-as-newline/keyboard.ts rename to core/ai/src/features/enter-as-newline/keyboard.ts index 44038c6..35f91ae 100644 --- a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts +++ b/core/ai/src/features/enter-as-newline/keyboard.ts @@ -1,14 +1,14 @@ import { toElement } from '@nolly/core' -import { dispatchEnter, findSendButton } from '../../core/synthetic-keys' - -export { isSynthetic } from '../../core/synthetic-keys' +import { dispatchEnter, findSendButton } from '../../keys' const EDITABLE_SELECTOR = 'textarea, [contenteditable="true"], [contenteditable="plaintext-only"]' -export const getEditableTarget = (event: Event): HTMLElement | null => { +export type EditableFilter = (editable: HTMLElement) => boolean + +export const getEditableTarget = (event: Event, reject: EditableFilter = () => false): HTMLElement | null => { const origin = event.composedPath()[0] ?? event.target const editable = toElement(origin)?.closest(EDITABLE_SELECTOR) - if (!editable?.isConnected) return null + if (!editable?.isConnected || reject(editable)) return null return editable instanceof HTMLTextAreaElement || editable.isContentEditable ? editable : null } @@ -41,6 +41,6 @@ export const insertNewline = (editable: HTMLElement): void => { if (dispatchEnter(editable, true)) insertNewlineManually(editable) } -export const sendMessage = (editable: HTMLElement): void => { +export const defaultSend = (editable: HTMLElement): void => { if (dispatchEnter(editable, false)) findSendButton(editable)?.click() -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/enter-as-newline/shortcuts.ts b/core/ai/src/features/enter-as-newline/shortcuts.ts similarity index 86% rename from ai/perplexity/src/modules/enter-as-newline/shortcuts.ts rename to core/ai/src/features/enter-as-newline/shortcuts.ts index b23b921..9054d83 100644 --- a/ai/perplexity/src/modules/enter-as-newline/shortcuts.ts +++ b/core/ai/src/features/enter-as-newline/shortcuts.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import type { ScriptStorage } from '@nolly/core' export type Modifier = 'ctrl' | 'alt' | 'meta' | 'shift' export type ShortcutSettings = Record @@ -20,13 +20,13 @@ export const SHORTCUT_OPTIONS: readonly ShortcutOption[] = [ export const DEFAULT_SHORTCUTS: Readonly = { ctrl: true, alt: false, meta: true, shift: false } -export const loadShortcuts = (): ShortcutSettings => { +export const loadShortcuts = (storage: ScriptStorage): ShortcutSettings => { const saved = storage.get>(STORAGE_KEY, DEFAULT_SHORTCUTS) const entries = SHORTCUT_OPTIONS.map(({ key }) => [key, typeof saved?.[key] === 'boolean' ? saved[key] : DEFAULT_SHORTCUTS[key]]) return Object.fromEntries(entries) as ShortcutSettings } -export const saveShortcuts = (settings: ShortcutSettings): void => storage.set(STORAGE_KEY, settings) +export const saveShortcuts = (storage: ScriptStorage, settings: ShortcutSettings): void => storage.set(STORAGE_KEY, settings) export const matchesShortcut = (event: KeyboardEvent, settings: ShortcutSettings): boolean => { const pressed = SHORTCUT_OPTIONS.filter(({ flag }) => event[flag]) @@ -38,4 +38,4 @@ export const hasModifier = (event: KeyboardEvent): boolean => SHORTCUT_OPTIONS.s export const describeShortcuts = (settings: ShortcutSettings): string => { const labels = SHORTCUT_OPTIONS.filter(({ key }) => settings[key]).map(({ label }) => label) return labels.length ? `Sends with: ${labels.join(', ')}. Plain Enter inserts a newline.` : 'No send shortcut selected: messages can only be sent with the button.' -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/citations.ts b/core/ai/src/features/exporter/citations.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/citations.ts rename to core/ai/src/features/exporter/citations.ts diff --git a/ai/perplexity/src/modules/exporter/dialog.ts b/core/ai/src/features/exporter/dialog.ts similarity index 82% rename from ai/perplexity/src/modules/exporter/dialog.ts rename to core/ai/src/features/exporter/dialog.ts index 802465c..65e89db 100644 --- a/ai/perplexity/src/modules/exporter/dialog.ts +++ b/core/ai/src/features/exporter/dialog.ts @@ -1,11 +1,13 @@ import { createElement } from '@nolly/core' +import { platform } from '../../platform' import { createButton, createSelectField, createSwitch } from '../../ui/controls' import { createDialog } from '../../ui/dialog' import type { CitationStyle } from './citations' import { runExport } from './service' import type { ExportFormat, ExportSettings } from './settings' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-export-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-export-dialog` const FORMATS: readonly { value: ExportFormat; label: string }[] = [ { value: 'md', label: 'Markdown (.md), formatted' }, @@ -25,20 +27,20 @@ const STYLES: readonly { value: CitationStyle; label: string }[] = [ ] export const toggleExportDialog = (settings: ExportSettings, onSettings: (settings: ExportSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Export thread', description: 'Exports the thread you are viewing.', width: 480 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Export thread', description: 'Exports the thread you are viewing.', width: 480 }) const state: ExportSettings = { ...settings } const status = createElement('div', 'bp-hint') const styleField = createSelectField('Citations', STYLES, state.style, (value) => update({ style: value })) - const logoField = createSwitch({ label: 'Remove the Perplexity logo line', checked: state.stripLogo, onChange: (value) => update({ stripLogo: value }) }).wrapper + const logoField = createSwitch({ label: `Remove the ${platform().exporter.name} logo line`, checked: state.stripLogo, onChange: (value) => update({ stripLogo: value }) }).wrapper const copyButton = createButton('Copy') const downloadButton = createButton('Download', { primary: true }) const render = (): void => { - const rendered = state.format !== 'json' + const rendered = state.format !== 'json' && platform().exporter.citations styleField.hidden = !rendered logoField.hidden = !rendered copyButton.hidden = !(state.format === 'md' || state.format === 'txt' || state.format === 'json') diff --git a/ai/perplexity/src/modules/exporter/docx.ts b/core/ai/src/features/exporter/docx.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/docx.ts rename to core/ai/src/features/exporter/docx.ts diff --git a/ai/perplexity/src/modules/exporter/index.ts b/core/ai/src/features/exporter/index.ts similarity index 63% rename from ai/perplexity/src/modules/exporter/index.ts rename to core/ai/src/features/exporter/index.ts index 1558c0f..5125287 100644 --- a/ai/perplexity/src/modules/exporter/index.ts +++ b/core/ai/src/features/exporter/index.ts @@ -1,22 +1,21 @@ -import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { markUi } from '../../core/dom' +import { Feature, createElement } from '@nolly/core' +import type { MenuEntry, ScriptContext } from '@nolly/core' +import { platform } from '../../platform' +import { markUi } from '../../ui/config' import { createIcon } from '../../ui/icons' import { ensureUiStyles } from '../../ui/styles' import { Tooltip } from '../../ui/tooltip' -import { currentThreadSlug } from './api' import { toggleExportDialog } from './dialog' -import { loadExportSettings, saveExportSettings, type ExportSettings } from './settings' +import { loadExportSettings, saveExportSettings } from './settings' +import type { ExportSettings } from './settings' -const INDICATOR_SELECTOR = '.bp-usage-indicator' -const GEAR_SELECTOR = '.bp-gear' - -export class ExporterModule extends Feature { +export class ExporterFeature extends Feature { readonly id = 'exporter' readonly name = 'Conversation Exporter' readonly description = 'Exports threads with configurable citation styles.' private settings: ExportSettings = loadExportSettings() - private readonly button = markUi(createElement('button', 'bp-header-btn bp-export')) + private readonly button = markUi(createElement('button', 'bp-header-btn bp-export bp-themed')) private readonly tooltip: Tooltip constructor(context: ScriptContext) { @@ -30,14 +29,11 @@ export class ExporterModule extends Feature { } run(): void { - const indicator = document.querySelector(INDICATOR_SELECTOR) - if (!this.enabled || !indicator || !currentThreadSlug()) { + const source = platform().exporter + if (!this.enabled || !source.slug() || !source.place(this.button)) { this.tooltip.hide() this.button.remove() - return } - const gear = indicator.querySelector(GEAR_SELECTOR) - if (this.button.parentElement !== indicator || (gear && this.button.nextElementSibling !== gear)) indicator.insertBefore(this.button, gear) } override menuEntries(): MenuEntry[] { @@ -50,4 +46,4 @@ export class ExporterModule extends Feature { saveExportSettings(settings) }) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/markdown.ts b/core/ai/src/features/exporter/markdown.ts similarity index 97% rename from ai/perplexity/src/modules/exporter/markdown.ts rename to core/ai/src/features/exporter/markdown.ts index 817cac1..38f5899 100644 --- a/ai/perplexity/src/modules/exporter/markdown.ts +++ b/core/ai/src/features/exporter/markdown.ts @@ -116,7 +116,7 @@ export const parseBlocks = (markdown: string): Block[] => { const BLOCK_START = /^(#{1,6}\s|---+\s*$|\s*(?:[-*+]|\d+[.)])\s|\s*\|)/ -export const formatMarkdown = (markdown: string, meta: { title: string; url: string }): string => { +export const formatMarkdown = (markdown: string, meta: { title: string; url: string; source: string }): string => { const cleaned: string[] = [] let fenced = false for (const raw of markdown.replace(/\r\n?/g, '\n').split('\n')) { @@ -143,7 +143,7 @@ export const formatMarkdown = (markdown: string, meta: { title: string; url: str if (fenced || fence || line.trim() !== '' || spaced.at(-1)?.trim() !== '') spaced.push(line) } const body = spaced.join('\n').replace(/\n{3,}/g, '\n\n').trim() - const stamp = `_Exported from Perplexity on ${new Date().toLocaleString()} · ${meta.url}_` + const stamp = `_Exported from ${meta.source} on ${new Date().toLocaleString()} · ${meta.url}_` const firstLine = body.split('\n', 1)[0] ?? '' if (firstLine.startsWith('# ')) return `${firstLine}\n\n${stamp}\n\n${body.slice(firstLine.length).trim()}\n` return `# ${meta.title}\n\n${stamp}\n\n---\n\n${body}\n` diff --git a/ai/perplexity/src/modules/exporter/pdf.ts b/core/ai/src/features/exporter/pdf.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/pdf.ts rename to core/ai/src/features/exporter/pdf.ts diff --git a/ai/perplexity/src/modules/exporter/service.ts b/core/ai/src/features/exporter/service.ts similarity index 58% rename from ai/perplexity/src/modules/exporter/service.ts rename to core/ai/src/features/exporter/service.ts index 418f041..7c52c37 100644 --- a/ai/perplexity/src/modules/exporter/service.ts +++ b/core/ai/src/features/exporter/service.ts @@ -1,6 +1,6 @@ -import { copyText } from '../../core/clipboard' -import { saveFile } from '../../core/download' -import { currentThreadSlug, exportThread, fetchThreadJson } from './api' +import { copyText } from '../../clipboard' +import { saveFile } from '../../download' +import { platform } from '../../platform' import { reformatCitations, stripLogo } from './citations' import { buildDocx } from './docx' import { formatMarkdown, parseBlocks } from './markdown' @@ -10,25 +10,31 @@ import { blocksToText } from './text' const MIME = { docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf: 'application/pdf' } as const -const filenameBase = (): string => (currentThreadSlug() ?? 'perplexity-thread').replace(/[^\w-]+/g, '-').slice(0, 60) || 'perplexity-thread' +const fallbackName = (): string => `${platform().exporter.name.toLowerCase()}-thread` -const pageTitle = (): string => document.title.replace(/\s*[-–|]\s*Perplexity\s*$/i, '').trim() || 'Perplexity thread' +const filenameBase = (): string => (platform().exporter.slug() ?? fallbackName()).replace(/[^\w-]+/g, '-').slice(0, 60) || fallbackName() -const loadMarkdown = async (settings: ExportSettings, base: string): Promise => { - const file = await exportThread('md', base) - const raw = new TextDecoder().decode(file.bytes) - return formatMarkdown(reformatCitations(settings.stripLogo ? stripLogo(raw) : raw, settings.style), { title: pageTitle(), url: location.href }) +const pageTitle = (): string => { + const { name } = platform().exporter + return document.title.replace(new RegExp(`\\s*[-–|]\\s*${name}\\s*$`, 'i'), '').trim() || `${name} thread` +} + +const loadMarkdown = async (settings: ExportSettings): Promise => { + const source = platform().exporter + const raw = await source.markdown() + const text = source.citations ? reformatCitations(settings.stripLogo ? stripLogo(raw) : raw, settings.style) : raw + return formatMarkdown(text, { title: pageTitle(), url: location.href, source: source.name }) } export const runExport = async (settings: ExportSettings, action: 'download' | 'copy'): Promise => { const base = filenameBase() if (settings.format === 'json') { - const json = await fetchThreadJson() + const json = await platform().exporter.json() if (action === 'copy') return (await copyText(json)) ? 'Copied JSON.' : 'Copy failed.' saveFile(`${base}.json`, json, 'application/json') return 'Downloaded.' } - const markdown = await loadMarkdown(settings, base) + const markdown = await loadMarkdown(settings) const blocks = parseBlocks(markdown) if (settings.format === 'md' || settings.format === 'txt') { const text = settings.format === 'md' ? markdown : blocksToText(blocks) @@ -40,4 +46,4 @@ export const runExport = async (settings: ExportSettings, action: 'download' | ' const bytes = settings.format === 'docx' ? buildDocx(blocks) : buildPdf(blocks, pageTitle()) saveFile(`${base}.${settings.format}`, bytes as BlobPart, MIME[settings.format]) return 'Downloaded.' -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/settings.ts b/core/ai/src/features/exporter/settings.ts similarity index 93% rename from ai/perplexity/src/modules/exporter/settings.ts rename to core/ai/src/features/exporter/settings.ts index 774d7fc..863213b 100644 --- a/ai/perplexity/src/modules/exporter/settings.ts +++ b/core/ai/src/features/exporter/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { CitationStyle } from './citations' export type ExportFormat = 'md' | 'txt' | 'docx' | 'pdf' | 'json' diff --git a/core/ai/src/features/exporter/source.ts b/core/ai/src/features/exporter/source.ts new file mode 100644 index 0000000..b72fa84 --- /dev/null +++ b/core/ai/src/features/exporter/source.ts @@ -0,0 +1,8 @@ +export interface ExportSource { + readonly name: string + readonly citations: boolean + readonly slug: () => string | null + readonly markdown: () => Promise + readonly json: () => Promise + readonly place: (button: HTMLElement) => boolean +} diff --git a/ai/perplexity/src/modules/exporter/text.ts b/core/ai/src/features/exporter/text.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/text.ts rename to core/ai/src/features/exporter/text.ts diff --git a/ai/perplexity/src/modules/exporter/zip.ts b/core/ai/src/features/exporter/zip.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/zip.ts rename to core/ai/src/features/exporter/zip.ts diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts new file mode 100644 index 0000000..f4d31d9 --- /dev/null +++ b/core/ai/src/features/index.ts @@ -0,0 +1,21 @@ +export { DraftGuardFeature } from './draft-guard' +export type { DraftGuardOptions } from './draft-guard' +export { EnterAsNewlineFeature } from './enter-as-newline' +export type { EnterAsNewlineOptions } from './enter-as-newline' +export { MessageSplitterFeature, loadSplitterSettings } from './message-splitter' +export type { MessageSplitterOptions, SplitterSettings } from './message-splitter' +export { CommandPaletteFeature } from './command-palette' +export { PromptQueueFeature } from './prompt-queue' +export { PromptLibraryFeature } from './prompt-library' +export { RecallFeature } from './recall' +export { BatchRunnerFeature } from './batch-runner' +export { SelectionToolbarFeature } from './selection-toolbar' +export { MaxWidthFeature } from './max-width' +export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './max-width' +export { formatShortcut, loadShortcut, matchesShortcut } from './command-palette/shortcut' +export type { Shortcut } from './command-palette/shortcut' +export { loadPromptShortcut } from './prompt-library/shortcut' +export { CodeBlocksFeature } from './code-blocks' +export { ExporterFeature } from './exporter' +export { UpdatesFeature } from './updates' +export type { ExportSource } from './exporter/source' diff --git a/core/ai/src/features/max-width/feature.ts b/core/ai/src/features/max-width/feature.ts new file mode 100644 index 0000000..c301512 --- /dev/null +++ b/core/ai/src/features/max-width/feature.ts @@ -0,0 +1,116 @@ +import { Feature, getElement } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isOwnUi } from '../../ui/config' +import { StyleManager } from './style-manager' + +const SIDEBAR_KEY = 'max-width:remove-sidebar' +const DEFAULT_CONSTRAINED = 'main [class*="max-w-"], main [style*="max-width"]' +const OVERLAYS = '[role="dialog"], [role="menu"], [role="listbox"], [role="tooltip"], dialog, [data-radix-popper-content-wrapper]' +const MIN_CONSTRAINT = 480 +const SCAN_INTERVAL = 1_200 + +export interface Target { + readonly xpath?: string + readonly selector?: string +} + +export interface HideRule extends Target { + readonly id: string +} + +export interface LayoutRule extends Target { + readonly styles: Readonly> +} + +export interface SidebarOption { + readonly rule: HideRule + readonly label: string + readonly defaultRemoved: boolean +} + +export interface MaxWidthOptions { + readonly storage: ScriptStorage + readonly hidden?: readonly HideRule[] + readonly layout?: readonly LayoutRule[] + readonly sidebar?: SidebarOption + readonly constrained?: string +} + +const resolveTarget = ({ xpath, selector }: Target): HTMLElement | null => { + if (xpath) return getElement(xpath) + return selector ? document.querySelector(selector) : null +} + +const labelOf = (rule: HideRule): string => rule.xpath ?? rule.selector ?? rule.id + +export class MaxWidthFeature extends Feature { + readonly id = 'max-width' + readonly name = 'Max Width' + readonly description = 'Remove width restrictions and expand the interface.' + + private readonly styles = new StyleManager() + private readonly touched = new Set() + private scannedAt = 0 + + constructor(context: ScriptContext, private readonly options: MaxWidthOptions) { + super(context) + } + + get removeSidebar(): boolean { + return this.options.storage.get(SIDEBAR_KEY, this.options.sidebar?.defaultRemoved ?? false) + } + + set removeSidebar(value: boolean) { + this.options.storage.set(SIDEBAR_KEY, value) + } + + run(): void { + const active = this.enabled + for (const rule of this.options.hidden ?? []) this.syncHidden(rule, active) + if (this.options.sidebar) this.syncHidden(this.options.sidebar.rule, active && this.removeSidebar) + for (const rule of this.options.layout ?? []) { + const element = resolveTarget(rule) + if (!element) continue + if (active) this.styles.apply(element, rule.styles) + else this.styles.restore(element, Object.keys(rule.styles)) + } + this.expand(active) + } + + override menuEntries(): MenuEntry[] { + const { sidebar } = this.options + return sidebar ? [{ label: `${this.removeSidebar ? 'Show' : 'Remove'} ${sidebar.label}`, action: () => this.toggleSidebar(sidebar) }] : [] + } + + private expand(active: boolean): void { + if (!active) { + for (const element of this.touched) this.styles.restore(element, ['max-width']) + this.touched.clear() + return + } + const now = Date.now() + if (now - this.scannedAt < SCAN_INTERVAL) return + this.scannedAt = now + for (const element of this.touched) if (!element.isConnected) this.touched.delete(element) + for (const element of document.querySelectorAll(this.options.constrained ?? DEFAULT_CONSTRAINED)) { + if (this.touched.has(element) || isOwnUi(element) || element.closest(OVERLAYS)) continue + const limit = Number.parseFloat(getComputedStyle(element).maxWidth) + if (!Number.isFinite(limit) || limit < MIN_CONSTRAINT) continue + if (element.getBoundingClientRect().width < limit * 0.9) continue + this.styles.apply(element, { 'max-width': '100%' }) + this.touched.add(element) + } + } + + private syncHidden(rule: HideRule, hidden: boolean): void { + const element = resolveTarget(rule) + if (element) this.styles.setHidden(element, hidden, labelOf(rule)) + } + + private toggleSidebar(sidebar: SidebarOption): void { + this.removeSidebar = !this.removeSidebar + this.context.logger.info(`${sidebar.label} removal ${this.removeSidebar ? 'enabled' : 'disabled'}.`) + this.context.refreshMenu() + this.context.requestUpdate() + } +} diff --git a/core/ai/src/features/max-width/index.ts b/core/ai/src/features/max-width/index.ts new file mode 100644 index 0000000..c184556 --- /dev/null +++ b/core/ai/src/features/max-width/index.ts @@ -0,0 +1,2 @@ +export { MaxWidthFeature } from './feature' +export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './feature' diff --git a/ai/perplexity/src/modules/max-width/style-manager.ts b/core/ai/src/features/max-width/style-manager.ts similarity index 97% rename from ai/perplexity/src/modules/max-width/style-manager.ts rename to core/ai/src/features/max-width/style-manager.ts index 70f3dda..c86237b 100644 --- a/ai/perplexity/src/modules/max-width/style-manager.ts +++ b/core/ai/src/features/max-width/style-manager.ts @@ -1,4 +1,4 @@ -import { logger } from '../../core/logger' +import { logger } from '../../platform' interface OriginalValue { readonly value: string @@ -47,4 +47,4 @@ export class StyleManager { this.hidden.delete(element) logger.debug('Element restored.', label) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/message-splitter/big-text.ts b/core/ai/src/features/message-splitter/big-text.ts similarity index 86% rename from ai/perplexity/src/modules/message-splitter/big-text.ts rename to core/ai/src/features/message-splitter/big-text.ts index 1d66a05..dee3225 100644 --- a/ai/perplexity/src/modules/message-splitter/big-text.ts +++ b/core/ai/src/features/message-splitter/big-text.ts @@ -1,14 +1,15 @@ import { createElement } from '@nolly/core' -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '../../tokens' +import { uiConfig } from '../../ui/config' import { createButton, createNumberField, createSelectField, createTextArea } from '../../ui/controls' import { createDialog } from '../../ui/dialog' -import { createPartRows, formatNumber, type SplitChoice } from './dialog' -import { planParts, type SplitPlan } from './plan' +import { createPartRows, formatNumber } from './dialog' +import type { SplitChoice } from './dialog' +import { planParts } from './plan' +import type { SplitPlan } from './plan' import type { SplitterSettings } from './settings' import { ensureSplitterStyles } from './styles' -const DIALOG_ID = 'better-perplexity-bigtext-dialog' - export interface BigTextRequest { settings: SplitterSettings onSettings: (settings: SplitterSettings) => void @@ -17,9 +18,10 @@ export interface BigTextRequest { } export const openBigTextDialog = ({ settings, onSettings, onInsert, onSend }: BigTextRequest): void => { - if (document.getElementById(DIALOG_ID)) return + const dialogId = `${uiConfig().id}-bigtext-dialog` + if (document.getElementById(dialogId)) return ensureSplitterStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Compose a big message', description: 'Paste any amount of text. It is split only if it is too big for one message.', width: 760 }) + const ui = createDialog({ id: dialogId, title: 'Compose a big message', description: 'Paste any amount of text. It is split only if it is too big for one message.', width: 760 }) const state: SplitterSettings = { ...settings } let text = '' let instruction = '' @@ -83,4 +85,4 @@ export const openBigTextDialog = ({ settings, onSettings, onInsert, onSend }: Bi render() ui.show() area.focus() -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/message-splitter/dialog.ts b/core/ai/src/features/message-splitter/dialog.ts similarity index 92% rename from ai/perplexity/src/modules/message-splitter/dialog.ts rename to core/ai/src/features/message-splitter/dialog.ts index b557d94..2dc2f9a 100644 --- a/ai/perplexity/src/modules/message-splitter/dialog.ts +++ b/core/ai/src/features/message-splitter/dialog.ts @@ -1,15 +1,15 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '../../tokens' +import { markUi, uiConfig } from '../../ui/config' import { createButton, createNumberField, createSelectField, createSwitch, createTextArea } from '../../ui/controls' import { createDialog } from '../../ui/dialog' import { ensureUiStyles } from '../../ui/styles' -import { planParts, type SplitPlan } from './plan' +import { planParts } from './plan' +import type { SplitPlan } from './plan' import type { PartStatus } from './runner' import type { SplitterSettings } from './settings' import { ensureSplitterStyles } from './styles' -const DIALOG_ID = 'better-perplexity-splitter-dialog' const PREVIEW_CHARS = 6_000 export interface SplitChoice { @@ -37,8 +37,9 @@ export const createPartRows = (plan: SplitPlan): HTMLElement[] => }) export const openSplitDialog = ({ text, settings, onSettings, onConfirm }: SplitDialogRequest): void => { - if (document.getElementById(DIALOG_ID)) return - const ui = createDialog({ id: DIALOG_ID, title: 'Message splitter', description: `This message is about ${formatNumber(estimateTokens(text))} tokens.`, width: 640 }) + const dialogId = `${uiConfig().id}-splitter-dialog` + if (document.getElementById(dialogId)) return + const ui = createDialog({ id: dialogId, title: 'Message splitter', description: `This message is about ${formatNumber(estimateTokens(text))} tokens.`, width: 640 }) const state: SplitterSettings = { ...settings } let instruction = '' let plan: SplitPlan = planParts(text, instruction, state.limit, state.balanced) @@ -132,4 +133,4 @@ export class ProgressPanel { window.clearTimeout(this.timer) this.timer = window.setTimeout(() => this.element.remove(), ms) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/message-splitter/index.ts b/core/ai/src/features/message-splitter/feature.ts similarity index 62% rename from ai/perplexity/src/modules/message-splitter/index.ts rename to core/ai/src/features/message-splitter/feature.ts index 4127a6a..b44a90f 100644 --- a/ai/perplexity/src/modules/message-splitter/index.ts +++ b/core/ai/src/features/message-splitter/feature.ts @@ -1,25 +1,44 @@ -import { attachFile, editableFrom, findComposer, isSendButton, readComposer, writeComposer } from '../../core/composer' -import { Feature, type MenuEntry, toElement, waitFor } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' -import { ProgressPanel, openSplitDialog, type SplitChoice } from './dialog' -import { SendRunner } from './runner' -import { loadSplitterSettings, saveSplitterSettings, type SplitterSettings } from './settings' +import { Feature, toElement, waitFor } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isAutomating } from '../../automation' +import { isSendButton, readComposer } from '../../composer' +import type { ComposerKit } from '../../composer' +import type { GenerationKit } from '../../generation' +import { estimateTokens } from '../../tokens' +import { uiConfig } from '../../ui/config' import { ComposerButton } from '../../ui/composer-button' import { openBigTextDialog } from './big-text' -import { isAutomating } from '../../core/automation' +import { ProgressPanel, openSplitDialog } from './dialog' +import type { SplitChoice } from './dialog' +import { SendRunner } from './runner' +import { loadSplitterSettings, saveSplitterSettings } from './settings' +import type { SplitterSettings } from './settings' + +export interface MessageSplitterOptions { + readonly storage: ScriptStorage + readonly composer: ComposerKit + readonly generation: Pick + readonly defaults?: Partial + readonly attachBlocked?: () => string | null +} -export class MessageSplitterModule extends Feature { +export class MessageSplitterFeature extends Feature { readonly id = 'message-splitter' readonly name = 'Message Splitter' readonly description = 'Splits oversized prompts into ordered parts, or attaches them as a file.' - private settings: SplitterSettings = loadSplitterSettings() - private readonly runner = new SendRunner() + private settings: SplitterSettings + private readonly runner: SendRunner private readonly panel = new ProgressPanel() private attached = false private readonly bigButton = new ComposerButton('Compose big message', 'file', 'Paste a large message. It is split only if needed.', () => this.openBig(), { id: 'big' }) + constructor(context: ScriptContext, private readonly options: MessageSplitterOptions) { + super(context) + this.settings = loadSplitterSettings(options.storage, options.defaults) + this.runner = new SendRunner({ composer: options.composer, waitForResponse: options.generation.waitForResponse, logger: context.logger }) + } + run(): void { if (this.enabled) this.bigButton.mount() else this.bigButton.unmount() @@ -46,18 +65,22 @@ export class MessageSplitterModule extends Feature { private saveSettings(settings: SplitterSettings): void { this.settings = settings - saveSplitterSettings(settings) + saveSplitterSettings(this.options.storage, settings) this.context.refreshMenu() } + private isOwn(element: Element): boolean { + return uiConfig().marker.isOwn(element) + } + private isOversized(editable: HTMLElement): boolean { return this.settings.autoIntercept && estimateTokens(readComposer(editable)) > this.settings.limit } private readonly handleKeydown = (event: KeyboardEvent): void => { if (this.runner.active || isAutomating() || event.key !== 'Enter' || event.shiftKey || event.isComposing) return - const editable = editableFrom(event.target) - if (!editable || isOwnUi(editable) || !this.isOversized(editable)) return + const editable = this.options.composer.editableFrom(event.target) + if (!editable || this.isOwn(editable) || !this.isOversized(editable)) return event.preventDefault() event.stopImmediatePropagation() this.open() @@ -66,8 +89,8 @@ export class MessageSplitterModule extends Feature { private readonly handleClick = (event: MouseEvent): void => { if (this.runner.active || isAutomating() || !this.settings.autoIntercept) return const button = toElement(event.target)?.closest('button') - if (!button || isOwnUi(button) || !isSendButton(button)) return - const composer = findComposer() + if (!button || this.isOwn(button) || !isSendButton(button)) return + const composer = this.options.composer.findComposer() if (!composer || !this.isOversized(composer)) return event.preventDefault() event.stopImmediatePropagation() @@ -75,7 +98,7 @@ export class MessageSplitterModule extends Feature { } private open(): void { - const composer = findComposer() + const composer = this.options.composer.findComposer() const text = composer ? readComposer(composer) : '' if (!text.trim()) { this.panel.notify('The composer is empty.') @@ -101,13 +124,18 @@ export class MessageSplitterModule extends Feature { } private async attachAsFile(text: string, instruction: string): Promise { - const composer = findComposer() + const blocked = this.options.attachBlocked?.() + if (blocked) { + this.panel.notify(blocked) + return + } + const composer = this.options.composer.findComposer() if (!composer) { this.panel.notify('No composer found.') return } - const attached = attachFile(composer, new File([text], 'message.txt', { type: 'text/plain' })) - await writeComposer(composer, instruction.trim()) + const attached = this.options.composer.attachFile(composer, new File([text], 'message.txt', { type: 'text/plain' })) + await this.options.composer.writeComposer(composer, instruction.trim()) this.panel.notify(attached ? 'File attached. Add your question and send.' : 'Could not attach the file automatically.') } @@ -121,11 +149,11 @@ export class MessageSplitterModule extends Feature { } private async insert(text: string): Promise { - const composer = await waitFor(findComposer, { timeout: 5_000 }) + const composer = await waitFor(this.options.composer.findComposer, { timeout: 5_000 }) if (!composer) { this.panel.notify('No composer found.') return } - this.panel.notify((await writeComposer(composer, text)) ? 'Inserted into the composer.' : 'Could not insert the text.') + this.panel.notify((await this.options.composer.writeComposer(composer, text)) ? 'Inserted into the composer.' : 'Could not insert the text.') } -} \ No newline at end of file +} diff --git a/core/ai/src/features/message-splitter/index.ts b/core/ai/src/features/message-splitter/index.ts new file mode 100644 index 0000000..d25038a --- /dev/null +++ b/core/ai/src/features/message-splitter/index.ts @@ -0,0 +1,4 @@ +export { MessageSplitterFeature } from './feature' +export type { MessageSplitterOptions } from './feature' +export { loadSplitterSettings } from './settings' +export type { SplitterSettings } from './settings' diff --git a/ai/perplexity/src/modules/message-splitter/plan.ts b/core/ai/src/features/message-splitter/plan.ts similarity index 96% rename from ai/perplexity/src/modules/message-splitter/plan.ts rename to core/ai/src/features/message-splitter/plan.ts index 50eab44..1bf888f 100644 --- a/ai/perplexity/src/modules/message-splitter/plan.ts +++ b/core/ai/src/features/message-splitter/plan.ts @@ -1,4 +1,4 @@ -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '../../tokens' import { splitText } from './splitter' export interface PartTemplates { @@ -31,4 +31,4 @@ export const planParts = (text: string, instruction: string, limit: number, bala const count = raw.length const parts = raw.map((chunk, index) => index === count - 1 ? `${fill(templates.final, index + 1, count)}\n\n${chunk}${tail}` : `${fill(templates.header, index + 1, count)}\n\n${chunk}`) return { parts, tokens: parts.map((part) => estimateTokens(part)), total } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/message-splitter/runner.ts b/core/ai/src/features/message-splitter/runner.ts similarity index 62% rename from ai/perplexity/src/modules/message-splitter/runner.ts rename to core/ai/src/features/message-splitter/runner.ts index 76e459b..8d72ea5 100644 --- a/ai/perplexity/src/modules/message-splitter/runner.ts +++ b/core/ai/src/features/message-splitter/runner.ts @@ -1,14 +1,22 @@ -import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { waitForResponse } from '../../core/generation' -import { logger } from '../../core/logger' import { isAbort, waitFor } from '@nolly/core' +import type { Logger } from '@nolly/core' +import type { ComposerKit } from '../../composer' +import type { GenerationKit } from '../../generation' export type PartStatus = 'sending' | 'waiting' | 'done' export type RunResult = 'done' | 'cancelled' | 'failed' +export interface RunnerDeps { + readonly composer: Pick + readonly waitForResponse: GenerationKit['waitForResponse'] + readonly logger: Logger +} + export class SendRunner { private controller: AbortController | null = null + constructor(private readonly deps: RunnerDeps) {} + get active(): boolean { return this.controller !== null } @@ -22,13 +30,14 @@ export class SendRunner { const controller = new AbortController() this.controller = controller const { signal } = controller + const { composer: kit, waitForResponse, logger } = this.deps try { for (let index = 0; index < parts.length; index++) { onStatus(index, 'sending') - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) + const composer = await waitFor(kit.findComposer, { timeout: 15_000, signal }) if (!composer) return 'failed' - if (!(await writeComposer(composer, parts[index]!))) return 'failed' - if (!(await sendComposer(composer))) return 'failed' + if (!(await kit.writeComposer(composer, parts[index]!))) return 'failed' + if (!(await kit.sendComposer(composer))) return 'failed' if (index < parts.length - 1) { onStatus(index, 'waiting') await waitForResponse({ signal }) @@ -44,4 +53,4 @@ export class SendRunner { this.controller = null } } -} \ No newline at end of file +} diff --git a/core/ai/src/features/message-splitter/settings.ts b/core/ai/src/features/message-splitter/settings.ts new file mode 100644 index 0000000..2b8383a --- /dev/null +++ b/core/ai/src/features/message-splitter/settings.ts @@ -0,0 +1,20 @@ +import type { ScriptStorage } from '@nolly/core' + +export interface SplitterSettings { + limit: number + autoIntercept: boolean + balanced: boolean + mode: 'parts' | 'file' +} + +const STORAGE_KEY = 'message-splitter:settings' + +export const DEFAULT_SPLITTER_SETTINGS: Readonly = { limit: 7_500, autoIntercept: true, balanced: true, mode: 'parts' } + +export const loadSplitterSettings = (storage: ScriptStorage, defaults: Partial = {}): SplitterSettings => ({ + ...DEFAULT_SPLITTER_SETTINGS, + ...defaults, + ...storage.get>(STORAGE_KEY, {}) +}) + +export const saveSplitterSettings = (storage: ScriptStorage, settings: SplitterSettings): void => storage.set(STORAGE_KEY, settings) diff --git a/ai/perplexity/src/modules/message-splitter/splitter.ts b/core/ai/src/features/message-splitter/splitter.ts similarity index 98% rename from ai/perplexity/src/modules/message-splitter/splitter.ts rename to core/ai/src/features/message-splitter/splitter.ts index 123d21e..be0e902 100644 --- a/ai/perplexity/src/modules/message-splitter/splitter.ts +++ b/core/ai/src/features/message-splitter/splitter.ts @@ -1,4 +1,4 @@ -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '../../tokens' interface CodeAtom { kind: 'code' @@ -117,4 +117,4 @@ export const splitText = (text: string, { budget, balanced }: SplitOptions): str }) if (current.length) parts.push(current) return parts.map((part) => part.join('\n\n')) -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/message-splitter/styles.ts b/core/ai/src/features/message-splitter/styles.ts similarity index 86% rename from ai/perplexity/src/modules/message-splitter/styles.ts rename to core/ai/src/features/message-splitter/styles.ts index 2b13b51..20011b7 100644 --- a/ai/perplexity/src/modules/message-splitter/styles.ts +++ b/core/ai/src/features/message-splitter/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-split-summary { margin-bottom: 12px; color: var(--bp-muted); font-size: 12px; } @@ -25,4 +26,4 @@ const CSS = ` } ` -export const ensureSplitterStyles = (): void => injectStyle('better-perplexity-splitter-styles', CSS) \ No newline at end of file +export const ensureSplitterStyles = (): void => injectStyle(`${uiConfig().id}-splitter-styles`, CSS) diff --git a/ai/perplexity/src/modules/prompt-library/index.ts b/core/ai/src/features/prompt-library/index.ts similarity index 94% rename from ai/perplexity/src/modules/prompt-library/index.ts rename to core/ai/src/features/prompt-library/index.ts index 3327aaf..91ed2fc 100644 --- a/ai/perplexity/src/modules/prompt-library/index.ts +++ b/core/ai/src/features/prompt-library/index.ts @@ -1,6 +1,5 @@ -import { findComposer, writeComposer } from '../../core/composer' +import { findComposer, writeComposer, storage } from '../../platform' import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { storage } from '../../core/storage' import { ComposerButton } from '../../ui/composer-button' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' @@ -11,7 +10,7 @@ import { loadPromptShortcut, PROMPT_SHORTCUT_KEY, DEFAULT_PROMPT_SHORTCUT } from import { PromptStore, type Prompt } from './store' import { expandPrompt } from './variables' -export class PromptLibraryModule extends Feature { +export class PromptLibraryFeature extends Feature { readonly id = 'prompt-library' readonly name = 'Prompt Library' readonly description = 'Insert saved and community prompts from a button or shortcut.' diff --git a/ai/perplexity/src/modules/prompt-library/manager.ts b/core/ai/src/features/prompt-library/manager.ts similarity index 89% rename from ai/perplexity/src/modules/prompt-library/manager.ts rename to core/ai/src/features/prompt-library/manager.ts index 11f4bdd..5791e6c 100644 --- a/ai/perplexity/src/modules/prompt-library/manager.ts +++ b/core/ai/src/features/prompt-library/manager.ts @@ -1,20 +1,21 @@ -import { copyText } from '../../core/clipboard' -import { createElement } from '@nolly/core' +import { copyText } from '../../clipboard' import { createButton, createTextArea } from '../../ui/controls' import { createDialog } from '../../ui/dialog' +import { createElement } from '@nolly/core' import type { Prompt, PromptStore } from './store' import { ensureSlashStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-prompts-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-prompts-dialog` export const toggleManager = (store: PromptStore, onInsert: (prompt: Prompt) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensureSlashStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Prompt library', description: 'Type / in an empty message box to insert a prompt.', width: 620 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Prompt library', description: 'Type / in an empty message box to insert a prompt.', width: 620 }) const status = createElement('span', 'bp-updated') const editForm = (prompt: Prompt): void => { const draft = { ...prompt } diff --git a/ai/perplexity/src/modules/prompt-library/picker.ts b/core/ai/src/features/prompt-library/picker.ts similarity index 93% rename from ai/perplexity/src/modules/prompt-library/picker.ts rename to core/ai/src/features/prompt-library/picker.ts index 9ab367c..4ea355e 100644 --- a/ai/perplexity/src/modules/prompt-library/picker.ts +++ b/core/ai/src/features/prompt-library/picker.ts @@ -3,8 +3,9 @@ import { createDialog } from '../../ui/dialog' import { fuzzyScore } from '../command-palette/fuzzy' import { ensurePaletteStyles } from '../command-palette/styles' import type { Prompt, PromptStore } from './store' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-prompt-picker' +const DIALOG_ID = (): string => `${uiConfig().id}-prompt-picker` export interface PickerOptions { store: PromptStore @@ -22,13 +23,13 @@ interface Row { } export const togglePromptPicker = ({ store, community, onPick, onSave, onManage }: PickerOptions): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Prompts', width: 600 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Prompts', width: 600 }) ui.dialog.classList.add('bp-palette') const mine = store.list() let shared: Prompt[] = [] diff --git a/ai/perplexity/src/modules/prompt-library/remote.ts b/core/ai/src/features/prompt-library/remote.ts similarity index 79% rename from ai/perplexity/src/modules/prompt-library/remote.ts rename to core/ai/src/features/prompt-library/remote.ts index e872c4b..aa18f7c 100644 --- a/ai/perplexity/src/modules/prompt-library/remote.ts +++ b/core/ai/src/features/prompt-library/remote.ts @@ -1,7 +1,5 @@ import { getText } from '@nolly/core' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { URLS } from '../../repo' +import { logger, platform, storage } from '../../platform' import type { Prompt } from './store' interface Cache { @@ -21,7 +19,7 @@ export const loadCommunity = async (force = false): Promise => { const cached = storage.get(KEY, null) if (cached && !force && Date.now() - cached.at < TTL) return cached.prompts try { - const parsed = JSON.parse(await getText(`${URLS.prompts}?t=${Date.now()}`)) as { prompts?: unknown[] } + const parsed = JSON.parse(await getText(`${platform().promptsUrl}?t=${Date.now()}`)) as { prompts?: unknown[] } const prompts = (parsed.prompts ?? []).filter(isPrompt) storage.set(KEY, { at: Date.now(), prompts }) return prompts diff --git a/ai/perplexity/src/modules/prompt-library/shortcut.ts b/core/ai/src/features/prompt-library/shortcut.ts similarity index 89% rename from ai/perplexity/src/modules/prompt-library/shortcut.ts rename to core/ai/src/features/prompt-library/shortcut.ts index 8b740fe..ba381f2 100644 --- a/ai/perplexity/src/modules/prompt-library/shortcut.ts +++ b/core/ai/src/features/prompt-library/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export const PROMPT_SHORTCUT_KEY = 'prompt-library:shortcut' diff --git a/ai/perplexity/src/modules/prompt-library/store.ts b/core/ai/src/features/prompt-library/store.ts similarity index 97% rename from ai/perplexity/src/modules/prompt-library/store.ts rename to core/ai/src/features/prompt-library/store.ts index c278c40..707a717 100644 --- a/ai/perplexity/src/modules/prompt-library/store.ts +++ b/core/ai/src/features/prompt-library/store.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface Prompt { id: string diff --git a/ai/perplexity/src/modules/prompt-library/styles.ts b/core/ai/src/features/prompt-library/styles.ts similarity index 70% rename from ai/perplexity/src/modules/prompt-library/styles.ts rename to core/ai/src/features/prompt-library/styles.ts index f9bea22..27c7bad 100644 --- a/ai/perplexity/src/modules/prompt-library/styles.ts +++ b/core/ai/src/features/prompt-library/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-prompt-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 12px; border: 1px solid var(--bp-border); border-radius: 10px; } @@ -6,4 +7,4 @@ const CSS = ` .bp-prompt-actions { display: flex; flex-shrink: 0; gap: 6px; } ` -export const ensureSlashStyles = (): void => injectStyle('better-perplexity-slash-styles', CSS) \ No newline at end of file +export const ensureSlashStyles = (): void => injectStyle(`${uiConfig().id}-slash-styles`, CSS) \ No newline at end of file diff --git a/ai/perplexity/src/modules/prompt-library/variables.ts b/core/ai/src/features/prompt-library/variables.ts similarity index 91% rename from ai/perplexity/src/modules/prompt-library/variables.ts rename to core/ai/src/features/prompt-library/variables.ts index ad19c84..8e09c57 100644 --- a/ai/perplexity/src/modules/prompt-library/variables.ts +++ b/core/ai/src/features/prompt-library/variables.ts @@ -1,5 +1,5 @@ -import { applyValues, findFields, type Field } from '../../core/placeholders' -import { currentSelection } from '../../core/selection' +import { applyValues, findFields, type Field } from '../../placeholders' +import { currentSelection } from '../../selection' import { askFields } from '../../ui/placeholder-dialog' const BUILTINS = new Set(['clipboard', 'selection', 'date', 'time', 'url', 'title']) diff --git a/ai/perplexity/src/modules/prompt-queue/index.ts b/core/ai/src/features/prompt-queue/index.ts similarity index 93% rename from ai/perplexity/src/modules/prompt-queue/index.ts rename to core/ai/src/features/prompt-queue/index.ts index 9a6563b..eb26efc 100644 --- a/ai/perplexity/src/modules/prompt-queue/index.ts +++ b/core/ai/src/features/prompt-queue/index.ts @@ -1,8 +1,6 @@ import { Feature, waitFor, type MenuEntry, type ScriptContext } from '@nolly/core' -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' -import { sendPrompt } from '../../core/dispatch' -import { isGenerating, waitForResponse } from '../../core/generation' -import { storage } from '../../core/storage' +import { findComposer, sendComposer, writeComposer, sendPrompt, isGenerating, waitForResponse, storage } from '../../platform' +import { readComposer } from '../../composer' import { ComposerButton } from '../../ui/composer-button' import { showToast } from '../../ui/toast' import { toggleShortcutDialog } from '../command-palette/dialog' @@ -29,7 +27,7 @@ const deps: RunnerDeps = { onSent: (text) => recordPrompt(text) } -export class PromptQueueModule extends Feature { +export class PromptQueueFeature extends Feature { readonly id = 'prompt-queue' readonly name = 'Message Queue' readonly description = 'Queue follow-up messages while an answer is generating; they send one by one when it finishes.' diff --git a/ai/perplexity/src/modules/prompt-queue/panel.ts b/core/ai/src/features/prompt-queue/panel.ts similarity index 98% rename from ai/perplexity/src/modules/prompt-queue/panel.ts rename to core/ai/src/features/prompt-queue/panel.ts index 02adc77..014848d 100644 --- a/ai/perplexity/src/modules/prompt-queue/panel.ts +++ b/core/ai/src/features/prompt-queue/panel.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { storage } from '../../core/storage' +import { markUi } from '../../ui/config' +import { storage } from '../../platform' import { createButton } from '../../ui/controls' import { createIcon } from '../../ui/icons' import { ensureUiStyles } from '../../ui/styles' diff --git a/ai/perplexity/src/modules/prompt-queue/queue.ts b/core/ai/src/features/prompt-queue/queue.ts similarity index 90% rename from ai/perplexity/src/modules/prompt-queue/queue.ts rename to core/ai/src/features/prompt-queue/queue.ts index 4bb9941..1eecdac 100644 --- a/ai/perplexity/src/modules/prompt-queue/queue.ts +++ b/core/ai/src/features/prompt-queue/queue.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage, lazy, platform } from '../../platform' export interface KeyValueStore { get(key: string, fallback: T): T @@ -13,12 +13,11 @@ export interface QueueItem { } const KEY = 'prompt-queue:items' -const ROOT_PATH = /^\/(?:computer|spaces|library|discover)?\/?$/ export const MAX_ITEMS = 50 export const MAX_AGE = 24 * 3_600_000 -export const threadOf = (pathname: string): string | null => (ROOT_PATH.test(pathname) ? null : pathname) +export const threadOf = (pathname: string): string | null => platform().threadOf(pathname) export class PromptQueue { private items: QueueItem[] @@ -104,4 +103,4 @@ export class PromptQueue { } } -export const promptQueue = new PromptQueue() +export const promptQueue = lazy(() => new PromptQueue()) diff --git a/ai/perplexity/src/modules/prompt-queue/runner.ts b/core/ai/src/features/prompt-queue/runner.ts similarity index 100% rename from ai/perplexity/src/modules/prompt-queue/runner.ts rename to core/ai/src/features/prompt-queue/runner.ts diff --git a/ai/perplexity/src/modules/prompt-queue/shortcut.ts b/core/ai/src/features/prompt-queue/shortcut.ts similarity index 89% rename from ai/perplexity/src/modules/prompt-queue/shortcut.ts rename to core/ai/src/features/prompt-queue/shortcut.ts index 91cdfd8..f1b001c 100644 --- a/ai/perplexity/src/modules/prompt-queue/shortcut.ts +++ b/core/ai/src/features/prompt-queue/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export const QUEUE_SHORTCUT_KEY = 'prompt-queue:shortcut' diff --git a/ai/perplexity/src/modules/prompt-queue/styles.ts b/core/ai/src/features/prompt-queue/styles.ts similarity index 94% rename from ai/perplexity/src/modules/prompt-queue/styles.ts rename to core/ai/src/features/prompt-queue/styles.ts index df230bb..05de4ac 100644 --- a/ai/perplexity/src/modules/prompt-queue/styles.ts +++ b/core/ai/src/features/prompt-queue/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-queue { position: fixed; right: 20px; bottom: 112px; z-index: 100000; display: flex; flex-direction: column; width: 340px; max-width: calc(100vw - 40px); border: 1px solid var(--bp-border); border-radius: 12px; background: var(--bp-bg); color: var(--bp-fg); box-shadow: 0 12px 32px rgb(0 0 0 / 22%); font: 12px/1.45 ui-sans-serif, system-ui, sans-serif; } @@ -21,4 +22,4 @@ const CSS = ` .bp-queue[data-collapsed='true'] .bp-queue-head { padding-bottom: 8px; } ` -export const ensureQueueStyles = (): void => injectStyle('better-perplexity-queue-styles', CSS) +export const ensureQueueStyles = (): void => injectStyle(`${uiConfig().id}-queue-styles`, CSS) diff --git a/ai/perplexity/src/modules/recall/caret.ts b/core/ai/src/features/recall/caret.ts similarity index 100% rename from ai/perplexity/src/modules/recall/caret.ts rename to core/ai/src/features/recall/caret.ts diff --git a/ai/perplexity/src/modules/recall/cursor.ts b/core/ai/src/features/recall/cursor.ts similarity index 100% rename from ai/perplexity/src/modules/recall/cursor.ts rename to core/ai/src/features/recall/cursor.ts diff --git a/ai/perplexity/src/modules/recall/dialog.ts b/core/ai/src/features/recall/dialog.ts similarity index 95% rename from ai/perplexity/src/modules/recall/dialog.ts rename to core/ai/src/features/recall/dialog.ts index 01d4a92..7c1defa 100644 --- a/ai/perplexity/src/modules/recall/dialog.ts +++ b/core/ai/src/features/recall/dialog.ts @@ -1,13 +1,14 @@ import { createElement } from '@nolly/core' -import { copyText } from '../../core/clipboard' +import { copyText } from '../../clipboard' import { createDialog } from '../../ui/dialog' import { showToast } from '../../ui/toast' import { ensurePaletteStyles } from '../command-palette/styles' import { threadLabel, timeAgo } from './format' import type { HistoryEntry, HistoryFilter, HistoryStore } from './store' import { ensureRecallStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-recall' +const DIALOG_ID = (): string => `${uiConfig().id}-recall` const LIMIT = 100 const FILTERS: readonly { readonly id: HistoryFilter; readonly label: string }[] = [ @@ -33,14 +34,14 @@ const metaLine = (entry: HistoryEntry, now: number): string => { } export const toggleRecall = ({ store, insert, send, queue }: RecallActions): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() ensureRecallStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Recall', width: 680 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Recall', width: 680 }) ui.dialog.classList.add('bp-palette', 'bp-recall') const input = createElement('input', 'bp-palette-input') input.placeholder = 'Search the messages you sent…' diff --git a/ai/perplexity/src/modules/recall/format.ts b/core/ai/src/features/recall/format.ts similarity index 100% rename from ai/perplexity/src/modules/recall/format.ts rename to core/ai/src/features/recall/format.ts diff --git a/ai/perplexity/src/modules/recall/history.ts b/core/ai/src/features/recall/history.ts similarity index 84% rename from ai/perplexity/src/modules/recall/history.ts rename to core/ai/src/features/recall/history.ts index f54bdba..39d3632 100644 --- a/ai/perplexity/src/modules/recall/history.ts +++ b/core/ai/src/features/recall/history.ts @@ -1,9 +1,9 @@ -import { storage } from '../../core/storage' +import { storage, lazy } from '../../platform' import { threadOf } from '../prompt-queue/queue' import { loadRecallSettings } from './settings' import { HistoryStore } from './store' -export const history = new HistoryStore() +export const history = lazy(() => new HistoryStore()) export const recordPrompt = (text: string): void => { if (!storage.get('module:recall', true) || loadRecallSettings().paused) return diff --git a/ai/perplexity/src/modules/recall/index.ts b/core/ai/src/features/recall/index.ts similarity index 90% rename from ai/perplexity/src/modules/recall/index.ts rename to core/ai/src/features/recall/index.ts index d086299..68f2cb0 100644 --- a/ai/perplexity/src/modules/recall/index.ts +++ b/core/ai/src/features/recall/index.ts @@ -1,14 +1,12 @@ import { Feature, toElement, type MenuEntry, type ScriptContext } from '@nolly/core' -import { isAutomating } from '../../core/automation' -import { copyText } from '../../core/clipboard' -import { editableFrom, findComposer, isSendButton, readComposer, sendComposer, writeComposer } from '../../core/composer' -import { isOwnUi } from '../../core/dom' -import { saveFile } from '../../core/download' -import { fetchSpy } from '../../core/fetch-spy' -import { isAskRequest } from '../../core/requests' -import { storage } from '../../core/storage' +import { isAutomating } from '../../automation' +import { copyText } from '../../clipboard' +import { isSendButton, readComposer } from '../../composer' +import { saveFile } from '../../download' import { ComposerButton } from '../../ui/composer-button' import { showToast } from '../../ui/toast' +import { editableFrom, findComposer, sendComposer, writeComposer, platform, storage } from '../../platform' +import { isOwnUi, uiConfig } from '../../ui/config' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { promptQueue, threadOf } from '../prompt-queue/queue' @@ -19,7 +17,7 @@ import { history, recordPrompt } from './history' import { SendRecorder } from './recorder' import { DEFAULT_RECALL_SHORTCUT, loadRecallSettings, loadRecallShortcut, RECALL_SHORTCUT_KEY, saveRecallSettings } from './settings' -export class RecallModule extends Feature { +export class RecallFeature extends Feature { readonly id = 'recall' readonly name = 'Recall' readonly description = 'Searchable history of the messages you send, with one-key reuse and arrow-key recall.' @@ -45,9 +43,7 @@ export class RecallModule extends Feature { history.prune(loadRecallSettings().retentionDays) this.scope.listen(window, 'keydown', this.onKeydown as EventListener, { capture: true }) this.scope.listen(document, 'click', this.onClick as EventListener, { capture: true }) - this.scope.add(fetchSpy.subscribe(({ method, url }) => { - if (isAskRequest(method, url)) this.recorder.request() - })) + this.scope.add(platform().onSend(() => this.recorder.request())) this.scope.interval(() => this.recorder.tick(), 250) } @@ -63,7 +59,7 @@ export class RecallModule extends Feature { { id: 'pause', label: settings.paused ? 'Resume Recording' : 'Pause Recording', action: () => this.update({ paused: !settings.paused }) }, { id: 'arrows', label: `Turn Arrow-Key History ${settings.arrowHistory ? 'Off' : 'On'}`, action: () => this.update({ arrowHistory: !settings.arrowHistory }) }, { id: 'retention', label: 'Set History Retention…', action: () => this.setRetention() }, - { id: 'export', label: 'Export History…', action: () => saveFile('better-perplexity-history.json', history.exportJson(), 'application/json') }, + { id: 'export', label: 'Export History…', action: () => saveFile(`${uiConfig().id}-history.json`, history.exportJson(), 'application/json') }, { id: 'import', label: 'Import History…', action: () => this.importFile() }, { id: 'clear', label: 'Clear History…', action: () => this.clear() }, { id: 'shortcut', label: 'Configure Recall Shortcut', action: () => this.configure() } diff --git a/ai/perplexity/src/modules/recall/recorder.ts b/core/ai/src/features/recall/recorder.ts similarity index 100% rename from ai/perplexity/src/modules/recall/recorder.ts rename to core/ai/src/features/recall/recorder.ts diff --git a/ai/perplexity/src/modules/recall/settings.ts b/core/ai/src/features/recall/settings.ts similarity index 95% rename from ai/perplexity/src/modules/recall/settings.ts rename to core/ai/src/features/recall/settings.ts index 4dd4b89..eff5079 100644 --- a/ai/perplexity/src/modules/recall/settings.ts +++ b/core/ai/src/features/recall/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export interface RecallSettings { diff --git a/ai/perplexity/src/modules/recall/store.ts b/core/ai/src/features/recall/store.ts similarity index 96% rename from ai/perplexity/src/modules/recall/store.ts rename to core/ai/src/features/recall/store.ts index 9396db7..2078c0a 100644 --- a/ai/perplexity/src/modules/recall/store.ts +++ b/core/ai/src/features/recall/store.ts @@ -1,6 +1,7 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import { fuzzyScore } from '../command-palette/fuzzy' import type { KeyValueStore } from '../prompt-queue/queue' +import { uiConfig } from '../../ui/config' export interface ThreadRef { readonly path: string @@ -171,7 +172,7 @@ export class HistoryStore { } exportJson(): string { - return JSON.stringify({ app: 'better-perplexity', kind: 'recall', version: 1, exportedAt: new Date(this.now()).toISOString(), entries: [...this.entries.values()] }, null, 2) + return JSON.stringify({ app: uiConfig().id, kind: 'recall', version: 1, exportedAt: new Date(this.now()).toISOString(), entries: [...this.entries.values()] }, null, 2) } importJson(json: string): ImportResult { diff --git a/ai/perplexity/src/modules/recall/styles.ts b/core/ai/src/features/recall/styles.ts similarity index 91% rename from ai/perplexity/src/modules/recall/styles.ts rename to core/ai/src/features/recall/styles.ts index 50db0a5..9856775 100644 --- a/ai/perplexity/src/modules/recall/styles.ts +++ b/core/ai/src/features/recall/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-recall .bp-palette-list { max-height: 340px; } @@ -16,4 +17,4 @@ const CSS = ` .bp-recall-hint { padding: 8px 14px; border-top: 1px solid var(--bp-border); color: var(--bp-muted); font-size: 11px; } ` -export const ensureRecallStyles = (): void => injectStyle('better-perplexity-recall-styles', CSS) +export const ensureRecallStyles = (): void => injectStyle(`${uiConfig().id}-recall-styles`, CSS) diff --git a/ai/perplexity/src/modules/selection-toolbar/index.ts b/core/ai/src/features/selection-toolbar/index.ts similarity index 93% rename from ai/perplexity/src/modules/selection-toolbar/index.ts rename to core/ai/src/features/selection-toolbar/index.ts index 4371259..ffd3188 100644 --- a/ai/perplexity/src/modules/selection-toolbar/index.ts +++ b/core/ai/src/features/selection-toolbar/index.ts @@ -1,9 +1,10 @@ -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' -import { createElement, Feature, injectStyle, type MenuEntry } from '@nolly/core' -import { isOwnUi, markUi } from '../../core/dom' -import { rememberSelection } from '../../core/selection' +import { findComposer, sendComposer, writeComposer } from '../../platform' +import { readComposer } from '../../composer' +import { rememberSelection } from '../../selection' import { ensureUiStyles } from '../../ui/styles' import { askFields } from '../../ui/placeholder-dialog' +import { createElement, Feature, injectStyle, type MenuEntry } from '@nolly/core' +import { isOwnUi, markUi, uiConfig } from '../../ui/config' interface Action { id: string @@ -38,7 +39,7 @@ const ACTIONS: readonly Action[] = [ { id: 'quote', label: 'Quote', title: 'Quote in the message box', compose: async (selected) => `${quote(selected)}\n\n` } ] -export class SelectionToolbarModule extends Feature { +export class SelectionToolbarFeature extends Feature { readonly id = 'selection-toolbar' readonly name = 'Selection Toolbar' readonly description = 'Ask, explain, summarize or quote any selected text.' @@ -50,7 +51,7 @@ export class SelectionToolbarModule extends Feature { constructor(context: ConstructorParameters[0]) { super(context) ensureUiStyles() - injectStyle('better-perplexity-selection-styles', CSS) + injectStyle(`${uiConfig().id}-selection-styles`, CSS) for (const action of ACTIONS) { const button = createElement('button', undefined, action.label) button.type = 'button' diff --git a/ai/perplexity/src/modules/updates/index.ts b/core/ai/src/features/updates/index.ts similarity index 66% rename from ai/perplexity/src/modules/updates/index.ts rename to core/ai/src/features/updates/index.ts index dfcba75..a15e773 100644 --- a/ai/perplexity/src/modules/updates/index.ts +++ b/core/ai/src/features/updates/index.ts @@ -1,14 +1,14 @@ -import { Feature, Updater, type MenuEntry } from '@nolly/core' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { URLS } from '../../repo' +import { Feature, Updater } from '@nolly/core' +import type { MenuEntry } from '@nolly/core' +import { logger, platform, storage } from '../../platform' import { showToast } from '../../ui/toast' -export { isNewerVersion as isNewer } from '@nolly/core' - -const releaseUrl = (version: string): string => `${URLS.releases}/tag/better-perplexity-v${version}` +const releaseUrl = (version: string): string => { + const { releasesUrl, slug } = platform().release + return `${releasesUrl}/tag/${slug}-v${version}` +} -export class UpdatesModule extends Feature { +export class UpdatesFeature extends Feature { readonly id = 'updates' readonly name = 'Update Checker' readonly description = 'Checks for new versions on load and every few minutes, and tells you once per version.' @@ -16,8 +16,8 @@ export class UpdatesModule extends Feature { private dismissToast: (() => void) | null = null private readonly updater = new Updater({ - metaUrl: URLS.meta, - current: __VERSION__, + metaUrl: platform().release.metaUrl, + current: platform().release.version, storage, logger, namespace: 'updates', @@ -36,10 +36,12 @@ export class UpdatesModule extends Feature { const entries: MenuEntry[] = [] const pending = this.updater.pending const available = this.updater.available - if (pending) entries.push({ id: 'install', label: `Update to v${pending}`, action: () => window.open(URLS.install, '_blank') }) + if (pending) entries.push({ id: 'install', label: `Update to v${pending}`, action: () => window.open(platform().release.installUrl, '_blank') }) if (available && available === this.updater.skipped) { entries.push({ - id: 'unskip', label: `Show Update v${available} Again`, action: () => { + id: 'unskip', + label: `Show Update v${available} Again`, + action: () => { this.updater.unskip() void this.check(true) } @@ -52,14 +54,15 @@ export class UpdatesModule extends Feature { private async check(manual: boolean): Promise { const result = await this.updater.check(manual) if (!manual) return - if (result === 'current') showToast(`You are up to date (v${__VERSION__}).`) + if (result === 'current') showToast(`You are up to date (v${platform().release.version}).`) else if (result === 'failed') showToast('Could not check for updates. Try again later.') } private announce(version: string, current: string): void { this.closeToast() - this.dismissToast = showToast(`Better Perplexity v${version} is available (you have v${current}).`, [ - { label: 'Update', primary: true, onClick: () => window.open(URLS.install, '_blank') }, + const { name, installUrl } = platform().release + this.dismissToast = showToast(`${name} v${version} is available (you have v${current}).`, [ + { label: 'Update', primary: true, onClick: () => window.open(installUrl, '_blank') }, { label: 'What’s new', keepOpen: true, onClick: () => window.open(releaseUrl(version), '_blank') }, { label: 'Skip this version', onClick: () => this.updater.skip(version) } ], 0) diff --git a/core/ai/src/index.ts b/core/ai/src/index.ts index c01cd0b..c90f7ba 100644 --- a/core/ai/src/index.ts +++ b/core/ai/src/index.ts @@ -1,6 +1,17 @@ export * from './adapter' +export * from './automation' +export * from './clipboard' export * from './composer' +export * from './download' +export * from './features' export * from './generation' export * from './keys' +export * from './placeholders' +export { configurePlatform, lazy } from './platform' +export type { Platform } from './platform' +export * from './prompt' export * from './response-spy' +export * from './selection' export * from './sse' +export * from './tokens' +export * from './ui' diff --git a/core/ai/src/keys.ts b/core/ai/src/keys.ts index f489fb6..2d35330 100644 --- a/core/ai/src/keys.ts +++ b/core/ai/src/keys.ts @@ -6,17 +6,17 @@ const synthetic = new WeakSet() export const isSynthetic = (event: Event): boolean => synthetic.has(event) export const dispatchEnter = (target: HTMLElement, shiftKey: boolean): boolean => { - const event = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, shiftKey, bubbles: true, cancelable: true, composed: true }) - synthetic.add(event) - return target.dispatchEvent(event) + const event = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, shiftKey, bubbles: true, cancelable: true, composed: true }) + synthetic.add(event) + return target.dispatchEvent(event) } -export const findGenericSendButton = (from: HTMLElement): HTMLButtonElement | null => { - let scope: HTMLElement | null = from - for (let depth = 0; scope && depth < MAX_SEARCH_DEPTH; depth++) { - const button = scope.querySelector(SEND_SELECTOR) - if (button && !button.disabled) return button - scope = scope.parentElement - } - return null +export const findSendButton = (from: HTMLElement): HTMLButtonElement | null => { + let scope: HTMLElement | null = from + for (let depth = 0; scope && depth < MAX_SEARCH_DEPTH; depth++) { + const button = scope.querySelector(SEND_SELECTOR) + if (button && !button.disabled) return button + scope = scope.parentElement + } + return null } diff --git a/ai/perplexity/src/core/placeholders.ts b/core/ai/src/placeholders.ts similarity index 94% rename from ai/perplexity/src/core/placeholders.ts rename to core/ai/src/placeholders.ts index 59d5cdd..75f06af 100644 --- a/ai/perplexity/src/core/placeholders.ts +++ b/core/ai/src/placeholders.ts @@ -23,4 +23,4 @@ export const findFields = (text: string, isResolved: (key: string) => boolean): return fields } -export const applyValues = (text: string, values: Readonly>): string => text.replace(TOKEN, (match, key: string) => (key in values ? (values[key] ?? '') : match)) \ No newline at end of file +export const applyValues = (text: string, values: Readonly>): string => text.replace(TOKEN, (match, key: string) => (key in values ? (values[key] ?? '') : match)) diff --git a/core/ai/src/platform.ts b/core/ai/src/platform.ts new file mode 100644 index 0000000..46db337 --- /dev/null +++ b/core/ai/src/platform.ts @@ -0,0 +1,66 @@ +import type { Logger, ScriptStorage } from '@nolly/core' +import type { ComposerKit } from './composer' +import type { GenerationKit } from './generation' +import type { PromptSender } from './prompt' +import type { ExportSource } from './features/exporter/source' + +export interface ReleaseInfo { + readonly name: string + readonly slug: string + readonly version: string + readonly metaUrl: string + readonly installUrl: string + readonly releasesUrl: string +} + +export interface Platform { + readonly id: string + readonly storage: ScriptStorage + readonly logger: Logger + readonly composer: ComposerKit + readonly generation: GenerationKit + readonly sendPrompt: PromptSender + readonly onSend: (listener: () => void) => () => void + readonly threadOf: (pathname: string) => string | null + readonly promptsUrl: string + readonly exporter: ExportSource + readonly release: ReleaseInfo + readonly codeBlockRoot?: (pre: HTMLElement) => HTMLElement | null +} + +let current: Platform | null = null + +export const configurePlatform = (platform: Platform): void => { + current = platform +} + +export const platform = (): Platform => { + if (!current) throw new Error('configurePlatform() must run before platform features are used.') + return current +} + +export const lazy = (create: () => T): T => { + let instance: T | null = null + const resolve = (): T => (instance ??= create()) + return new Proxy({} as T, { + get: (_target, key) => { + const target = resolve() + const value: unknown = Reflect.get(target, key, target) + return typeof value === 'function' ? value.bind(target) : value + }, + set: (_target, key, value) => Reflect.set(resolve(), key, value), + has: (_target, key) => Reflect.has(resolve(), key) + }) +} + +export const storage: ScriptStorage = lazy(() => platform().storage) +export const logger: Logger = lazy(() => platform().logger) + +export const findComposer: ComposerKit['findComposer'] = () => platform().composer.findComposer() +export const writeComposer: ComposerKit['writeComposer'] = (editable, text) => platform().composer.writeComposer(editable, text) +export const sendComposer: ComposerKit['sendComposer'] = (editable) => platform().composer.sendComposer(editable) +export const editableFrom: ComposerKit['editableFrom'] = (target) => platform().composer.editableFrom(target) +export const attachFile: ComposerKit['attachFile'] = (editable, file) => platform().composer.attachFile(editable, file) +export const isGenerating: GenerationKit['isGenerating'] = () => platform().generation.isGenerating() +export const waitForResponse: GenerationKit['waitForResponse'] = (options) => platform().generation.waitForResponse(options) +export const sendPrompt: PromptSender = (prompt, signal) => platform().sendPrompt(prompt, signal) diff --git a/core/ai/src/prompt.ts b/core/ai/src/prompt.ts new file mode 100644 index 0000000..17f8247 --- /dev/null +++ b/core/ai/src/prompt.ts @@ -0,0 +1,17 @@ +import { sleep, waitFor } from '@nolly/core' +import { automate } from './automation' +import { readComposer } from './composer' +import type { ComposerKit } from './composer' + +export type PromptSender = (prompt: string, signal?: AbortSignal) => Promise + +export const createPromptSender = ({ findComposer, writeComposer, sendComposer }: Pick): PromptSender => (prompt, signal) => automate(async () => { + for (let attempt = 0; attempt < 2; attempt++) { + const composer = await waitFor(findComposer, { timeout: 15_000, signal }) + if (!composer) return false + if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true + if (readComposer(composer).trim() === '') return true + await sleep(1_500, signal) + } + return false +}) diff --git a/ai/perplexity/src/core/selection.ts b/core/ai/src/selection.ts similarity index 84% rename from ai/perplexity/src/core/selection.ts rename to core/ai/src/selection.ts index 79e2d36..fdaacce 100644 --- a/ai/perplexity/src/core/selection.ts +++ b/core/ai/src/selection.ts @@ -4,4 +4,4 @@ export const rememberSelection = (text: string): void => { if (text.trim()) recent = text } -export const currentSelection = (): string => window.getSelection()?.toString().trim() || recent \ No newline at end of file +export const currentSelection = (): string => window.getSelection()?.toString().trim() || recent diff --git a/ai/perplexity/src/core/tokens.ts b/core/ai/src/tokens.ts similarity index 99% rename from ai/perplexity/src/core/tokens.ts rename to core/ai/src/tokens.ts index bebb013..5c5ba67 100644 --- a/ai/perplexity/src/core/tokens.ts +++ b/core/ai/src/tokens.ts @@ -10,4 +10,4 @@ export const estimateTokens = (text: string, asCode = false): number => { }) const wide = prose.match(WIDE)?.length ?? 0 return Math.ceil((prose.length - wide) / 4 + wide + code / 3.2) -} \ No newline at end of file +} diff --git a/ai/perplexity/src/ui/composer-button.ts b/core/ai/src/ui/composer-button.ts similarity index 89% rename from ai/perplexity/src/ui/composer-button.ts rename to core/ai/src/ui/composer-button.ts index 141e8c3..7417ad1 100644 --- a/ai/perplexity/src/ui/composer-button.ts +++ b/core/ai/src/ui/composer-button.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' -import { findComposerActions } from '../locate' +import { markUi, uiConfig } from './config' +import type { ComposerActions } from './config' import { createIcon, type IconName } from './icons' import { ensureUiStyles } from './styles' import { Tooltip } from './tooltip' @@ -11,6 +11,7 @@ export interface ComposerButtonOptions { } const CONFIG_BUTTON = '.bp-config-button' +const NO_ACTIONS: ComposerActions = { first: null, submit: null } export class ComposerButton { readonly element = markUi(createElement('button')) @@ -32,7 +33,7 @@ export class ComposerButton { } mount(): void { - const { first, submit } = findComposerActions() + const { first, submit } = uiConfig().composerActions?.() ?? NO_ACTIONS const chained = (this.options.after ?? []).map((id) => document.querySelector(`.bp-cb-${id}`)).find(Boolean) const anchor = chained ?? document.querySelector(CONFIG_BUTTON) ?? first if (!anchor && !submit) { diff --git a/core/ai/src/ui/config.ts b/core/ai/src/ui/config.ts new file mode 100644 index 0000000..5628da1 --- /dev/null +++ b/core/ai/src/ui/config.ts @@ -0,0 +1,31 @@ +import type { createUiMarker } from '@nolly/core' + +export type UiMarker = ReturnType + +export interface ComposerActions { + readonly first: HTMLElement | null + readonly submit: HTMLElement | null +} + +export interface UiConfig { + readonly id: string + readonly title: string + readonly version: string + readonly marker: UiMarker + readonly composerActions?: () => ComposerActions +} + +let current: UiConfig | null = null + +export const configureUi = (config: UiConfig): void => { + current = config +} + +export const uiConfig = (): UiConfig => { + if (!current) throw new Error('configureUi() must run before any UI is created.') + return current +} + +export const markUi: UiMarker['mark'] = (element) => uiConfig().marker.mark(element) + +export const isOwnUi: UiMarker['isOwn'] = (node) => uiConfig().marker.isOwn(node) diff --git a/core/ai/src/ui/controls.ts b/core/ai/src/ui/controls.ts new file mode 100644 index 0000000..5a74988 --- /dev/null +++ b/core/ai/src/ui/controls.ts @@ -0,0 +1,104 @@ +import { createElement } from '@nolly/core' + +export interface ButtonOptions { + primary?: boolean + onClick?: (event: MouseEvent) => void +} + +export interface SwitchOptions { + label: string + hint?: string + checked: boolean + onChange: (checked: boolean) => void +} + +export interface NumberFieldOptions { + label: string + hint?: string + value: number + min?: number + max?: number + step?: number + onChange: (value: number) => void +} + +export const createButton = (label: string, { primary = false, onClick }: ButtonOptions = {}): HTMLButtonElement => { + const button = createElement('button', primary ? 'bp-button bp-button-primary' : 'bp-button', label) + button.type = 'button' + if (onClick) button.addEventListener('click', onClick) + return button +} + +export const createSwitch = ({ label, hint, checked, onChange }: SwitchOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { + const wrapper = createElement('label', 'bp-switch') + const text = createElement('span', 'bp-switch-text') + text.appendChild(createElement('span', undefined, label)) + if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) + const input = createElement('input') + input.type = 'checkbox' + input.checked = checked + input.addEventListener('change', () => onChange(input.checked)) + wrapper.append(text, input, createElement('span', 'bp-switch-track')) + return { wrapper, input } +} + +export const createSection = (title: string, aside?: string): HTMLElement => { + const section = createElement('section', 'bp-section') + const heading = createElement('h3', 'bp-section-heading') + heading.appendChild(createElement('span', undefined, title)) + if (aside !== undefined) heading.appendChild(createElement('span', undefined, aside)) + section.appendChild(heading) + return section +} + +export const createDataRow = (label: string, value: string, className = ''): HTMLElement => { + const row = createElement('div', 'bp-data-row') + row.append(createElement('span', 'bp-data-label', label), createElement('span', `bp-data-value ${className}`.trim(), value)) + return row +} + +export const createNumberField = ({ label, hint, value, min, max, step = 1, onChange }: NumberFieldOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { + const wrapper = createElement('label', 'bp-field') + const text = createElement('span', 'bp-switch-text') + text.appendChild(createElement('span', undefined, label)) + if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) + const input = createElement('input', 'bp-input') + input.type = 'number' + input.value = String(value) + input.step = String(step) + if (min !== undefined) input.min = String(min) + if (max !== undefined) input.max = String(max) + input.addEventListener('change', () => { + const parsed = Number(input.value) + if (!Number.isFinite(parsed)) return + const clamped = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, parsed)) + input.value = String(clamped) + onChange(clamped) + }) + wrapper.append(text, input) + return { wrapper, input } +} + +export const createSelectField = (label: string, options: readonly { value: T; label: string }[], value: T, onChange: (value: T) => void): HTMLLabelElement => { + const wrapper = createElement('label', 'bp-field') + wrapper.appendChild(createElement('span', undefined, label)) + const select = createElement('select', 'bp-input') + for (const option of options) { + const element = createElement('option', undefined, option.label) + element.value = option.value + select.appendChild(element) + } + select.value = value + select.addEventListener('change', () => onChange(select.value as T)) + wrapper.appendChild(select) + return wrapper +} + +export const createTextArea = (placeholder: string, value: string, onInput: (value: string) => void): HTMLTextAreaElement => { + const area = createElement('textarea', 'bp-input') + area.placeholder = placeholder + area.value = value + area.rows = 3 + area.addEventListener('input', () => onInput(area.value)) + return area +} diff --git a/ai/perplexity/src/ui/css/controls.ts b/core/ai/src/ui/css.ts similarity index 58% rename from ai/perplexity/src/ui/css/controls.ts rename to core/ai/src/ui/css.ts index a2a66a0..bd57c71 100644 --- a/ai/perplexity/src/ui/css/controls.ts +++ b/core/ai/src/ui/css.ts @@ -1,3 +1,108 @@ +export const THEME_CSS = ` +.bp-themed { + --bp-bg: hsl(0 0% 100%); + --bp-fg: hsl(240 10% 3.9%); + --bp-muted: hsl(240 3.8% 46.1%); + --bp-border: hsl(240 5.9% 90%); + --bp-accent: hsl(240 4.8% 95.9%); + --bp-track: hsl(240 5% 78%); + --bp-ring: hsl(240 5% 64.9%); + --bp-green: hsl(142 71% 40%); + --bp-yellow: hsl(38 92% 45%); + --bp-red: hsl(0 84% 55%); +} + +@media (prefers-color-scheme: dark) { + .bp-themed { + --bp-bg: hsl(240 10% 5%); + --bp-fg: hsl(0 0% 98%); + --bp-muted: hsl(240 5% 64.9%); + --bp-border: hsl(240 3.7% 17%); + --bp-accent: hsl(240 3.7% 13%); + --bp-track: hsl(240 3.7% 28%); + --bp-green: hsl(142 71% 45%); + --bp-yellow: hsl(38 92% 50%); + --bp-red: hsl(0 84% 60%); + } +} +` + +export const DIALOG_CSS = ` +.bp-dialog { + width: min(var(--bp-width, 560px), calc(100vw - 32px)); + max-width: none; + max-height: min(86vh, 820px); + padding: 0; + overflow: hidden; + border: 1px solid var(--bp-border); + border-radius: 14px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 24px 60px -12px rgb(0 0 0 / 35%); + font-family: inherit; + font-size: 13px; + line-height: 1.5; +} + +.bp-dialog[open] { display: flex; flex-direction: column; animation: bp-dialog-in 160ms ease-out; } +.bp-dialog::backdrop { background: rgb(0 0 0 / 55%); backdrop-filter: blur(6px); animation: bp-fade-in 160ms ease-out; } +.bp-dialog *, .bp-dialog *::before, .bp-dialog *::after { box-sizing: border-box; } + +@keyframes bp-dialog-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } } +@keyframes bp-fade-in { from { opacity: 0; } to { opacity: 1; } } + +@media (prefers-reduced-motion: reduce) { + .bp-dialog[open], .bp-dialog::backdrop { animation: none; } +} + +.bp-dialog-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + padding: 18px 20px 14px; + border-bottom: 1px solid var(--bp-border); +} + +.bp-dialog-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -.02em; } +.bp-dialog-description { margin: 3px 0 0; color: var(--bp-muted); font-size: 12px; } +.bp-dialog-body { flex: 1; min-height: 0; padding: 16px 20px; overflow-y: auto; overscroll-behavior: contain; } + +.bp-dialog-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 12px 20px; + border-top: 1px solid var(--bp-border); +} + +.bp-dialog-footer:empty { display: none; } + +.bp-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 28px; + height: 28px; + border: 0; + border-radius: 7px; + background: transparent; + color: var(--bp-muted); + font: inherit; + font-size: 18px; + line-height: 1; + cursor: pointer; +} + +.bp-icon-button:hover { background: var(--bp-accent); color: var(--bp-fg); } + +@media (max-width: 520px) { + .bp-dialog-header, .bp-dialog-body, .bp-dialog-footer { padding-right: 14px; padding-left: 14px; } +} +` + export const CONTROLS_CSS = ` .bp-button { display: inline-flex; @@ -41,6 +146,7 @@ export const CONTROLS_CSS = ` } .bp-hint { margin: 12px 0 0; color: var(--bp-muted); font-size: 12px; } +.bp-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 2px; } .bp-switch { position: relative; @@ -179,4 +285,35 @@ textarea.bp-input { width: 100%; min-height: 64px; resize: vertical; font-family .bp-header-btn:hover { background: var(--bp-accent); } .bp-header-btn:focus-visible { outline: 2px solid var(--bp-fg); outline-offset: 2px; } -` \ No newline at end of file +` + +export const TOOLTIP_CSS = ` +.bp-tooltip { + position: fixed; + inset: auto; + width: max-content; + max-width: min(300px, calc(100vw - 16px)); + margin: 0; + padding: 0; + overflow: visible; + border: 1px solid var(--bp-border); + border-radius: 12px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 12px 32px rgb(0 0 0 / 22%); + font: inherit; + font-size: 12px; + line-height: 1.5; + pointer-events: none; +} + +.bp-tooltip:popover-open { animation: bp-tooltip-in 120ms ease-out; } +.bp-tooltip *, .bp-tooltip *::before, .bp-tooltip *::after { box-sizing: border-box; } +.bp-tooltip-body { padding: 12px 14px; } + +@keyframes bp-tooltip-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } } + +@media (prefers-reduced-motion: reduce) { + .bp-tooltip:popover-open { animation: none; } +} +` diff --git a/ai/perplexity/src/ui/dialog.ts b/core/ai/src/ui/dialog.ts similarity index 97% rename from ai/perplexity/src/ui/dialog.ts rename to core/ai/src/ui/dialog.ts index 5889478..33f1ee5 100644 --- a/ai/perplexity/src/ui/dialog.ts +++ b/core/ai/src/ui/dialog.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi } from './config' import { ensureUiStyles } from './styles' export interface DialogOptions { @@ -44,4 +44,4 @@ export const createDialog = ({ id, title, description, width = 560 }: DialogOpti dialog.showModal() } return { dialog, body, footer, close, show } -} \ No newline at end of file +} diff --git a/core/ai/src/ui/icons.ts b/core/ai/src/ui/icons.ts new file mode 100644 index 0000000..9c15751 --- /dev/null +++ b/core/ai/src/ui/icons.ts @@ -0,0 +1,33 @@ +type Shape = readonly [tag: string, attributes: Readonly>] + +const ICONS = { + copy: [['rect', { x: '9', y: '9', width: '13', height: '13', rx: '2' }], ['path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }]], + check: [['polyline', { points: '20 6 9 17 4 12' }]], + download: [['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }], ['polyline', { points: '7 10 12 15 17 10' }], ['line', { x1: '12', y1: '15', x2: '12', y2: '3' }]], + wrap: [['line', { x1: '3', y1: '6', x2: '21', y2: '6' }], ['path', { d: 'M3 12h15a3 3 0 1 1 0 6h-4' }], ['polyline', { points: '16 16 14 18 16 20' }], ['line', { x1: '3', y1: '18', x2: '10', y2: '18' }]], + lines: [['line', { x1: '10', y1: '6', x2: '21', y2: '6' }], ['line', { x1: '10', y1: '12', x2: '21', y2: '12' }], ['line', { x1: '10', y1: '18', x2: '21', y2: '18' }], ['path', { d: 'M4 6h1v4' }], ['path', { d: 'M4 10h2' }], ['path', { d: 'M6 18H4c0-1 2-2 2-3s-1-1.5-2-1' }]], + fold: [['polyline', { points: '7 20 12 15 17 20' }], ['polyline', { points: '7 4 12 9 17 4' }]], + file: [['path', { d: 'M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z' }], ['polyline', { points: '14 2 14 8 20 8' }], ['line', { x1: '16', y1: '13', x2: '8', y2: '13' }], ['line', { x1: '16', y1: '17', x2: '8', y2: '17' }]], + sliders: [['line', { x1: '21', y1: '4', x2: '14', y2: '4' }], ['line', { x1: '10', y1: '4', x2: '3', y2: '4' }], ['line', { x1: '21', y1: '12', x2: '12', y2: '12' }], ['line', { x1: '8', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '21', y1: '20', x2: '16', y2: '20' }], ['line', { x1: '12', y1: '20', x2: '3', y2: '20' }], ['line', { x1: '14', y1: '2', x2: '14', y2: '6' }], ['line', { x1: '8', y1: '10', x2: '8', y2: '14' }], ['line', { x1: '16', y1: '18', x2: '16', y2: '22' }]], + book: [['path', { d: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20' }]], + layers: [['polygon', { points: '12 2 2 7 12 12 22 7 12 2' }], ['polyline', { points: '2 17 12 22 22 17' }], ['polyline', { points: '2 12 12 17 22 12' }]], + help: [['circle', { cx: '12', cy: '12', r: '10' }], ['path', { d: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3' }], ['line', { x1: '12', y1: '17', x2: '12.01', y2: '17' }]], + clock: [['circle', { cx: '12', cy: '12', r: '10' }], ['polyline', { points: '12 6 12 12 16 14' }]], + queue: [['line', { x1: '11', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '16', y1: '6', x2: '3', y2: '6' }], ['line', { x1: '16', y1: '18', x2: '3', y2: '18' }], ['line', { x1: '18', y1: '9', x2: '18', y2: '15' }], ['line', { x1: '21', y1: '12', x2: '15', y2: '12' }]] +} as const satisfies Record + +export type IconName = keyof typeof ICONS + +const NS = 'http://www.w3.org/2000/svg' + +export const createIcon = (name: IconName, size = 16): SVGSVGElement => { + const svg = document.createElementNS(NS, 'svg') + const attributes = { width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' } + for (const [key, value] of Object.entries(attributes)) svg.setAttribute(key, value) + for (const [tag, props] of ICONS[name] as readonly Shape[]) { + const element = document.createElementNS(NS, tag) + for (const [key, value] of Object.entries(props)) element.setAttribute(key, value) + svg.appendChild(element) + } + return svg +} diff --git a/core/ai/src/ui/index.ts b/core/ai/src/ui/index.ts new file mode 100644 index 0000000..3031e7d --- /dev/null +++ b/core/ai/src/ui/index.ts @@ -0,0 +1,11 @@ +export * from './composer-button' +export * from './config' +export * from './controls' +export * from './css' +export * from './dialog' +export * from './icons' +export * from './placeholder-dialog' +export * from './settings-dialog' +export * from './styles' +export * from './toast' +export * from './tooltip' diff --git a/ai/perplexity/src/ui/placeholder-dialog.ts b/core/ai/src/ui/placeholder-dialog.ts similarity index 88% rename from ai/perplexity/src/ui/placeholder-dialog.ts rename to core/ai/src/ui/placeholder-dialog.ts index 089ec59..40c3def 100644 --- a/ai/perplexity/src/ui/placeholder-dialog.ts +++ b/core/ai/src/ui/placeholder-dialog.ts @@ -1,10 +1,9 @@ -import type { Field } from '../core/placeholders' import { createElement } from '@nolly/core' +import type { Field } from '../placeholders' +import { uiConfig } from './config' import { createButton } from './controls' import { createDialog } from './dialog' -const DIALOG_ID = 'better-perplexity-fields-dialog' - export interface AskOptions { title: string description: string @@ -12,8 +11,9 @@ export interface AskOptions { } export const askFields = (fields: readonly Field[], { title, description, confirm = 'Continue' }: AskOptions): Promise | null> => new Promise((resolve) => { - document.getElementById(DIALOG_ID)?.remove() - const ui = createDialog({ id: DIALOG_ID, title, description, width: 540 }) + const dialogId = `${uiConfig().id}-fields-dialog` + document.getElementById(dialogId)?.remove() + const ui = createDialog({ id: dialogId, title, description, width: 540 }) const values: Record = Object.fromEntries(fields.map((field) => [field.key, field.value ?? ''])) let settled = false const finish = (result: Record | null): void => { @@ -51,4 +51,4 @@ export const askFields = (fields: readonly Field[], { title, description, confir ui.footer.append(createButton('Cancel', { onClick: ui.close }), createButton(confirm, { primary: true, onClick: submit })) ui.show() first?.focus() -}) \ No newline at end of file +}) diff --git a/core/ai/src/ui/settings-dialog.ts b/core/ai/src/ui/settings-dialog.ts new file mode 100644 index 0000000..28334a7 --- /dev/null +++ b/core/ai/src/ui/settings-dialog.ts @@ -0,0 +1,62 @@ +import { createElement } from '@nolly/core' +import type { ScriptContext } from '@nolly/core' +import { uiConfig } from './config' +import { createButton, createSwitch } from './controls' +import { createDialog } from './dialog' + +type SettingsHost = Pick + +export const toggleSettingsDialog = (host: SettingsHost): void => { + const { id, title, version } = uiConfig() + const dialogId = `${id}-settings-dialog` + const existing = document.getElementById(dialogId) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + const ui = createDialog({ id: dialogId, title, description: `Version ${version}`, width: 560 }) + const render = (): void => { + ui.body.replaceChildren( + ...host.getFeatures().map((feature) => { + const section = createElement('section', 'bp-section') + section.appendChild( + createSwitch({ + label: feature.name, + hint: feature.description, + checked: feature.enabled, + onChange: () => { + feature.toggle() + render() + } + }).wrapper + ) + if (feature.enabled) { + const actions = createElement('div', 'bp-actions') + for (const entry of feature.menuEntries()) { + actions.appendChild( + createButton(entry.label, { + onClick: () => { + ui.close() + window.setTimeout(entry.action, 0) + } + }) + ) + } + if (actions.childElementCount) section.appendChild(actions) + } + return section + }) + ) + } + render() + ui.footer.append( + createButton('Command palette', { + onClick: () => { + ui.close() + window.setTimeout(() => host.runCommand('command-palette:open'), 0) + } + }), + createButton('Close', { primary: true, onClick: ui.close }) + ) + ui.show() +} diff --git a/core/ai/src/ui/styles.ts b/core/ai/src/ui/styles.ts new file mode 100644 index 0000000..fbca7f8 --- /dev/null +++ b/core/ai/src/ui/styles.ts @@ -0,0 +1,7 @@ +import { injectStyle } from '@nolly/core' +import { uiConfig } from './config' +import { CONTROLS_CSS, DIALOG_CSS, THEME_CSS, TOOLTIP_CSS } from './css' + +export const ensureUiStyles = (): void => { + injectStyle(`${uiConfig().id}-ui-base`, [THEME_CSS, DIALOG_CSS, CONTROLS_CSS, TOOLTIP_CSS].join('\n')) +} diff --git a/ai/perplexity/src/ui/toast.ts b/core/ai/src/ui/toast.ts similarity index 86% rename from ai/perplexity/src/ui/toast.ts rename to core/ai/src/ui/toast.ts index 49dcef0..303cd9e 100644 --- a/ai/perplexity/src/ui/toast.ts +++ b/core/ai/src/ui/toast.ts @@ -1,5 +1,5 @@ import { createElement, injectStyle } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi, uiConfig } from './config' import { createButton } from './controls' import { ensureUiStyles } from './styles' @@ -17,7 +17,7 @@ const CSS = ` export const showToast = (message: string, actions: readonly ToastAction[] = [], duration = 8_000): (() => void) => { ensureUiStyles() - injectStyle('better-perplexity-toast-styles', CSS) + injectStyle(`${uiConfig().id}-toast-styles`, CSS) const toast = markUi(createElement('div', 'bp-toast bp-themed')) const dismiss = (): void => toast.remove() toast.appendChild(createElement('div', undefined, message)) @@ -27,10 +27,10 @@ export const showToast = (message: string, actions: readonly ToastAction[] = [], row.appendChild( createButton(action.label, { primary: action.primary, - onClick: () => { - if (!action.keepOpen) dismiss() - action.onClick() - } + onClick: () => { + if (!action.keepOpen) dismiss() + action.onClick() + } }) ) } diff --git a/ai/perplexity/src/ui/tooltip.ts b/core/ai/src/ui/tooltip.ts similarity index 99% rename from ai/perplexity/src/ui/tooltip.ts rename to core/ai/src/ui/tooltip.ts index 8311bfc..f9a2d30 100644 --- a/ai/perplexity/src/ui/tooltip.ts +++ b/core/ai/src/ui/tooltip.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi } from './config' import { ensureUiStyles } from './styles' export type TooltipRenderer = (container: HTMLElement) => void @@ -119,4 +119,4 @@ export class Tooltip { this.element.style.left = `${Math.round(left)}px` this.element.style.top = `${Math.round(top)}px` } -} \ No newline at end of file +} diff --git a/core/docs/getting-started.md b/core/docs/getting-started.md index cc21944..6ccaa08 100644 --- a/core/docs/getting-started.md +++ b/core/docs/getting-started.md @@ -15,6 +15,8 @@ cd my-script bun run dev ``` +Pass a third argument to create it inside a parent folder, for example `ai`. The `cd` command goes to the created folder. + ## A feature ```ts import { Feature } from '@nolly/core' diff --git a/scripts/new-userscript.ts b/scripts/new-userscript.ts index 2e54892..6ce5e6f 100644 --- a/scripts/new-userscript.ts +++ b/scripts/new-userscript.ts @@ -2,57 +2,62 @@ import { existsSync } from 'node:fs' import { mkdir, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' -const [slug, name] = process.argv.slice(2) +const [slug, name, parent = ''] = process.argv.slice(2) if (!slug || !name || !/^[a-z0-9-]+$/.test(slug)) { - console.error('Usage: bun scripts/new-userscript.ts ""') - process.exit(1) + console.error('Usage: bun scripts/new-userscript.ts "" [parent-folder]') + process.exit(1) } -if (existsSync(slug)) { - console.error(`${slug}/ already exists.`) - process.exit(1) + +const dir = parent ? `${parent}/${slug}` : slug +const up = '../'.repeat(dir.split('/').length) + +if (existsSync(dir)) { + console.error(`${dir}/ already exists.`) + process.exit(1) } const files: Record = { - 'package.json': JSON.stringify({ - name: slug, - version: '0.1.0', - private: true, - type: 'module', - license: 'PolyForm-Strict-1.0.0', - repository: { type: 'git', url: 'git+https://github.com/thenolle/userscripts.git', directory: slug }, - scripts: { build: 'bun run scripts/build.ts', dev: 'bun run scripts/build.ts --watch', typecheck: 'tsc --noEmit' }, - dependencies: { '@nolly/core': 'workspace:*' }, - devDependencies: { '@types/bun': '^1.4.4', typescript: '^7.0.2' } - }, null, 2), - 'tsconfig.json': JSON.stringify({ - compilerOptions: { - lib: ['ESNext', 'DOM', 'DOM.Iterable'], types: ['bun'], module: 'preserve', target: 'esnext', moduleResolution: 'bundler', - verbatimModuleSyntax: true, isolatedModules: true, noEmit: true, strict: true, noImplicitOverride: true, skipLibCheck: true, - noUnusedLocals: true, noUnusedParameters: true, noPropertyAccessFromIndexSignature: true - }, - include: ['src', 'scripts', '../core/src/globals.d.ts'] - }, null, 2), - 'README.md': `# ${name}\n\nDescribe what ${name} does in one paragraph.\n\n## Install\n\nInstall from the project website once the first release is published.\n`, - 'CHANGELOG.md': `# Changelog\n\n## 0.1.0\n\n- Initial release.\n`, - 'docs/getting-started.md': `---\ntitle: Getting started\ndescription: Install ${name} and get going.\nsection: Guides\norder: 10\n---\n\n# Getting started\n\nWrite your guide here.\n`, - 'src/types/globals.d.ts': 'declare const __VERSION__: string\n', - 'src/repo.ts': `import { repoUrls } from '@nolly/core'\n\nexport const SLUG = '${slug}'\n\nexport const URLS = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG })\n`, - 'src/main.ts': `import { Userscript } from '@nolly/core'\nimport { Hello } from './features/hello'\n\nnew Userscript({ id: '${slug}', name: '${name}', version: __VERSION__ })\n .register((context) => new Hello(context))\n .start()\n`, - 'src/features/hello.ts': `import { Feature } from '@nolly/core'\n\nexport class Hello extends Feature {\n readonly id = 'hello'\n readonly name = 'Hello'\n readonly description = 'Example feature.'\n\n override onEnable(): void {\n this.context.logger.info('Hello enabled.')\n }\n\n run(): void {}\n}\n`, - 'scripts/header.ts': `import { createHeader as render } from '@nolly/core/build'\nimport { URLS } from '../src/repo'\n\nexport const createHeader = ({ version }: { version: string }): string =>\n render({\n name: '${name}',\n namespace: URLS.namespace,\n version,\n description: 'Describe ${name}.',\n author: 'Nolly',\n license: 'PolyForm-Strict-1.0.0',\n homepageURL: URLS.home,\n supportURL: URLS.issues,\n updateURL: URLS.meta,\n downloadURL: URLS.install,\n icon: 'https://www.google.com/s2/favicons?sz=64&domain=example.com',\n match: ['https://example.com/*'],\n noframes: true,\n grant: ['GM_getValue', 'GM_setValue', 'GM_deleteValue', 'GM_registerMenuCommand', 'GM_unregisterMenuCommand', 'GM_xmlhttpRequest', 'unsafeWindow']\n })\n`, - 'scripts/build.ts': `import { buildUserscript } from '@nolly/core/build'\nimport pkg from '../package.json' with { type: 'json' }\nimport { SLUG } from '../src/repo'\nimport { createHeader } from './header'\n\nawait buildUserscript({ slug: SLUG, version: pkg.version, header: createHeader({ version: pkg.version }) })\n` + 'package.json': JSON.stringify({ + name: slug, + version: '0.1.0', + private: true, + type: 'module', + license: 'PolyForm-Strict-1.0.0', + userscript: { slug }, + repository: { type: 'git', url: 'git+https://github.com/thenolle/userscripts.git', directory: dir }, + scripts: { build: 'bun run scripts/build.ts', dev: 'bun run scripts/build.ts --watch', typecheck: 'tsc --noEmit' }, + dependencies: { '@nolly/core': 'workspace:*' }, + devDependencies: { '@types/bun': '^1.4.4', typescript: '^7.0.2' } + }, null, 2), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + lib: ['ESNext', 'DOM', 'DOM.Iterable'], types: ['bun'], module: 'preserve', target: 'esnext', moduleResolution: 'bundler', resolveJsonModule: true, + verbatimModuleSyntax: true, isolatedModules: true, noEmit: true, strict: true, noImplicitOverride: true, skipLibCheck: true, + noUnusedLocals: true, noUnusedParameters: true, noPropertyAccessFromIndexSignature: true + }, + include: ['src', 'scripts', `${up}core/src/globals.d.ts`] + }, null, 2), + 'README.md': `# ${name}\n\nDescribe what ${name} does in one paragraph.\n\n## Install\n\nInstall from the project website once the first release is published.\n`, + 'CHANGELOG.md': `# Changelog\n\n## [0.1.0] - ${new Date().toISOString().slice(0, 10)}\n\n- Initial release.\n`, + 'docs/getting-started.md': `---\ntitle: Getting started\ndescription: Install ${name} and get going.\nsection: Guides\norder: 10\n---\n\n# Getting started\n\nWrite your guide here.\n`, + 'src/types/globals.d.ts': 'declare const __VERSION__: string\n', + 'src/repo.ts': `import { repoUrls } from '@nolly/core'\n\nexport const SLUG = '${slug}'\n\nexport const URLS = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG, dir: '${dir}' })\n`, + 'src/main.ts': `import { Userscript } from '@nolly/core'\nimport { Hello } from './features/hello'\n\nnew Userscript({ id: '${slug}', name: '${name}', version: __VERSION__ })\n .register((context) => new Hello(context))\n .start()\n`, + 'src/features/hello.ts': `import { Feature } from '@nolly/core'\n\nexport class Hello extends Feature {\n readonly id = 'hello'\n readonly name = 'Hello'\n readonly description = 'Example feature.'\n\n override onEnable(): void {\n this.context.logger.info('Hello enabled.')\n }\n\n run(): void {}\n}\n`, + 'scripts/header.ts': `import { createHeader as render } from '@nolly/core/build'\nimport { URLS } from '../src/repo'\n\nexport const createHeader = ({ version }: { version: string }): string =>\n render({\n name: '${name}',\n namespace: URLS.namespace,\n version,\n description: 'Describe ${name}.',\n author: 'Nolly',\n license: 'PolyForm-Strict-1.0.0',\n homepageURL: URLS.home,\n supportURL: URLS.issues,\n updateURL: URLS.meta,\n downloadURL: URLS.install,\n icon: 'https://www.google.com/s2/favicons?sz=64&domain=example.com',\n match: ['https://example.com/*'],\n noframes: true,\n grant: ['GM_getValue', 'GM_setValue', 'GM_deleteValue', 'GM_registerMenuCommand', 'GM_unregisterMenuCommand', 'GM_xmlhttpRequest', 'unsafeWindow']\n })\n`, + 'scripts/build.ts': `import { buildUserscript } from '@nolly/core/build'\nimport pkg from '../package.json' with { type: 'json' }\nimport { SLUG } from '../src/repo'\nimport { createHeader } from './header'\n\nawait buildUserscript({ slug: SLUG, version: pkg.version, header: createHeader({ version: pkg.version }) })\n` } for (const [path, content] of Object.entries(files)) { - const target = join(slug, path) - await mkdir(join(target, '..'), { recursive: true }) - await writeFile(target, content.endsWith('\n') ? content : `${content}\n`) + const target = join(dir, path) + await mkdir(join(target, '..'), { recursive: true }) + await writeFile(target, content.endsWith('\n') ? content : `${content}\n`) } const rootFile = JSON.parse(await readFile('package.json', 'utf8')) as { workspaces: string[] } -if (!rootFile.workspaces.includes(slug)) { - rootFile.workspaces.push(slug) - await writeFile('package.json', `${JSON.stringify(rootFile, null, 2)}\n`) +if (!rootFile.workspaces.includes(dir)) { + rootFile.workspaces.push(dir) + await writeFile('package.json', `${JSON.stringify(rootFile, null, 2)}\n`) } -console.log(`Created ${slug}/. Run: bun install && cd ${slug} && bun run dev`) +console.log(`Created ${dir}/. Run: bun install && cd ${dir} && bun run dev`)