From d43ed4e9d7a85360668ce912c4ee8a2500553e68 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 16:17:51 +0100 Subject: [PATCH] feat: Code Blocks V2; correct usage semantics and restore ChatGPT header interaction --- ai/chatgpt/CHANGELOG.md | 16 + ai/chatgpt/README.md | 38 ++- ai/chatgpt/docs/code-blocks-v2.md | 35 ++ ai/chatgpt/package.json | 2 +- ai/chatgpt/src/features/usage.ts | 158 +++++---- ai/chatgpt/src/header-tools.ts | 50 ++- ai/chatgpt/src/tours.ts | 21 +- ai/perplexity/CHANGELOG.md | 16 + ai/perplexity/README.md | 36 +- ai/perplexity/docs/code-blocks-v2.md | 35 ++ ai/perplexity/package.json | 2 +- .../src/modules/usage-status/caps.ts | 22 +- .../src/modules/usage-status/definitions.ts | 10 +- .../src/modules/usage-status/plan.ts | 2 +- .../src/modules/usage-status/service.ts | 21 +- ai/perplexity/src/tours.ts | 21 +- bun.lock | 4 +- core/ai/CHANGELOG.md | 5 + core/ai/src/features/code-blocks/block.ts | 317 +++++++++--------- core/ai/src/features/code-blocks/dialog.ts | 2 +- core/ai/src/features/code-blocks/index.ts | 180 +++++----- core/ai/src/features/code-blocks/styles.ts | 212 ++++++------ core/ai/src/ui/css.ts | 26 ++ 23 files changed, 694 insertions(+), 537 deletions(-) create mode 100644 ai/chatgpt/docs/code-blocks-v2.md create mode 100644 ai/perplexity/docs/code-blocks-v2.md diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index 4f351db..3ef73fc 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [1.2.0] - 2026-11-10 + +### Changed + +- Renamed Code Block Pro to Code Blocks V2. +- Rebuilt code selection around actual newline text nodes and source-faithful content. +- Added restrained toolbar styling, explicit folding, and a non-selectable line-number gutter. +- Improved shared dialog spacing and form styling. + +### Fixed + +- Removed unverified usage totals and misleading quota interpretations. +- ChatGPT header tools explicitly restore pointer interaction and reattach to the visible native row. +- Expired ChatGPT tool counters are labelled as awaiting an update rather than automatically refilled. + ## [1.1.2] - 2026-11-10 ### Fixed @@ -78,3 +93,4 @@ [1.1.0]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.1.0 [1.1.1]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.1.1 [1.1.2]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.1.2 +[1.2.0]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.2.0 diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md index 204d7f1..e65229a 100644 --- a/ai/chatgpt/README.md +++ b/ai/chatgpt/README.md @@ -14,24 +14,24 @@ Updates arrive automatically. The script also checks on its own and offers to up ## 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 | -| Tutorial | Guided tours of every feature, started from the “?” button in the header | -| Max Width | Full-width conversations, optional sidebar removal | -| Update Checker | Checks on load and every few minutes, tells you once per version | -| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | +| Feature | What you get | +| ----------------- | ------------------------------------------------------------------------------------------------------------------ | +| Usage Status | Remaining counts reported by ChatGPT, your plan, and low/empty alerts; totals and reset schedules are not inferred | +| Code Blocks V2 | 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 | +| Tutorial | Guided tours of every feature, started from the “?” button in the header | +| Max Width | Full-width conversations, optional sidebar removal | +| Update Checker | Checks on load and every few minutes, tells you once per version | +| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | ## Shortcuts @@ -44,6 +44,8 @@ Updates arrive automatically. The script also checks on its own and offers to up All of them can be changed from the settings dialog. +Usage Status shows reported remaining counts only; it does not invent totals or reset schedules. The `/wham/usage` endpoint is not displayed as the ordinary chat quota. + ## 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. diff --git a/ai/chatgpt/docs/code-blocks-v2.md b/ai/chatgpt/docs/code-blocks-v2.md new file mode 100644 index 0000000..8cca0f6 --- /dev/null +++ b/ai/chatgpt/docs/code-blocks-v2.md @@ -0,0 +1,35 @@ +--- +title: Code Blocks V2 +description: Faithful source selection, syntax colors and a compact code toolbar. +section: Guides +order: 48 +--- + +# Code Blocks V2 + +Code Blocks V2 keeps a continuous source text flow with actual newline characters. + +## Copying + +Select code and use Ctrl+C or Cmd+C. Line breaks and selected indentation are preserved. Selecting from the middle of a line copies only the selected portion of that line. + +Copy code copies the entire original block. Line numbers are not part of the source. + +The feature does not alter ChatGPT's editable Run-code editors. + +## Reading + +- Wrap toggles visual wrapping without changing the source. +- Line numbers appear when wrapping is off. +- Fold is available for sufficiently long blocks, but code starts expanded. +- Download saves the original source text. + +Syntax highlighting is retained only when its reconstructed text matches the source. Otherwise the block falls back to plain text rather than corrupting code. + +## Guided tour + +Open Help and select Code blocks. The tour highlights the block and its toolbar. + +## Verification + +Copy a selection containing blank lines, tabs and nested indentation into a plain-text editor. Verify the result before using copied code in a project. diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index f870aa1..706931a 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-chatgpt", - "version": "1.1.2", + "version": "1.2.0", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/ai/chatgpt/src/features/usage.ts b/ai/chatgpt/src/features/usage.ts index 81fae8d..45baaa3 100644 --- a/ai/chatgpt/src/features/usage.ts +++ b/ai/chatgpt/src/features/usage.ts @@ -2,48 +2,40 @@ import { Tooltip, createButton, createDataRow, createDialog, createSection, ensu import { Feature, createElement, injectStyle } from '@nolly/core' import type { MenuEntry, ScriptContext } from '@nolly/core' import { placeTool } from '../header-tools' +import { PILL_BUTTON_CLASS } from '../header-style' 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', + reason: 'Reasoning tool', file_upload: 'File uploads', - paste_text_to_file: 'Pasted text as file', + paste_text_to_file: 'Paste-to-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 labelOf = (feature: string): string => LABELS[feature] ?? feature.replace(/_/g, ' ') -const level = (remaining: number): 'ok' | 'low' | 'empty' => (remaining === 0 ? 'empty' : remaining <= LOW ? 'low' : 'ok') +const resetText = (iso: string | null): string => { + const timestamp = iso ? Date.parse(iso) : Number.NaN + if (!Number.isFinite(timestamp)) return 'reset not reported' + if (timestamp <= Date.now()) return 'reported reset passed · awaiting updated count' + return `reset ${new Date(timestamp).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}` +} -const titleCase = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1) +const expired = (iso: string | null): boolean => { + const timestamp = iso ? Date.parse(iso) : Number.NaN + return Number.isFinite(timestamp) && timestamp <= Date.now() +} 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.' + readonly description = 'Shows reported tool allowances without inventing a chat-message quota.' private readonly pill = markUi(createElement('button', `${PILL_BUTTON_CLASS} bp-usage-pill bp-themed`)) private readonly label = createElement('span') @@ -52,12 +44,12 @@ export class UsageFeature extends Feature { constructor(context: ScriptContext) { super(context) ensureUiStyles() - injectStyle(`${uiConfig().id}-usage-styles`, CSS) + injectStyle(`${uiConfig().id}-usage-styles`, `.bp-usage-pill[data-level='low'] { color: var(--bp-yellow); }.bp-usage-pill[data-level='empty'] { color: var(--bp-red); }`) 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' }) + this.tooltip = new Tooltip(this.pill, (container) => container.appendChild(this.rows()), { align: 'end' }) } private get primary(): string { @@ -65,14 +57,24 @@ export class UsageFeature extends Feature { } 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() - }) - ) + this.scope.add(session.subscribe((event) => { + if (!['limits', 'usage', 'plan'].includes(event)) return + if (event === 'limits') this.checkAlerts() + this.update() + this.renderOpenDialog() + this.context.refreshMenu() + })) + this.scope.interval(() => { + this.update() + this.renderOpenDialog() + }, 30_000) + } + + override onDisable(): void { + this.tooltip.hide() + this.pill.remove() + const dialog = document.getElementById(this.dialogId) + if (dialog instanceof HTMLDialogElement) dialog.close() } run(): void { @@ -87,64 +89,77 @@ export class UsageFeature extends Feature { 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() } + { id: 'metric', label: `Badge: ${labelOf(this.primary)} · change`, action: () => this.cycle() } ] } + private get dialogId(): string { + return `${uiConfig().id}-usage-dialog` + } + 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' + const stale = entry ? expired(entry.resetAfter) : false + this.label.textContent = entry ? `${labelOf(entry.feature)} ${stale ? '—' : entry.remaining}` : 'Tool usage' + this.pill.dataset['level'] = !entry || stale ? 'ok' : entry.remaining <= 0 ? 'empty' : entry.remaining <= LOW ? 'low' : '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() + const next = features[(features.indexOf(this.primary) + 1) % features.length]! + storage.set(PRIMARY_KEY, next) this.update() + this.context.refreshMenu() } 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.')) + if (!session.limits.length) { + list.appendChild(createElement('div', 'bp-empty', 'No tool allowances reported yet.')) return list } - for (const limit of limits) list.appendChild(createDataRow(labelOf(limit.feature), `${limit.remaining} left · ${formatReset(limit.resetAfter)}`, limit.remaining === 0 ? 'negative' : '')) + for (const limit of session.limits) { + const value = expired(limit.resetAfter) ? `Last reported: ${limit.remaining} · ${resetText(limit.resetAfter)}` : `${limit.remaining} remaining · ${resetText(limit.resetAfter)}` + list.appendChild(createDataRow(labelOf(limit.feature), value)) + } return list } + private body(): HTMLElement[] { + const limits = createSection('Reported tool allowances') + limits.appendChild(this.rows()) + const explanation = createElement('p', 'bp-hint', 'These are tool counters returned by ChatGPT, not a verified total chat-message allowance. Totals are not supplied. Counts refresh when ChatGPT returns new data; elapsed reset times do not imply a confirmed refill.') + const nodes = [limits, explanation] + if (session.maxFileMb !== null) { + const files = createSection('Reported attachment ceiling') + files.appendChild(createDataRow('General file ceiling', `${session.maxFileMb} MB`)) + files.appendChild(createElement('p', 'bp-hint', 'File-type and account restrictions can be lower.')) + nodes.push(files) + } + if (session.usage) nodes.push(createElement('p', 'bp-hint', 'The separate /wham/usage window is excluded because it has not been established as the quota for this chat.')) + return nodes + } + + private renderOpenDialog(): void { + const dialog = document.getElementById(this.dialogId) + if (!(dialog instanceof HTMLDialogElement) || !dialog.open) return + const body = dialog.querySelector('.bp-dialog-body') + if (!body) return + const top = body.scrollTop + body.replaceChildren(...this.body()) + body.scrollTop = top + } + private open(): void { - const dialogId = `${uiConfig().id}-usage-dialog` - const existing = document.getElementById(dialogId) + const existing = document.getElementById(this.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) + const ui = createDialog({ id: this.dialogId, title: 'Usage', description: session.plan ? `Reported plan: ${session.plan}` : 'Plan not reported', width: 600 }) + ui.body.append(...this.body()) ui.footer.append(createButton('Close', { primary: true, onClick: ui.close })) ui.show() } @@ -152,14 +167,13 @@ export class UsageFeature extends Feature { 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 + for (const entry of session.limits) { + if (expired(entry.resetAfter)) continue + const before = last[entry.feature] + next[entry.feature] = entry.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) + if (before > 0 && entry.remaining === 0) showToast(`${labelOf(entry.feature)}: none remaining · ${resetText(entry.resetAfter)}`) + else if (before === 0 && entry.remaining > 0) showToast(`${labelOf(entry.feature)}: ${entry.remaining} now reported available.`) } storage.set(LAST_KEY, next) } diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts index 51c99da..f9e6e01 100644 --- a/ai/chatgpt/src/header-tools.ts +++ b/ai/chatgpt/src/header-tools.ts @@ -1,25 +1,45 @@ -import { findHeaderSlot } from './locate' +import { markUi } from './dom' const ORDER = ['settings', 'usage', 'export', 'help'] as const export type ToolId = (typeof ORDER)[number] +const visible = (element: HTMLElement): boolean => { + const style = getComputedStyle(element) + const rect = element.getBoundingClientRect() + return !element.closest('[aria-hidden="true"], [inert]') && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0 +} + export const toolRow = (): HTMLElement | null => { - const slot = findHeaderSlot() - return slot?.querySelector('.contents > div') ?? slot + const titlebars = [...document.querySelectorAll('[data-app-shell-main-titlebar="true"]')].filter(visible) + for (const titlebar of titlebars) { + const slots = [...titlebar.querySelectorAll('[data-app-shell-header-obstacle="true"]')].filter(visible) + for (const slot of slots) { + const rows = [...slot.querySelectorAll('.contents > div')].filter(visible) + const nativeRow = rows.find((row) => [...row.children].some((child) => child instanceof HTMLButtonElement && !child.hasAttribute('data-bc-tool'))) + if (nativeRow) return nativeRow + } + } + return null } export const placeTool = (button: HTMLElement, id: ToolId): boolean => { - const row = toolRow() - if (!row) return false - button.dataset['bcTool'] = id - if (button.parentElement !== row) row.append(button) - const ours = ORDER.flatMap((name) => row.querySelector(`:scope > [data-bc-tool="${name}"]`) ?? []) - let cursor: Element | null = [...row.children].filter((child) => !child.hasAttribute('data-bc-tool')).at(-1) ?? null - for (const element of ours) { - const wanted: Element | null = cursor ? cursor.nextElementSibling : row.firstElementChild - if (wanted !== element) row.insertBefore(element, wanted) - cursor = element - } - return true + const row = toolRow() + if (!row) return false + markUi(button) + button.dataset['bcTool'] = id + button.style.setProperty('pointer-events', 'auto', 'important') + button.style.setProperty('-webkit-app-region', 'no-drag', 'important') + if (button.parentElement !== row) row.appendChild(button) + const ours = ORDER.flatMap((name) => { + const element = row.querySelector(`:scope > [data-bc-tool="${name}"]`) + return element ? [element] : [] + }) + let cursor: Element | null = [...row.children].filter((child) => !child.hasAttribute('data-bc-tool')).at(-1) ?? null + for (const element of ours) { + const wanted = cursor ? cursor.nextElementSibling : row.firstElementChild + if (wanted !== element) row.insertBefore(element, wanted) + cursor = element + } + return true } diff --git a/ai/chatgpt/src/tours.ts b/ai/chatgpt/src/tours.ts index 4278707..6187a7b 100644 --- a/ai/chatgpt/src/tours.ts +++ b/ai/chatgpt/src/tours.ts @@ -85,12 +85,23 @@ const batch: Tour = { const codeBlocks: Tour = { id: 'code', - title: 'Code blocks', - summary: 'Language badges, folding, wrapping and copying.', + title: 'Code Blocks V2', + summary: 'Faithful copying, syntax colors and a compact source toolbar.', steps: [ - point('Enhanced code', 'When an answer finishes, its code blocks are replaced with these. Ask for some code if you do not see one.', find('.bp-code')), - point('Toolbar', 'Wrap long lines, toggle line numbers, fold long code, copy, or download as a file.', find('.bp-code-actions')), - info('Selecting and copying', 'You can select part of a block and copy it. Indentation and line breaks are kept exactly.') + point( + 'Source-faithful code', + 'These blocks contain real newline characters. Select code and copy it with Ctrl+C or Cmd+C. Only the selected text is copied.', + find('.bp-code-v2') + ), + point( + 'Code toolbar', + 'Copy the entire block, download its source, wrap long lines, toggle line numbers or explicitly fold a long block.', + find('.bp-code-v2 .bp-code-actions') + ), + info( + 'Visual wrapping is not a source change', + 'Wrapping hides the gutter to avoid misleading visual line numbers. Blank lines, tabs and indentation remain part of the source.' + ) ] } diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 506f3e7..c3bf8db 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -2,6 +2,21 @@ 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/). +## [1.2.0] - 2026-11-10 + +### Changed + +- Renamed Code Block Pro to Code Blocks V2. +- Rebuilt code selection around actual newline text nodes and source-faithful content. +- Added restrained toolbar styling, explicit folding, and a non-selectable line-number gutter. +- Improved shared dialog spacing and form styling. + +### Fixed + +- Removed unverified usage totals and misleading quota interpretations. +- ChatGPT header tools explicitly restore pointer interaction and reattach to the visible native row. +- Expired ChatGPT tool counters are labelled as awaiting an update rather than automatically refilled. + ## [1.1.2] - 2026-11-10 ### Fixed @@ -170,3 +185,4 @@ First public release. [1.1.0]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.1.0 [1.1.1]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.1.1 [1.1.2]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.1.2 +[1.2.0]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.2.0 diff --git a/ai/perplexity/README.md b/ai/perplexity/README.md index 2119ece..dfd9a19 100644 --- a/ai/perplexity/README.md +++ b/ai/perplexity/README.md @@ -14,24 +14,24 @@ Updates arrive automatically. The script also checks on its own and offers to up ## Features -| Feature | What you get | -| ----------------- | ---------------------------------------------------------------------------------------------------- | -| Usage status | Remaining queries per mode in the header, hover summary, details dialog, learned refill estimates | -| Code Block Pro | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe selection copy | -| Big messages | 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 and PDF, with citation styles | -| 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 | -| Max Width | Full-width layout, optional sidebar removal | -| Usage alerts | Refill, low and used-up alerts (desktop notifications in the background), plus your daily pace | -| Update checker | Checks on load and every few minutes, tells you once per version, remembers skipped versions | -| Message Queue | Type ahead: queue follow-ups while an answer generates; they send one by one | -| Recall | Search everything you sent, reuse it in one key, walk back through it with the arrow keys | -| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | +| Feature | What you get | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| Usage status | Reported remaining counts per mode in the header, hover summary and details dialog; totals and reset schedules are not invented | +| Code Blocks V2 | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe selection copy | +| Big messages | 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 and PDF, with citation styles | +| 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 | +| Max Width | Full-width layout, optional sidebar removal | +| Usage alerts | Refill, low and used-up alerts (desktop notifications in the background), plus your daily pace | +| Update checker | Checks on load and every few minutes, tells you once per version, remembers skipped versions | +| Message Queue | Type ahead: queue follow-ups while an answer generates; they send one by one | +| Recall | Search everything you sent, reuse it in one key, walk back through it with the arrow keys | +| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | ## Shortcuts diff --git a/ai/perplexity/docs/code-blocks-v2.md b/ai/perplexity/docs/code-blocks-v2.md new file mode 100644 index 0000000..8cca0f6 --- /dev/null +++ b/ai/perplexity/docs/code-blocks-v2.md @@ -0,0 +1,35 @@ +--- +title: Code Blocks V2 +description: Faithful source selection, syntax colors and a compact code toolbar. +section: Guides +order: 48 +--- + +# Code Blocks V2 + +Code Blocks V2 keeps a continuous source text flow with actual newline characters. + +## Copying + +Select code and use Ctrl+C or Cmd+C. Line breaks and selected indentation are preserved. Selecting from the middle of a line copies only the selected portion of that line. + +Copy code copies the entire original block. Line numbers are not part of the source. + +The feature does not alter ChatGPT's editable Run-code editors. + +## Reading + +- Wrap toggles visual wrapping without changing the source. +- Line numbers appear when wrapping is off. +- Fold is available for sufficiently long blocks, but code starts expanded. +- Download saves the original source text. + +Syntax highlighting is retained only when its reconstructed text matches the source. Otherwise the block falls back to plain text rather than corrupting code. + +## Guided tour + +Open Help and select Code blocks. The tour highlights the block and its toolbar. + +## Verification + +Copy a selection containing blank lines, tabs and nested indentation into a plain-text editor. Verify the result before using copied code in a project. diff --git a/ai/perplexity/package.json b/ai/perplexity/package.json index 5bf85a7..694cfd5 100644 --- a/ai/perplexity/package.json +++ b/ai/perplexity/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-perplexity", - "version": "1.1.2", + "version": "1.2.0", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/ai/perplexity/src/modules/usage-status/caps.ts b/ai/perplexity/src/modules/usage-status/caps.ts index b534955..5ac29e6 100644 --- a/ai/perplexity/src/modules/usage-status/caps.ts +++ b/ai/perplexity/src/modules/usage-status/caps.ts @@ -5,15 +5,13 @@ const candidates = (name: string): string[] => [`limit_${name}`, `${name}_limit` const isCap = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0 export const findCap = (rate: RateLimitResponse | null, key: LimitKey): number | null => { - if (!rate) return null - const names = candidates(key.replace(/^remaining_/, '')) - const scopes: Record[] = [rate as Record] - if (rate.model_specific_limits && typeof rate.model_specific_limits === 'object') scopes.push(rate.model_specific_limits) - for (const scope of scopes) { - for (const name of names) { - const value = scope[name] - if (isCap(value)) return value - } - } - return null -} \ No newline at end of file + if (!rate) return null + const root = rate as Record + + for (const name of candidates(key.replace(/^remaining_/, ''))) { + const value = root[name] + if (isCap(value)) return value + } + + return null +} diff --git a/ai/perplexity/src/modules/usage-status/definitions.ts b/ai/perplexity/src/modules/usage-status/definitions.ts index f121319..6aa412e 100644 --- a/ai/perplexity/src/modules/usage-status/definitions.ts +++ b/ai/perplexity/src/modules/usage-status/definitions.ts @@ -3,10 +3,10 @@ import type { LimitDefinition, LimitKey, SettingField, Status } from './types' const DAY = 86_400_000 export const LIMITS: Readonly> = { - remaining_pro: { label: 'Pro Search', total: 200, period: 'Rolling (learned)', window: 7 * DAY }, - remaining_research: { label: 'Deep Research', total: 20, period: 'Rolling (learned)', window: 30 * DAY }, - remaining_agentic_research: { label: 'Computer / Agentic', total: null, period: 'Rolling (learned)', window: 7 * DAY }, - remaining_labs: { label: 'Labs', total: 25, period: 'Rolling (learned)', window: 30 * DAY } + remaining_pro: { label: 'Pro Search', total: 200, period: 'Reset schedule not supplied', window: 7 * DAY }, + remaining_research: { label: 'Deep Research', total: 20, period: 'Reset schedule not supplied', window: 30 * DAY }, + remaining_agentic_research: { label: 'Computer / Agentic', total: null, period: 'Reset schedule not supplied', window: 7 * DAY }, + remaining_labs: { label: 'Labs', total: 25, period: 'Reset schedule not supplied', window: 30 * DAY } } export const LIMIT_KEYS = Object.keys(LIMITS) as LimitKey[] @@ -79,4 +79,4 @@ export const SOURCE_LABELS: Readonly> = { visualdx: 'VisualDx', web: 'Web', wiley_mcp_cashmere: 'Wiley' -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/usage-status/plan.ts b/ai/perplexity/src/modules/usage-status/plan.ts index 22d4574..c444f4d 100644 --- a/ai/perplexity/src/modules/usage-status/plan.ts +++ b/ai/perplexity/src/modules/usage-status/plan.ts @@ -36,7 +36,7 @@ export const resolvePlan = (settings: SettingsResponse | null): PlanInfo => { } if (UNKNOWN.has(tierKey)) { - if (active) return { plan: 'paid', label: 'Paid subscription · tier not reported' } + if (active) return { plan: 'unknown', label: 'Subscription active · tier not reported' } return { plan: 'unknown', label: status ? `Tier not reported (${status})` : 'Tier not reported' } } diff --git a/ai/perplexity/src/modules/usage-status/service.ts b/ai/perplexity/src/modules/usage-status/service.ts index a532d0e..8d54625 100644 --- a/ai/perplexity/src/modules/usage-status/service.ts +++ b/ai/perplexity/src/modules/usage-status/service.ts @@ -135,9 +135,7 @@ export class UsageService { getNotice(): string | null { if (!this.initialized || this.getPlan() !== 'free') return null - return hasSignInPrompt() - ? 'Not signed in: Perplexity returned anonymous limits. Sign in to see your plan.' - : 'Perplexity reports no subscription tier or status for this session, even though the page looks signed in. Open "Raw API data" to see which request variants were tried.' + return hasSignInPrompt() ? 'Not signed in: Perplexity returned anonymous limits. Sign in to see your plan.' : 'Perplexity reports no subscription tier or status for this session, even though the page looks signed in. Open "Raw API data" to see which request variants were tried.' } getRemaining(key: LimitKey | null): number | null { @@ -148,22 +146,19 @@ export class UsageService { resolveTotal(key: LimitKey | null): number | null { if (!key) return null - return findCap(this.rate, key) ?? (Math.max(LIMITS[key].total ?? 0, this.tracker.peak(key) ?? 0) || null) + const cap = findCap(this.rate, key) + const remaining = this.getRemaining(key) + if (cap === null || (remaining !== null && remaining > cap)) return null + return cap } totalSource(key: LimitKey | null): 'api' | 'configured' | 'learned' | null { - if (!key) return null - if (findCap(this.rate, key) !== null) return 'api' - const configured = LIMITS[key].total ?? 0 - const peak = this.tracker.peak(key) ?? 0 - if (peak > configured) return 'learned' - return configured > 0 ? 'configured' : null + return this.resolveTotal(key) !== null ? 'api' : null } formatTotal(key: LimitKey | null): string | null { const total = this.resolveTotal(key) - if (total === null) return null - return this.totalSource(key) === 'learned' ? `≥${total}` : String(total) + return total === null ? null : String(total) } getForecast(key: LimitKey | null): Forecast | null { @@ -229,7 +224,7 @@ export class UsageService { freeFallback, period: mode.key ? LIMITS[mode.key].period : 'Unknown', reset: this.formatForecast(mode.key), - status: freeFallback ? 'low' : getStatus(remaining, total) + status: freeFallback ? 'low' : remaining === null ? 'unavailable' : remaining === 0 ? 'empty' : total === null ? 'unavailable' : getStatus(remaining, total) } } diff --git a/ai/perplexity/src/tours.ts b/ai/perplexity/src/tours.ts index 4760226..e1880d2 100644 --- a/ai/perplexity/src/tours.ts +++ b/ai/perplexity/src/tours.ts @@ -78,12 +78,23 @@ const batch: Tour = { const codeBlocks: Tour = { id: 'code', - title: 'Code blocks', - summary: 'Language badges, folding, wrapping and copying.', + title: 'Code Blocks V2', + summary: 'Faithful copying, syntax colors and a compact source toolbar.', steps: [ - point('Enhanced code', 'When an answer finishes, its code blocks are replaced with these. Ask for some code if you do not see one.', find('.bp-code')), - point('Toolbar', 'Wrap long lines, toggle line numbers, fold long code, copy, or download as a file.', find('.bp-code-actions')), - info('Selecting and copying', 'You can select part of a block and copy it. Indentation and line breaks are kept exactly.') + point( + 'Source-faithful code', + 'These blocks contain real newline characters. Select code and copy it with Ctrl+C or Cmd+C. Only the selected text is copied.', + find('.bp-code-v2') + ), + point( + 'Code toolbar', + 'Copy the entire block, download its source, wrap long lines, toggle line numbers or explicitly fold a long block.', + find('.bp-code-v2 .bp-code-actions') + ), + info( + 'Visual wrapping is not a source change', + 'Wrapping hides the gutter to avoid misleading visual line numbers. Blank lines, tabs and indentation remain part of the source.' + ) ] } diff --git a/bun.lock b/bun.lock index a2787a2..8871d23 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ }, "ai/chatgpt": { "name": "@nolly/ai-chatgpt", - "version": "1.1.2", + "version": "1.2.0", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", @@ -19,7 +19,7 @@ }, "ai/perplexity": { "name": "@nolly/ai-perplexity", - "version": "1.1.2", + "version": "1.2.0", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", diff --git a/core/ai/CHANGELOG.md b/core/ai/CHANGELOG.md index 55d30c2..ad3e239 100644 --- a/core/ai/CHANGELOG.md +++ b/core/ai/CHANGELOG.md @@ -1,4 +1,9 @@ # Changelog +# Changelog + +## [0.2.2] - 2026-11-10 + +- Added the V2 renderer and shared UI changes. ## [0.2.1] - 2026-11-10 diff --git a/core/ai/src/features/code-blocks/block.ts b/core/ai/src/features/code-blocks/block.ts index 1c32602..826070b 100644 --- a/core/ai/src/features/code-blocks/block.ts +++ b/core/ai/src/features/code-blocks/block.ts @@ -1,179 +1,162 @@ -import { copyText } from '../../clipboard' -import { createIcon, type IconName } from '../../ui/icons' import { createElement } from '@nolly/core' +import { copyText } from '../../clipboard' +import { saveFile } from '../../download' import { markUi } from '../../ui/config' +import { createIcon, type IconName } from '../../ui/icons' +import { createLanguageIcon } from './badges' import type { BlockInfo } from './detect' import { highlightLines } from './highlight' import { languageInfo } from './languages' import { renderPlainLines, splitHighlighted } from './lines' import type { CodeBlockSettings } from './settings' import { ensureCodeStyles } from './styles' -import { createLanguageIcon } from './badges' type Flag = 'wrap' | 'lines' | 'collapsed' -const FLASH_MS = 1_200 - export class EnhancedBlock { - readonly element = markUi(createElement('div', 'bp-code')) - private readonly lineCount: number - private readonly collapsible: boolean - private readonly toggles = new Map() - - constructor( - readonly source: HTMLElement, - readonly root: HTMLElement, - readonly info: BlockInfo, - private readonly settings: CodeBlockSettings - ) { - ensureCodeStyles() - this.lineCount = info.text.split('\n').length - this.collapsible = settings.collapseAfter > 0 && this.lineCount > settings.collapseAfter - this.build() - } - - get text(): string { - return this.info.text - } - - get fenced(): string { - const language = this.info.language === 'text' ? '' : this.info.language - return `\`\`\`${language}\n${this.info.text}\n\`\`\`` - } - - mount(): void { - this.root.insertAdjacentElement('beforebegin', this.element) - this.ensureHidden() - } - - ensureHidden(): void { - if (this.root.style.getPropertyValue('display') !== 'none') this.root.style.setProperty('display', 'none', 'important') - } - - destroy(): void { - this.element.remove() - this.root.style.removeProperty('display') - } - - private setFlag(flag: Flag, value: boolean): void { - this.element.dataset[flag] = String(value) - this.toggles.get(flag)?.setAttribute('aria-pressed', String(value)) - } - - private button(icon: IconName, title: string, onClick: (button: HTMLButtonElement) => void): HTMLButtonElement { - const button = createElement('button', 'bp-code-btn') - button.type = 'button' - button.title = title - button.setAttribute('aria-label', title) - button.appendChild(createIcon(icon, 15)) - button.addEventListener('click', () => onClick(button)) - return button - } - - private toggle(flag: Flag, icon: IconName, title: string, initial: boolean): HTMLButtonElement { - const button = this.button(icon, title, () => this.setFlag(flag, this.element.dataset[flag] !== 'true')) - this.toggles.set(flag, button) - this.setFlag(flag, initial) - return button - } - - private swapIcon(button: HTMLButtonElement, icon: IconName, restore: IconName): void { - button.replaceChildren(createIcon(icon, 15)) - button.dataset['done'] = 'true' - window.setTimeout(() => { - button.replaceChildren(createIcon(restore, 15)) - delete button.dataset['done'] - }, FLASH_MS) - } - - private download(): void { - const { filename, language, text } = this.info - const name = (filename ?? `snippet.${languageInfo(language).ext}`).split(/[\\/]/).pop() ?? 'snippet.txt' - const url = URL.createObjectURL(new Blob([text], { type: 'text/plain' })) - const link = createElement('a') - link.href = url - link.download = name - link.click() - URL.revokeObjectURL(url) - } - - private renderLines(): HTMLElement[] { - const { language, text } = this.info - const diff = language === 'diff' - if (diff || this.settings.highlight === 'plain') return renderPlainLines(text, diff) - if (this.settings.highlight === 'builtin') return highlightLines(text, language) ?? renderPlainLines(text, false) - const original = this.source.querySelector('code') ?? this.source - return original.hasChildNodes() ? splitHighlighted(original, this.lineCount) : renderPlainLines(text, false) - } - - private build(): void { - const { language, filename } = this.info - const info = languageInfo(language) - const meta = createElement('div', 'bp-code-meta') - meta.append(createLanguageIcon(language), createElement('span', 'bp-code-lang', info.name)) - if (filename) meta.appendChild(createElement('span', 'bp-code-file', filename)) - meta.appendChild(createElement('span', 'bp-code-count', `${this.lineCount} ${this.lineCount === 1 ? 'line' : 'lines'}`)) - const actions = createElement('div', 'bp-code-actions') - actions.append(this.toggle('wrap', 'wrap', 'Wrap lines', this.settings.wrap), this.toggle('lines', 'lines', 'Line numbers', this.settings.lineNumbers)) - if (this.collapsible) actions.appendChild(this.toggle('collapsed', 'fold', 'Fold long code', true)) - actions.append( - this.button('copy', 'Copy code', (button) => void copyText(this.info.text).then((ok) => ok && this.swapIcon(button, 'check', 'copy'))), - this.button('download', 'Download as file', () => this.download()) - ) - const header = createElement('div', 'bp-code-head') - header.append(meta, actions) - const pre = createElement('pre', 'bp-code-pre') - const code = createElement('code') - code.append(...this.renderLines()) - pre.appendChild(code) - const body = createElement('div', 'bp-code-body') - body.appendChild(pre) - this.element.style.setProperty('--bp-lang-hue', String(info.hue)) - this.element.style.setProperty('--bp-code-collapse', String(this.settings.collapseAfter)) - this.element.style.setProperty('--bp-digits', String(String(this.lineCount).length)) - this.element.dataset['collapsed'] = 'false' - this.element.append(header, body) - this.element.addEventListener('copy', this.handleCopy) - if (!this.collapsible) return - this.setFlag('collapsed', true) - const more = createElement('button', 'bp-code-more', `Show ${this.lineCount - this.settings.collapseAfter} more lines`) - more.type = 'button' - more.addEventListener('click', () => this.setFlag('collapsed', false)) - this.element.appendChild(more) - } - - private locate(lines: HTMLElement[], code: Element | null, node: Node, offset: number, isEnd: boolean): { line: number; column: number } | null { - const element = node instanceof Element ? node : node.parentElement - const line = element?.closest('.bp-line') - if (line) { - const index = lines.indexOf(line) - const cell = line.querySelector('.bp-text') - if (index < 0 || !cell) return null - if (!cell.contains(node)) return { line: index, column: isEnd ? (cell.textContent ?? '').length : 0 } - const probe = document.createRange() - probe.selectNodeContents(cell) - probe.setEnd(node, offset) - return { line: index, column: probe.toString().length } - } - const last = lines.length - 1 - if (node !== code) return isEnd ? { line: last, column: (lines[last]?.querySelector('.bp-text')?.textContent ?? '').length } : { line: 0, column: 0 } - const index = Math.min(Math.max(isEnd ? offset - 1 : offset, 0), last) - return { line: index, column: isEnd ? (lines[index]?.querySelector('.bp-text')?.textContent ?? '').length : 0 } - } - - private readonly handleCopy = (event: ClipboardEvent): void => { - const selection = window.getSelection() - if (!selection || selection.isCollapsed || !selection.rangeCount || !event.clipboardData) return - const range = selection.getRangeAt(0) - if (!this.element.contains(range.startContainer) || !this.element.contains(range.endContainer)) return - const lines = [...this.element.querySelectorAll('.bp-line')] - const code = this.element.querySelector('code') - const start = this.locate(lines, code, range.startContainer, range.startOffset, false) - const end = this.locate(lines, code, range.endContainer, range.endOffset, true) - if (!start || !end || end.line < start.line) return - const source = this.info.text.split('\n') - const text = start.line === end.line ? (source[start.line] ?? '').slice(start.column, end.column) : [(source[start.line] ?? '').slice(start.column), ...source.slice(start.line + 1, end.line), (source[end.line] ?? '').slice(0, end.column)].join('\n') - event.clipboardData.setData('text/plain', text) - event.preventDefault() - } -} \ No newline at end of file + readonly element = markUi(createElement('div', 'bp-code bp-code-v2 bp-themed')) + + private readonly code = createElement('code', 'bp-code-source') + private readonly gutter = createElement('div', 'bp-code-gutter') + private readonly toggles = new Map() + private readonly lineCount: number + private readonly originalDisplay: string + private readonly originalPriority: string + + constructor( + readonly source: HTMLElement, + readonly root: HTMLElement, + readonly info: BlockInfo, + private readonly settings: CodeBlockSettings + ) { + ensureCodeStyles() + this.lineCount = info.text.split('\n').length + this.originalDisplay = root.style.getPropertyValue('display') + this.originalPriority = root.style.getPropertyPriority('display') + this.build() + } + + get text(): string { + return this.info.text + } + + get fenced(): string { + const longest = Math.max(0, ...(this.text.match(/`+/g) ?? []).map((run) => run.length)) + const marker = '`'.repeat(Math.max(3, longest + 1)) + return `${marker}${this.info.language === 'text' ? '' : this.info.language}\n${this.text}\n${marker}` + } + + mount(): void { + this.root.insertAdjacentElement('beforebegin', this.element) + this.ensureHidden() + } + + ensureHidden(): void { + if (this.root.style.getPropertyValue('display') !== 'none') this.root.style.setProperty('display', 'none', 'important') + } + + destroy(): void { + this.element.remove() + if (this.originalDisplay) this.root.style.setProperty('display', this.originalDisplay, this.originalPriority) + else this.root.style.removeProperty('display') + } + + private setFlag(flag: Flag, value: boolean): void { + this.element.dataset[flag] = String(value) + this.toggles.get(flag)?.setAttribute('aria-pressed', String(value)) + } + + private button(icon: IconName, title: string, action: () => void): HTMLButtonElement { + const button = createElement('button', 'bp-code-btn') + button.type = 'button' + button.title = title + button.setAttribute('aria-label', title) + button.appendChild(createIcon(icon, 16)) + button.addEventListener('click', action) + return button + } + + private toggle(flag: Flag, icon: IconName, title: string, value: boolean): HTMLButtonElement { + const button = this.button(icon, title, () => { + this.setFlag(flag, this.element.dataset[flag] !== 'true') + }) + this.toggles.set(flag, button) + this.setFlag(flag, value) + return button + } + + private renderSource(): void { + let lines: HTMLElement[] + if (this.settings.highlight === 'builtin') { + lines = highlightLines(this.text, this.info.language) + ?? renderPlainLines(this.text, this.info.language === 'diff') + } else if (this.settings.highlight === 'site') { + lines = splitHighlighted(this.source.querySelector('code') ?? this.source, this.lineCount) + } else { + lines = renderPlainLines(this.text, this.info.language === 'diff') + } + const fragment = document.createDocumentFragment() + lines.forEach((line, index) => { + if (index > 0) fragment.appendChild(document.createTextNode('\n')) + const cell = line.querySelector('.bp-text') + for (const child of cell?.childNodes ?? []) fragment.appendChild(child.cloneNode(true)) + }) + if (fragment.textContent === this.text) this.code.appendChild(fragment) + else this.code.textContent = this.text + } + + private build(): void { + const meta = createElement('div', 'bp-code-meta') + meta.append(createLanguageIcon(this.info.language), createElement('span', 'bp-code-lang', languageInfo(this.info.language).name)) + if (this.info.filename) meta.appendChild(createElement('span', 'bp-code-file', this.info.filename)) + meta.appendChild(createElement('span', 'bp-code-count', `${this.lineCount} lines`)) + const actions = createElement('div', 'bp-code-actions') + actions.append(this.toggle('wrap', 'wrap', 'Wrap lines', this.settings.wrap), this.toggle('lines', 'lines', 'Line numbers', this.settings.lineNumbers)) + const collapsible = this.settings.collapseAfter > 0 && this.lineCount > this.settings.collapseAfter + if (collapsible) actions.appendChild(this.toggle('collapsed', 'fold', 'Fold code', false)) + const copy = this.button('copy', 'Copy code', () => { + void copyText(this.text).then((ok) => { + if (!ok) return + copy.replaceChildren(createIcon('check', 16)) + window.setTimeout(() => copy.replaceChildren(createIcon('copy', 16)), 1_200) + }) + }) + actions.appendChild(copy) + actions.appendChild(this.button('download', 'Download code', () => { + const filename = (this.info.filename ?? `snippet.${languageInfo(this.info.language).ext}`).split(/[\\/]/).pop() || 'snippet.txt' + saveFile(filename, this.text) + })) + const head = createElement('div', 'bp-code-head') + head.append(meta, actions) + this.gutter.setAttribute('aria-hidden', 'true') + this.gutter.textContent = Array.from({ length: this.lineCount }, (_, index) => index + 1).join('\n') + const pre = createElement('pre', 'bp-code-native-pre') + pre.tabIndex = 0 + pre.setAttribute('aria-label', `${languageInfo(this.info.language).name} source code`) + this.renderSource() + pre.appendChild(this.code) + const scroll = createElement('div', 'bp-code-scroll') + scroll.append(this.gutter, pre) + const body = createElement('div', 'bp-code-body') + body.appendChild(scroll) + this.element.style.setProperty('--bp-code-collapse', String(this.settings.collapseAfter)) + this.element.append(head, body) + if (collapsible) { + const expand = createElement('button', 'bp-code-more', 'Expand code') + expand.type = 'button' + expand.addEventListener('click', () => this.setFlag('collapsed', false)) + this.element.appendChild(expand) + } + this.element.addEventListener('copy', this.handleCopy, true) + } + + private readonly handleCopy = (event: ClipboardEvent): void => { + const selection = window.getSelection() + if (!selection || selection.isCollapsed || !selection.rangeCount || !event.clipboardData) return + const range = selection.getRangeAt(0) + if (!this.code.contains(range.startContainer) || !this.code.contains(range.endContainer)) return + event.clipboardData.setData('text/plain', range.toString()) + event.preventDefault() + event.stopImmediatePropagation() + } +} diff --git a/core/ai/src/features/code-blocks/dialog.ts b/core/ai/src/features/code-blocks/dialog.ts index 0821ca3..a46093e 100644 --- a/core/ai/src/features/code-blocks/dialog.ts +++ b/core/ai/src/features/code-blocks/dialog.ts @@ -12,7 +12,7 @@ export const toggleCodeSettingsDialog = (current: CodeBlockSettings, onSave: (se 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 Blocks V2', 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/core/ai/src/features/code-blocks/index.ts b/core/ai/src/features/code-blocks/index.ts index 72318d0..7d6763c 100644 --- a/core/ai/src/features/code-blocks/index.ts +++ b/core/ai/src/features/code-blocks/index.ts @@ -12,103 +12,103 @@ const FORCE_MS = 6_000 const RESCAN_MS = 500 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.' + readonly id = 'code-blocks' + readonly name = 'Code Blocks V2' + readonly description = 'Selectable source with faithful whitespace, syntax colors, wrapping, line numbers and downloads.' - private settings: CodeBlockSettings = loadCodeSettings() - private readonly blocks = new Map() - private readonly seen = new WeakMap() - private rescan = 0 + private settings: CodeBlockSettings = loadCodeSettings() + private readonly blocks = new Map() + private readonly seen = new WeakMap() + private rescan = 0 - run(): void { - if (!this.enabled) { - this.clear() - return - } - this.prune() - const generating = isGenerating() - const now = Date.now() - let waiting = false - for (const pre of document.querySelectorAll('pre')) { - if (isOwnUi(pre) || pre.closest('[contenteditable], textarea')) continue - const text = readCode(pre) - if (!text.trim()) continue - const existing = this.blocks.get(pre) - if (existing?.text === text) continue - if (existing) this.release(pre) - const entry = this.seen.get(pre) - if (!entry || entry.text !== text) { - this.seen.set(pre, { text, since: now }) - waiting = true - continue - } - const stable = now - entry.since - if (stable < STABLE_MS || (generating && stable < FORCE_MS)) { - waiting = true - continue - } - this.enhance(pre, text) - } - if (waiting) this.scheduleRescan() - } + run(): void { + if (!this.enabled) { + this.clear() + return + } + this.prune() + const generating = isGenerating() + const now = Date.now() + let waiting = false + for (const pre of document.querySelectorAll('pre')) { + if (isOwnUi(pre) || pre.closest('[contenteditable], textarea')) continue + const text = readCode(pre) + if (!text.trim()) continue + const existing = this.blocks.get(pre) + if (existing?.text === text) continue + if (existing) this.release(pre) + const entry = this.seen.get(pre) + if (!entry || entry.text !== text) { + this.seen.set(pre, { text, since: now }) + waiting = true + continue + } + const stable = now - entry.since + if (stable < STABLE_MS || (generating && stable < FORCE_MS)) { + waiting = true + continue + } + this.enhance(pre, text) + } + if (waiting) this.scheduleRescan() + } - override menuEntries(): MenuEntry[] { - return [ - { label: 'Configure Code Block Pro', action: () => this.configure() }, - { label: 'Copy All Code Blocks', action: () => void this.copyAll() } - ] - } + override menuEntries(): MenuEntry[] { + return [ + { label: 'Configure Code Blocks V2', action: () => this.configure() }, + { label: 'Copy All Code Blocks', action: () => void this.copyAll() } + ] + } - private enhance(pre: HTMLElement, text: string): void { - try { - const root = findBlockRoot(pre, this.settings.hideSiteChrome) - const block = new EnhancedBlock(pre, root, analyze(pre, root, text), this.settings) - block.mount() - this.blocks.set(pre, block) - } catch (error) { - logger.errorOnce('Code block enhancement failed; the original block is kept.', error) - } - } + private enhance(pre: HTMLElement, text: string): void { + try { + const root = findBlockRoot(pre, this.settings.hideSiteChrome) + const block = new EnhancedBlock(pre, root, analyze(pre, root, text), this.settings) + block.mount() + this.blocks.set(pre, block) + } catch (error) { + logger.errorOnce('Code block enhancement failed; the original block is kept.', error) + } + } - private release(source: HTMLElement): void { - this.blocks.get(source)?.destroy() - this.blocks.delete(source) - this.seen.delete(source) - } + private release(source: HTMLElement): void { + this.blocks.get(source)?.destroy() + this.blocks.delete(source) + this.seen.delete(source) + } - private prune(): void { - for (const [source, block] of this.blocks) { - if (!source.isConnected || !block.root.isConnected || !block.element.isConnected) this.release(source) - else block.ensureHidden() - } - } + private prune(): void { + for (const [source, block] of this.blocks) { + if (!source.isConnected || !block.root.isConnected || !block.element.isConnected) this.release(source) + else block.ensureHidden() + } + } - private clear(): void { - for (const source of [...this.blocks.keys()]) this.release(source) - } + private clear(): void { + for (const source of [...this.blocks.keys()]) this.release(source) + } - private scheduleRescan(): void { - if (this.rescan) return - this.rescan = window.setTimeout(() => { - this.rescan = 0 - this.context.requestUpdate() - }, RESCAN_MS) - } + private scheduleRescan(): void { + if (this.rescan) return + this.rescan = window.setTimeout(() => { + this.rescan = 0 + this.context.requestUpdate() + }, RESCAN_MS) + } - private configure(): void { - toggleCodeSettingsDialog(this.settings, (settings) => { - this.settings = settings - saveCodeSettings(settings) - this.clear() - this.context.requestUpdate() - }) - } + private configure(): void { + toggleCodeSettingsDialog(this.settings, (settings) => { + this.settings = settings + saveCodeSettings(settings) + this.clear() + this.context.requestUpdate() + }) + } - private async copyAll(): Promise { - const ordered = [...this.blocks.values()].sort((a, b) => (a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)) - if (!ordered.length) return - const ok = await copyText(ordered.map((block) => block.fenced).join('\n\n')) - logger.info(ok ? `Copied ${ordered.length} code blocks.` : 'Could not copy code blocks.') - } -} \ No newline at end of file + private async copyAll(): Promise { + const ordered = [...this.blocks.values()].sort((a, b) => (a.element.compareDocumentPosition(b.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)) + if (!ordered.length) return + const ok = await copyText(ordered.map((block) => block.fenced).join('\n\n')) + logger.info(ok ? `Copied ${ordered.length} code blocks.` : 'Could not copy code blocks.') + } +} diff --git a/core/ai/src/features/code-blocks/styles.ts b/core/ai/src/features/code-blocks/styles.ts index 9510f61..e060743 100644 --- a/core/ai/src/features/code-blocks/styles.ts +++ b/core/ai/src/features/code-blocks/styles.ts @@ -2,145 +2,135 @@ import { injectStyle } from '@nolly/core' import { uiConfig } from '../../ui/config' const CSS = ` -.bp-code { - --bp-edge: color-mix(in srgb, currentColor 13%, transparent); - --bp-muted: color-mix(in srgb, currentColor 52%, transparent); - --bp-hover: color-mix(in srgb, currentColor 9%, transparent); +.bp-code-v2 { position: relative; - margin: 14px 0; + margin: 16px 0; overflow: hidden; - border: 1px solid var(--bp-edge); + border: 1px solid var(--bp-border); border-radius: 10px; - background: color-mix(in srgb, currentColor 3.5%, transparent); - font-size: 13px; + background: var(--bp-bg); + color: var(--bp-fg); } - -.bp-code * { box-sizing: border-box; } -.bp-code ::selection { background: color-mix(in srgb, #3b82f6 38%, transparent); } - -.bp-code-head { +.bp-code-v2 * { box-sizing: border-box; } +.bp-code-v2 .bp-code-head { display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; - gap: 12px; - height: 42px; - padding: 0 8px 0 12px; - border-bottom: 1px solid var(--bp-edge); + gap: 8px; + min-height: 44px; + padding: 8px 12px; + border-bottom: 1px solid var(--bp-border); + background: var(--bp-accent); } - -.bp-code-meta { display: flex; align-items: center; gap: 8px; min-width: 0; } -.bp-code-lang { font-size: 13px; font-weight: 500; white-space: nowrap; } -.bp-code-file { overflow: hidden; color: var(--bp-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; } -.bp-code-count { color: var(--bp-muted); font-size: 12px; white-space: nowrap; } -.bp-code-count::before { content: '·'; margin-right: 8px; } -.bp-code-actions { display: flex; flex-shrink: 0; gap: 2px; } - -.bp-code-btn { +.bp-code-v2 .bp-code-meta { display: flex; align-items: center; gap: 8px; min-width: 0; } +.bp-code-v2 .bp-code-lang { font: 600 12px system-ui, sans-serif; } +.bp-code-v2 .bp-code-file { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bp-code-v2 .bp-code-count, .bp-code-v2 .bp-code-file { color: var(--bp-muted); font-size: 11px; } +.bp-code-v2 .bp-code-actions { display: flex; flex-wrap: wrap; gap: 3px; } +.bp-code-v2 .bp-code-btn { display: inline-flex; align-items: center; justify-content: center; - width: 28px; - height: 28px; - border: 0; + width: 30px; + height: 30px; + border: 1px solid transparent; border-radius: 6px; background: transparent; color: var(--bp-muted); cursor: pointer; - transition: background 120ms ease, color 120ms ease; } - -.bp-code-btn:hover { background: var(--bp-hover); color: inherit; } -.bp-code-btn[aria-pressed='true'] { background: var(--bp-hover); color: inherit; } -.bp-code-btn[data-done='true'] { color: hsl(142 71% 45%); } -.bp-code-btn:focus-visible { outline: 2px solid color-mix(in srgb, #3b82f6 70%, transparent); outline-offset: 1px; } - -.bp-code-body { overflow: auto; } -.bp-code[data-collapsed='true'] .bp-code-body { - max-height: calc(var(--bp-code-collapse, 30) * 1.6em + 28px); - overflow: hidden; - -webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - 64px), transparent); - mask-image: linear-gradient(to bottom, #000 calc(100% - 64px), transparent); +.bp-code-v2 .bp-code-btn:hover, +.bp-code-v2 .bp-code-btn[aria-pressed='true'] { + border-color: var(--bp-border); + background: var(--bp-bg); + color: var(--bp-fg); } - -.bp-code-pre { +.bp-code-v2 button:focus-visible, +.bp-code-v2 pre:focus-visible { outline: 2px solid var(--bp-ring); outline-offset: -2px; } +.bp-code-v2 .bp-code-body { overflow: auto; } +.bp-code-v2 .bp-code-scroll { + display: flex; + align-items: stretch; width: max-content; min-width: 100%; + font: 13px/21px ui-monospace, "Cascadia Code", Consolas, monospace; +} +.bp-code-v2 .bp-code-gutter { + flex: none; + padding: 14px 12px; + border-right: 1px solid var(--bp-border); + color: var(--bp-muted); + background: var(--bp-accent); + white-space: pre; + text-align: right; + user-select: none; + font: inherit; +} +.bp-code-v2 .bp-code-native-pre { + flex: 1; + min-width: 0; margin: 0 !important; - padding: 14px 0 !important; + padding: 14px 16px !important; border: 0 !important; background: transparent !important; - font: 13px/1.6 ui-monospace, 'Geist Mono', 'JetBrains Mono', SFMono-Regular, Menlo, Consolas, monospace !important; + color: inherit !important; + font: inherit !important; + white-space: pre !important; + tab-size: 4; overflow: visible !important; - tab-size: 2; - counter-reset: bp-line; } - -.bp-code-pre code { display: block; padding: 0 !important; background: transparent !important; font: inherit !important; } -.bp-code[data-wrap='true'] .bp-code-pre { width: auto; min-width: 0; } - -.bp-line { display: flex; align-items: flex-start; counter-increment: bp-line; } -.bp-line:hover { background: color-mix(in srgb, currentColor 5%, transparent); } - -.bp-num { - flex: 0 0 calc(var(--bp-digits, 2) * 1ch + 30px); - padding-right: 14px; - color: var(--bp-muted); - opacity: .7; - text-align: right; - user-select: none; +.bp-code-v2 .bp-code-source { + display: block; + padding: 0 !important; + background: transparent !important; + color: inherit; + font: inherit !important; + white-space: inherit !important; } - -.bp-num::before { content: counter(bp-line); } -.bp-text { flex: 1; min-width: 0; min-height: 1.6em; padding-right: 16px; white-space: pre; } -.bp-code[data-lines='false'] .bp-num { display: none; } -.bp-code[data-lines='false'] .bp-text { padding-left: 16px; } -.bp-code[data-wrap='true'] .bp-text { white-space: pre-wrap; overflow-wrap: anywhere; } - -.bp-line.add { background: hsl(142 71% 45% / 14%); } -.bp-line.del { background: hsl(0 84% 60% / 14%); } -.bp-line.hunk { color: var(--bp-muted); } - -.bp-tok-comment { color: var(--bp-muted); font-style: italic; } -.bp-tok-string { color: color-mix(in srgb, hsl(28 82% 52%) 72%, currentColor); } -.bp-tok-number { color: color-mix(in srgb, hsl(160 60% 42%) 72%, currentColor); } -.bp-tok-keyword { color: color-mix(in srgb, hsl(285 65% 58%) 74%, currentColor); } -.bp-tok-fn { color: color-mix(in srgb, hsl(215 78% 56%) 74%, currentColor); } -.bp-tok-type { color: color-mix(in srgb, hsl(185 62% 42%) 74%, currentColor); } -.bp-tok-tag { color: color-mix(in srgb, hsl(350 70% 55%) 74%, currentColor); } -.bp-tok-attr { color: color-mix(in srgb, hsl(40 80% 48%) 74%, currentColor); } -.bp-tok-key { color: color-mix(in srgb, hsl(215 70% 55%) 74%, currentColor); } - -.bp-code-more { - position: absolute; - bottom: 12px; - left: 50%; +.bp-code-v2[data-lines='false'] .bp-code-gutter, +.bp-code-v2[data-wrap='true'] .bp-code-gutter { display: none; } +.bp-code-v2[data-wrap='true'] .bp-code-scroll { width: 100%; } +.bp-code-v2[data-wrap='true'] .bp-code-native-pre { + white-space: pre-wrap !important; + overflow-wrap: anywhere; +} +.bp-code-v2[data-collapsed='true'] .bp-code-body { + max-height: calc(var(--bp-code-collapse, 30) * 21px + 28px); + overflow: hidden; +} +.bp-code-v2 .bp-code-more { display: none; - height: 32px; - padding: 0 14px; - border: 1px solid var(--bp-edge); - border-radius: 6px; - background: color-mix(in srgb, currentColor 8%, Canvas); - color: inherit; - font: inherit; - font-size: 12.5px; - font-weight: 500; - transform: translateX(-50%); + width: 100%; + padding: 9px; + border: 0; + border-top: 1px solid var(--bp-border); + background: var(--bp-accent); + color: var(--bp-fg); cursor: pointer; } - -.bp-code[data-collapsed='true'] .bp-code-more { display: block; } -.bp-code-more:hover { background: color-mix(in srgb, currentColor 14%, Canvas); } - -.bp-lang-icon { flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border-radius: 6px; } -.bp-lang-badge { - background: linear-gradient(145deg, var(--c), color-mix(in srgb, var(--c) 70%, #000)); - box-shadow: inset 0 0 0 1px rgb(255 255 255 / 20%), 0 1px 2px rgb(0 0 0 / 28%); - font: 700 9.5px/1 ui-sans-serif, system-ui, sans-serif; - letter-spacing: -.03em; +.bp-code-v2[data-collapsed='true'] .bp-code-more { display: block; } +.bp-code-v2 ::selection { background: rgb(59 130 246 / 25%); } +.bp-code-v2 .bp-tok-comment { color: var(--bp-muted); font-style: italic; } +.bp-code-v2 .bp-tok-keyword { color: #a855f7; } +.bp-code-v2 .bp-tok-string { color: #b45309; } +.bp-code-v2 .bp-tok-number { color: #059669; } +.bp-code-v2 .bp-tok-fn { color: #2563eb; } +.bp-code-v2 .bp-tok-type { color: #0891b2; } +.bp-code-v2 .bp-tok-tag { color: #e11d48; } +.bp-code-v2 .bp-tok-attr, .bp-code-v2 .bp-tok-key { color: #2563eb; } +.bp-code-v2 .bp-lang-icon { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 22px; + height: 22px; + padding: 2px; + border: 1px solid var(--bp-border); + border-radius: 5px; + color: var(--bp-fg); + font: 600 10px system-ui, sans-serif; } -.bp-lang-badge[data-size='3'] { font-size: 8px; } -.bp-lang-badge[data-size='4'] { font-size: 6.8px; letter-spacing: -.05em; } -.bp-lang-plain { color: var(--bp-muted); } ` -export const ensureCodeStyles = (): void => injectStyle(`${uiConfig().id}-code-styles`, CSS) \ No newline at end of file +export const ensureCodeStyles = (): void => injectStyle(`${uiConfig().id}-code-v2-styles`, CSS) diff --git a/core/ai/src/ui/css.ts b/core/ai/src/ui/css.ts index 3dc2e85..08fb696 100644 --- a/core/ai/src/ui/css.ts +++ b/core/ai/src/ui/css.ts @@ -289,6 +289,32 @@ 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; } + +.bp-dialog .bp-button { + min-height: 34px; + border-radius: 6px; + box-shadow: 0 1px 2px rgb(0 0 0 / 4%); +} +.bp-dialog .bp-input { + min-height: 36px; + border-radius: 6px; +} +.bp-dialog .bp-input::placeholder { color: var(--bp-muted); } +.bp-dialog .bp-section-heading { + color: var(--bp-fg); + font-size: 12px; + font-weight: 600; + letter-spacing: 0; + text-transform: none; +} +.bp-dialog .bp-data-row { + align-items: flex-start; + padding: 10px 12px; +} +.bp-dialog .bp-data-label { flex: 0 1 42%; } +.bp-dialog .bp-data-value { flex: 1; font-variant-numeric: tabular-nums; } +.bp-dialog .bp-actions { gap: 8px; margin-top: 10px; } +.bp-dialog .bp-switch { border-radius: 8px; } ` export const TOOLTIP_CSS = `