diff --git a/core/ai/src/features/code-blocks/badges.ts b/core/ai/src/features/code-blocks/badges.ts index 373543e..d6060a2 100644 --- a/core/ai/src/features/code-blocks/badges.ts +++ b/core/ai/src/features/code-blocks/badges.ts @@ -4,36 +4,36 @@ import { createIcon } from '../../ui/icons' type Badge = readonly [label: string, background: string, color: string] const BADGES: Readonly> = { - javascript: ['JS', '#f7df1e', '#000'], typescript: ['TS', '#3178c6', '#fff'], python: ['PY', '#3776ab', '#ffd43b'], - bash: ['>_', '#3b8f2b', '#fff'], powershell: ['PS', '#012456', '#fff'], batch: ['BAT', '#4d4d4d', '#fff'], - json: ['{}', '#e9a620', '#000'], yaml: ['YML', '#cb171e', '#fff'], toml: ['TOML', '#9c4221', '#fff'], - html: ['', '#e34f26', '#fff'], xml: ['XML', '#0060ac', '#fff'], css: ['CSS', '#1572b6', '#fff'], - sql: ['SQL', '#e48e00', '#000'], graphql: ['GQL', '#e10098', '#fff'], protobuf: ['PB', '#4a7fb0', '#fff'], - go: ['GO', '#00add8', '#fff'], rust: ['RS', '#ce422b', '#fff'], zig: ['ZIG', '#f7a41d', '#000'], nim: ['NIM', '#ffe953', '#000'], - java: ['JV', '#e76f00', '#fff'], kotlin: ['KT', '#7f52ff', '#fff'], scala: ['SC', '#dc322f', '#fff'], groovy: ['GRV', '#4298b8', '#fff'], - swift: ['SW', '#f05138', '#fff'], objectivec: ['OBJ', '#438eff', '#fff'], dart: ['DRT', '#0175c2', '#fff'], - c: ['C', '#00599c', '#fff'], cpp: ['C++', '#00599c', '#fff'], csharp: ['C#', '#68217a', '#fff'], - php: ['PHP', '#777bb4', '#fff'], ruby: ['RB', '#cc342d', '#fff'], perl: ['PL', '#39457e', '#fff'], lua: ['LUA', '#000080', '#fff'], - r: ['R', '#276dc3', '#fff'], julia: ['JL', '#9558b2', '#fff'], matlab: ['M', '#e16737', '#fff'], - haskell: ['HS', '#5d4f85', '#fff'], elixir: ['EX', '#6e4a7e', '#fff'], clojure: ['CLJ', '#5881d8', '#fff'], - solidity: ['SOL', '#363636', '#fff'], assembly: ['ASM', '#6e4c13', '#fff'], vim: ['VIM', '#019733', '#fff'], - nginx: ['NGX', '#009639', '#fff'], makefile: ['MK', '#6d8086', '#fff'], dockerfile: ['DK', '#2496ed', '#fff'], - latex: ['TEX', '#008080', '#fff'], markdown: ['M↓', '#083fa1', '#fff'], diff: ['±', '#6f42c1', '#fff'], - regex: ['.*', '#6f42c1', '#fff'], http: ['HTTP', '#1f6feb', '#fff'], log: ['LOG', '#6e7681', '#fff'], csv: ['CSV', '#217346', '#fff'] + javascript: ['JS', '#f7df1e', '#000'], typescript: ['TS', '#3178c6', '#fff'], python: ['PY', '#3776ab', '#ffd43b'], + bash: ['>_', '#3b8f2b', '#fff'], powershell: ['PS', '#012456', '#fff'], batch: ['BAT', '#4d4d4d', '#fff'], + json: ['{}', '#e9a620', '#000'], yaml: ['YML', '#cb171e', '#fff'], toml: ['TOML', '#9c4221', '#fff'], + html: ['', '#e34f26', '#fff'], xml: ['XML', '#0060ac', '#fff'], css: ['CSS', '#1572b6', '#fff'], + sql: ['SQL', '#e48e00', '#000'], graphql: ['GQL', '#e10098', '#fff'], protobuf: ['PB', '#4a7fb0', '#fff'], + go: ['GO', '#00add8', '#fff'], rust: ['RS', '#ce422b', '#fff'], zig: ['ZIG', '#f7a41d', '#000'], nim: ['NIM', '#ffe953', '#000'], + java: ['JV', '#e76f00', '#fff'], kotlin: ['KT', '#7f52ff', '#fff'], scala: ['SC', '#dc322f', '#fff'], groovy: ['GRV', '#4298b8', '#fff'], + swift: ['SW', '#f05138', '#fff'], objectivec: ['OBJ', '#438eff', '#fff'], dart: ['DRT', '#0175c2', '#fff'], + c: ['C', '#00599c', '#fff'], cpp: ['C++', '#00599c', '#fff'], csharp: ['C#', '#68217a', '#fff'], + php: ['PHP', '#777bb4', '#fff'], ruby: ['RB', '#cc342d', '#fff'], perl: ['PL', '#39457e', '#fff'], lua: ['LUA', '#000080', '#fff'], + r: ['R', '#276dc3', '#fff'], julia: ['JL', '#9558b2', '#fff'], matlab: ['M', '#e16737', '#fff'], + haskell: ['HS', '#5d4f85', '#fff'], elixir: ['EX', '#6e4a7e', '#fff'], clojure: ['CLJ', '#5881d8', '#fff'], + solidity: ['SOL', '#363636', '#fff'], assembly: ['ASM', '#6e4c13', '#fff'], vim: ['VIM', '#019733', '#fff'], + nginx: ['NGX', '#009639', '#fff'], makefile: ['MK', '#6d8086', '#fff'], dockerfile: ['DK', '#2496ed', '#fff'], + latex: ['TEX', '#008080', '#fff'], markdown: ['M↓', '#083fa1', '#fff'], diff: ['±', '#6f42c1', '#fff'], + regex: ['.*', '#6f42c1', '#fff'], http: ['HTTP', '#1f6feb', '#fff'], log: ['LOG', '#6e7681', '#fff'], csv: ['CSV', '#217346', '#fff'] } export const createLanguageIcon = (language: string): HTMLElement => { - const badge = BADGES[language] - if (!badge) { - const plain = createElement('span', 'bp-lang-icon bp-lang-plain') - plain.title = 'Plain text' - plain.appendChild(createIcon('file', 16)) - return plain - } - const [label, background, color] = badge - const element = createElement('span', 'bp-lang-icon bp-lang-badge', label) - element.style.setProperty('--c', background) - element.style.color = color - element.dataset['size'] = String(label.length) - return element -} \ No newline at end of file + const badge = BADGES[language] + if (!badge) { + const plain = createElement('span', 'bp-lang-icon bp-lang-plain') + plain.title = 'Plain text' + plain.appendChild(createIcon('file', 16)) + return plain + } + const [label, background, color] = badge + const element = createElement('span', 'bp-lang-icon bp-lang-badge', label) + element.style.setProperty('--c', background) + element.style.setProperty('--badge-fg', color) + element.dataset['size'] = String(label.length) + return element +} diff --git a/core/ai/src/features/code-blocks/styles.ts b/core/ai/src/features/code-blocks/styles.ts index e060743..f9c3046 100644 --- a/core/ai/src/features/code-blocks/styles.ts +++ b/core/ai/src/features/code-blocks/styles.ts @@ -1,5 +1,6 @@ import { injectStyle } from '@nolly/core' import { uiConfig } from '../../ui/config' +import { ensureCodeTheme } from './theme' const CSS = ` .bp-code-v2 { @@ -133,4 +134,7 @@ const CSS = ` } ` -export const ensureCodeStyles = (): void => injectStyle(`${uiConfig().id}-code-v2-styles`, CSS) +export const ensureCodeStyles = (): void => { + injectStyle(`${uiConfig().id}-code-v2-styles`, CSS) + ensureCodeTheme() +} diff --git a/core/ai/src/features/code-blocks/theme.ts b/core/ai/src/features/code-blocks/theme.ts new file mode 100644 index 0000000..a42619d --- /dev/null +++ b/core/ai/src/features/code-blocks/theme.ts @@ -0,0 +1,84 @@ +import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' + +let installed = false + +const CSS = ` +html[data-bp-code-theme='light'] .bp-code-v2 { + --bp-bg: #ffffff; + --bp-fg: #1f2328; + --bp-muted: #59636e; + --bp-border: #d1d9e0; + --bp-accent: #f6f8fa; + --bp-ring: #0969da; + --bp-code-keyword: #cf222e; + --bp-code-string: #0a3069; + --bp-code-number: #0550ae; + --bp-code-function: #8250df; + --bp-code-type: #953800; + --bp-code-tag: #116329; + --bp-code-attribute: #0550ae; + color-scheme: light; +} +html[data-bp-code-theme='dark'] .bp-code-v2 { + --bp-bg: #0d1117; + --bp-fg: #e6edf3; + --bp-muted: #9198a1; + --bp-border: #30363d; + --bp-accent: #161b22; + --bp-ring: #58a6ff; + --bp-code-keyword: #ff7b72; + --bp-code-string: #a5d6ff; + --bp-code-number: #79c0ff; + --bp-code-function: #d2a8ff; + --bp-code-type: #ffa657; + --bp-code-tag: #7ee787; + --bp-code-attribute: #79c0ff; + color-scheme: dark; +} +.bp-code-v2 .bp-tok-comment { color: var(--bp-muted); } +.bp-code-v2 .bp-tok-keyword { color: var(--bp-code-keyword); } +.bp-code-v2 .bp-tok-string { color: var(--bp-code-string); } +.bp-code-v2 .bp-tok-number { color: var(--bp-code-number); } +.bp-code-v2 .bp-tok-fn { color: var(--bp-code-function); } +.bp-code-v2 .bp-tok-type { color: var(--bp-code-type); } +.bp-code-v2 .bp-tok-tag { color: var(--bp-code-tag); } +.bp-code-v2 .bp-tok-attr, +.bp-code-v2 .bp-tok-key { color: var(--bp-code-attribute); } +.bp-code-v2 .bp-lang-badge { + background: var(--c); + color: var(--badge-fg); + border-color: transparent; + font-weight: 700; +} +.bp-code-v2 .bp-code-head { box-shadow: none; } +.bp-code-v2 .bp-code-btn { transition: background 120ms ease, color 120ms ease; } +` + +const explicitTheme = (element: HTMLElement): 'dark' | 'light' | null => { + if (element.classList.contains('dark')) return 'dark' + if (element.classList.contains('light')) return 'light' + for (const attribute of ['data-theme', 'data-color-mode', 'data-color-scheme']) { + const value = element.getAttribute(attribute)?.toLowerCase() + if (value === 'dark' || value === 'light') return value + } + const scheme = getComputedStyle(element).colorScheme.trim() + return scheme === 'dark' || scheme === 'light' ? scheme : null +} + +export const ensureCodeTheme = (): void => { + injectStyle(`${uiConfig().id}-code-v2-theme`, CSS) + if (installed) return + installed = true + const media = window.matchMedia('(prefers-color-scheme: dark)') + const update = (): void => { + const theme = explicitTheme(document.documentElement) ?? (document.body ? explicitTheme(document.body) : null) ?? (media.matches ? 'dark' : 'light') + if (document.documentElement.dataset['bpCodeTheme'] !== theme) document.documentElement.dataset['bpCodeTheme'] = theme + } + const observer = new MutationObserver(update) + const options: MutationObserverInit = { attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-mode', 'data-color-scheme', 'style'] } + observer.observe(document.documentElement, options) + if (document.body) observer.observe(document.body, options) + media.addEventListener('change', update) + update() +} diff --git a/core/ai/src/features/enter-as-newline/config-button.ts b/core/ai/src/features/enter-as-newline/config-button.ts index 2c1609e..834c9a9 100644 --- a/core/ai/src/features/enter-as-newline/config-button.ts +++ b/core/ai/src/features/enter-as-newline/config-button.ts @@ -2,6 +2,7 @@ import { createElement, injectStyle } from '@nolly/core' import { markUi, uiConfig } from '../../ui/config' import { ensureUiStyles } from '../../ui/styles' import { Tooltip } from '../../ui/tooltip' +import { mountComposerTool, unmountComposerTool } from '../../ui/composer-toolbar' const SVG_NS = 'http://www.w3.org/2000/svg' @@ -31,7 +32,6 @@ const createIcon = (): SVGSVGElement => { export class ConfigButton { readonly element = markUi(createElement('button', 'bp-config-button')) private readonly tooltip: Tooltip - private appliedClass = '' constructor(onClick: () => void, describe: () => string) { ensureUiStyles() @@ -50,27 +50,11 @@ export class ConfigButton { } 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() - } + if (!mountComposerTool(this.element, 'config')) this.tooltip.hide() + } - private syncClass(reference: HTMLElement): void { - const next = `${reference.className} bp-config-button` - if (next === this.appliedClass) return - this.element.className = next - this.appliedClass = next - } + unmount(): void { + this.tooltip.hide() + unmountComposerTool(this.element, 'config') + } } diff --git a/core/ai/src/features/max-width/feature.ts b/core/ai/src/features/max-width/feature.ts index c301512..8f51726 100644 --- a/core/ai/src/features/max-width/feature.ts +++ b/core/ai/src/features/max-width/feature.ts @@ -5,112 +5,134 @@ 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 EXCLUDED = ['header', 'pre', 'code', '[data-code-block]', '[role="dialog"]', '[role="menu"]', '[role="listbox"]', '[role="tooltip"]', 'dialog', '[data-radix-popper-content-wrapper]'].join(', ') + const SCAN_INTERVAL = 1_200 +const GUTTER = '12px' export interface Target { - readonly xpath?: string - readonly selector?: string + readonly xpath?: string + readonly selector?: string } export interface HideRule extends Target { - readonly id: string + readonly id: string } export interface LayoutRule extends Target { - readonly styles: Readonly> + readonly styles: Readonly> } export interface SidebarOption { - readonly rule: HideRule - readonly label: string - readonly defaultRemoved: boolean + 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 + 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 + if (xpath) return getElement(xpath) + return selector ? document.querySelector(selector) : null } -const labelOf = (rule: HideRule): string => rule.xpath ?? rule.selector ?? rule.id +const safeTarget = (element: HTMLElement): boolean => element.isConnected && !isOwnUi(element) && !element.closest(EXCLUDED) && element.closest('main') !== null 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() - } + readonly id = 'max-width' + readonly name = 'Max Width' + readonly description = 'Use the available content width without overflowing the page or removing its side padding.' + + private readonly styles = new StyleManager() + private readonly touched = new Map>() + 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) + if (!active) { + this.restore() + return + } + for (const rule of this.options.layout ?? []) { + const element = resolveTarget(rule) + if (!element || !safeTarget(element)) continue + this.apply(element, { ...rule.styles, 'box-sizing': 'border-box', 'min-width': '0', 'max-width': '100%' }) + } + this.expand() + } + + override onDisable(): void { + this.restore() + for (const rule of this.options.hidden ?? []) this.syncHidden(rule, false) + if (this.options.sidebar) this.syncHidden(this.options.sidebar.rule, false) + } + + override menuEntries(): MenuEntry[] { + const sidebar = this.options.sidebar + return sidebar ? [{ + label: `${this.removeSidebar ? 'Show' : 'Remove'} ${sidebar.label}`, + action: () => { + this.removeSidebar = !this.removeSidebar + this.context.refreshMenu() + this.context.requestUpdate() + } + }] : [] + } + + private apply(element: HTMLElement, values: Readonly>): void { + const properties = this.touched.get(element) ?? new Set() + for (const property of Object.keys(values)) properties.add(property) + this.touched.set(element, properties) + this.styles.apply(element, values) + } + + private expand(): void { + const now = Date.now() + if (now - this.scannedAt < SCAN_INTERVAL) return + this.scannedAt = now + for (const element of this.touched.keys()) { + if (!element.isConnected) this.touched.delete(element) + } + const candidates = [...document.querySelectorAll(this.options.constrained ?? DEFAULT_CONSTRAINED)].filter((element) => { + if (!safeTarget(element)) return false + const rect = element.getBoundingClientRect() + if (rect.width < 320) return false + const maximum = Number.parseFloat(getComputedStyle(element).maxWidth) + return this.touched.has(element) || Number.isFinite(maximum) && maximum >= 480 + }) + const outermost = candidates.filter((element) => !candidates.some((other) => other !== element && other.contains(element))) + for (const element of candidates) this.apply(element, { 'box-sizing': 'border-box', 'min-width': '0', 'max-width': '100%' }) + for (const element of outermost) this.apply(element, { 'padding-inline-start': GUTTER, 'padding-inline-end': GUTTER }) + } + + private syncHidden(rule: HideRule, hidden: boolean): void { + const element = resolveTarget(rule) + if (element) this.styles.setHidden(element, hidden, rule.xpath ?? rule.selector ?? rule.id) + } + + private restore(): void { + for (const [element, properties] of this.touched) this.styles.restore(element, [...properties]) + this.touched.clear() + this.scannedAt = 0 + } } diff --git a/core/ai/src/features/max-width/style-manager.ts b/core/ai/src/features/max-width/style-manager.ts index c86237b..38e3765 100644 --- a/core/ai/src/features/max-width/style-manager.ts +++ b/core/ai/src/features/max-width/style-manager.ts @@ -1,50 +1,40 @@ -import { logger } from '../../platform' - interface OriginalValue { - readonly value: string - readonly priority: string + readonly value: string + readonly priority: string } export class StyleManager { - private readonly originals = new WeakMap>() - private readonly hidden = new WeakSet() + private readonly originals = new WeakMap>() + private readonly hidden = new WeakSet() - apply(element: HTMLElement, styles: Readonly>): void { - const originals = this.originals.get(element) ?? new Map() - this.originals.set(element, originals) - for (const [property, value] of Object.entries(styles)) { - if (!originals.has(property)) originals.set(property, { value: element.style.getPropertyValue(property), priority: element.style.getPropertyPriority(property) }) - if (element.style.getPropertyValue(property) === value && element.style.getPropertyPriority(property) === 'important') continue - element.style.setProperty(property, value, 'important') - } - } + apply(element: HTMLElement, styles: Readonly>): void { + const originals = this.originals.get(element) ?? new Map() + this.originals.set(element, originals) + for (const [property, value] of Object.entries(styles)) { + if (!originals.has(property)) originals.set(property, {value: element.style.getPropertyValue(property),priority: element.style.getPropertyPriority(property)}) + if (element.style.getPropertyValue(property) !== value|| element.style.getPropertyPriority(property) !== 'important') element.style.setProperty(property, value, 'important') + } + } - restore(element: HTMLElement, properties: readonly string[]): void { - const originals = this.originals.get(element) - if (!originals) return - for (const property of properties) { - const original = originals.get(property) - if (!original) continue - if (original.value) element.style.setProperty(property, original.value, original.priority) - else element.style.removeProperty(property) - originals.delete(property) - } - } + restore(element: HTMLElement, properties: readonly string[]): void { + const originals = this.originals.get(element) + if (!originals) return + for (const property of properties) { + const original = originals.get(property) + if (!original) continue + if (original.value) element.style.setProperty(property, original.value, original.priority) + else element.style.removeProperty(property) + originals.delete(property) + } + } - setHidden(element: HTMLElement, hidden: boolean, label: string): void { - if (hidden) { - const applied = element.style.getPropertyValue('display') === 'none' && element.style.getPropertyPriority('display') === 'important' - if (applied) return - element.style.setProperty('display', 'none', 'important') - if (!this.hidden.has(element)) { - this.hidden.add(element) - logger.debug('Element hidden.', label) - } - return - } - if (!this.hidden.has(element)) return - element.style.removeProperty('display') - this.hidden.delete(element) - logger.debug('Element restored.', label) - } + setHidden(element: HTMLElement, hidden: boolean, _label: string): void { + if (hidden) { + this.apply(element, { display: 'none' }) + this.hidden.add(element) + } else if (this.hidden.has(element)) { + this.restore(element, ['display']) + this.hidden.delete(element) + } + } } diff --git a/core/ai/src/ui/composer-button.ts b/core/ai/src/ui/composer-button.ts index 7417ad1..8a3866a 100644 --- a/core/ai/src/ui/composer-button.ts +++ b/core/ai/src/ui/composer-button.ts @@ -1,59 +1,39 @@ import { createElement } from '@nolly/core' -import { markUi, uiConfig } from './config' -import type { ComposerActions } from './config' +import { markUi } from './config' +import { mountComposerTool, unmountComposerTool } from './composer-toolbar' import { createIcon, type IconName } from './icons' import { ensureUiStyles } from './styles' import { Tooltip } from './tooltip' export interface ComposerButtonOptions { - id: string - after?: readonly string[] + id: string + after?: readonly string[] } -const CONFIG_BUTTON = '.bp-config-button' -const NO_ACTIONS: ComposerActions = { first: null, submit: null } - export class ComposerButton { - readonly element = markUi(createElement('button')) - private readonly tooltip: Tooltip - private appliedClass = '' + readonly element = markUi(createElement('button')) + private readonly tooltip: Tooltip - constructor(label: string, icon: IconName, hint: string, onClick: () => void, private readonly options: ComposerButtonOptions) { - ensureUiStyles() - this.element.type = 'button' - this.element.setAttribute('aria-label', label) - this.element.style.cssText = 'display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;cursor:pointer' - this.element.appendChild(createIcon(icon)) - this.element.addEventListener('click', (event) => { - event.preventDefault() - event.stopPropagation() - onClick() - }) - this.tooltip = new Tooltip(this.element, (container) => container.append(createElement('div', 'bp-tip-mode', label), createElement('div', 'bp-tip-sub', hint))) - } + constructor(label: string, icon: IconName, hint: string, onClick: () => void, private readonly options: ComposerButtonOptions) { + ensureUiStyles() + this.element.className = `bp-composer-button bp-cb-${options.id}` + this.element.type = 'button' + this.element.setAttribute('aria-label', label) + this.element.appendChild(createIcon(icon, 16)) + this.element.addEventListener('click', (event) => { + event.preventDefault() + event.stopPropagation() + onClick() + }) + this.tooltip = new Tooltip(this.element, (container) => container.append(createElement('div', 'bp-tip-mode', label), createElement('div', 'bp-tip-sub', hint))) + } - mount(): void { - 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) { - this.unmount() - return - } - const className = `${first?.className ?? ''} bp-composer-button bp-cb-${this.options.id}` - if (className !== this.appliedClass) { - this.element.className = className - this.appliedClass = className - } - if (anchor) { - if (anchor.nextElementSibling !== this.element) anchor.insertAdjacentElement('afterend', this.element) - return - } - if (submit && submit.previousElementSibling !== this.element) submit.insertAdjacentElement('beforebegin', this.element) - } + mount(): void { + if (!mountComposerTool(this.element, this.options.id)) this.tooltip.hide() + } - unmount(): void { - this.tooltip.hide() - this.element.remove() - } + unmount(): void { + this.tooltip.hide() + unmountComposerTool(this.element, this.options.id) + } } diff --git a/core/ai/src/ui/composer-toolbar.ts b/core/ai/src/ui/composer-toolbar.ts new file mode 100644 index 0000000..7c5a4d4 --- /dev/null +++ b/core/ai/src/ui/composer-toolbar.ts @@ -0,0 +1,129 @@ +import { createElement, injectStyle } from '@nolly/core' +import { platform } from '../platform' +import { markUi, uiConfig } from './config' + +const ORDER = ['config', 'big', 'prompts', 'batch', 'queue', 'recall', 'context'] +const MODE = /^(?:switch to |select |use )?(?:pro search|pro|search|deep research|research|labs?|computer|agentic(?: research)?|think|thinking)(?: mode)?$/i +const EXCLUDED = 'header, aside, dialog, [role="dialog"], [data-code-block], .cm-editor' +const tools = new Map() +let dock: HTMLElement | null = null + +const CSS = ` +.bp-composer-tools { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 3px; + min-width: 0; + max-width: 100%; + margin-inline-start: 6px; + pointer-events: auto; + vertical-align: middle; +} +.bp-composer-tools > button { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 30px; + height: 30px; + padding: 0; + border: 1px solid transparent; + border-radius: 6px; + background: transparent; + color: var(--bp-muted); + cursor: pointer; + pointer-events: auto; +} +.bp-composer-tools > button:hover { + border-color: var(--bp-border); + background: var(--bp-accent); + color: var(--bp-fg); +} +.bp-composer-tools > button:focus-visible { + outline: 2px solid var(--bp-ring); + outline-offset: 1px; +} +.bp-composer-tools svg { pointer-events: none; } +` + +const labelOf = (element: HTMLElement): string => (element.getAttribute('aria-label') || element.textContent || '').replace(/\s+/g, ' ').trim() + +const locate = (): { parent: HTMLElement; after: HTMLElement | null } | null => { + const editable = platform().composer.findComposer() + if (!editable?.isConnected || editable.closest(EXCLUDED)) return null + const actions = uiConfig().composerActions?.() + const submit = actions?.submit + if (!submit?.isConnected || submit.closest(EXCLUDED)) return null + let scope = editable.parentElement + let root: HTMLElement | null = null + for (let depth = 0; scope && depth < 8; depth++, scope = scope.parentElement) { + if (scope === document.body || scope.tagName === 'MAIN') break + if (scope.contains(submit)) { + root = scope + break + } + } + if (!root) return null + const modes = [...root.querySelectorAll('button, [role="tab"], [role="radio"]')].filter((element) => { + const rect = element.getBoundingClientRect() + return !uiConfig().marker.isOwn(element) && !element.closest(EXCLUDED) && MODE.test(labelOf(element)) && rect.width > 0 && rect.height > 0 + }) + const lastMode = modes.at(-1) + if (lastMode) { + let anchor = lastMode + for (let depth = 0; depth < 4; depth++) { + const parent = anchor.parentElement + if (!parent || parent === root) break + const display = getComputedStyle(parent).display + if (display === 'flex' || display === 'inline-flex') return { parent, after: anchor } + anchor = parent + } + if (lastMode.parentElement) return { parent: lastMode.parentElement, after: lastMode } + } + const first = actions?.first + if (first?.isConnected && root.contains(first) && first.parentElement) return { parent: first.parentElement, after: first } + return submit.parentElement ? { parent: submit.parentElement, after: null } : null +} + +const mountDock = (): boolean => { + const location = locate() + if (!location) { + dock?.remove() + return false + } + if (!dock) { + dock = markUi(createElement('div', 'bp-composer-tools bp-themed')) + dock.setAttribute('role', 'group') + dock.setAttribute('aria-label', 'Better AI composer tools') + injectStyle(`${uiConfig().id}-composer-tools`, CSS) + } + if (location.after) { + if (location.after.nextElementSibling !== dock) location.after.insertAdjacentElement('afterend', dock) + } else { + const submit = uiConfig().composerActions?.().submit + if (!submit || submit.parentElement !== location.parent) return false + if (submit.previousElementSibling !== dock) location.parent.insertBefore(dock, submit) + } + const entries = [...tools.entries()].sort(([a], [b]) => { + const left = ORDER.indexOf(a) + const right = ORDER.indexOf(b) + return (left < 0 ? 100 : left) - (right < 0 ? 100 : right) || a.localeCompare(b) + }) + entries.forEach(([, element], index) => { + const expected = dock!.children[index] ?? null + if (expected !== element) dock!.insertBefore(element, expected) + }) + return true +} + +export const mountComposerTool = (element: HTMLElement, id: string): boolean => { + tools.set(id, element) + return mountDock() +} + +export const unmountComposerTool = (element: HTMLElement, id: string): void => { + if (tools.get(id) === element) tools.delete(id) + element.remove() + if (!tools.size) dock?.remove() +}