Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/web/modules/nova-web/chat-appearance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ import { describe, expect, test } from "bun:test"
import { contrastingText, DEFAULT_CHAT_APPEARANCE, parseChatAppearance } from "./chat-appearance"

describe("chat appearance", () => {
test("restores and bounds background adjustments", () => {
const appearance = parseChatAppearance(JSON.stringify({ effect: "image", brightness: 250, blur: -1, imageOpacity: 55, bottomFade: 30, overlayOpacity: 20, inputOpacity: 70 }))
expect(appearance).toMatchObject({ effect: "image", brightness: 200, blur: 0, imageOpacity: 55, bottomFade: 30, overlayOpacity: 20, inputOpacity: 70 })
expect(parseChatAppearance(JSON.stringify({ effect: "unknown", brightness: "100" }))).toEqual(DEFAULT_CHAT_APPEARANCE)
})
test("restores a selected bundled background and ignores unknown images", () => {
expect(parseChatAppearance(JSON.stringify({ image: "clouds" })).image).toBe("clouds")
expect(parseChatAppearance(JSON.stringify({ image: "https://example.com/image" })).image).toBeUndefined()
})
test("uses defaults for missing or corrupt preferences", () => {
for (const raw of [null, "bad json", "null", "42"]) {
expect(parseChatAppearance(raw)).toEqual(DEFAULT_CHAT_APPEARANCE)
Expand Down
26 changes: 26 additions & 0 deletions apps/web/modules/nova-web/chat-appearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@ export type ChatAppearance = {
background: string
ascii: string
text: string | null
image?: "night" | "clouds"
effect?: "ascii" | "image"
brightness?: number
blur?: number
imageOpacity?: number
bottomFade?: number
overlayOpacity?: number
inputOpacity?: number
}

export const BACKGROUND_DEFAULTS = {
effect: "ascii" as const,
brightness: 100,
blur: 0,
imageOpacity: 100,
bottomFade: 40,
overlayOpacity: 0,
inputOpacity: 85,
}

export const DEFAULT_CHAT_APPEARANCE: ChatAppearance = {
Expand All @@ -27,10 +45,18 @@ export function parseChatAppearance(raw: string | null): ChatAppearance {
const record = value as Record<string, unknown>
const color = (key: string, fallback: string) =>
typeof record[key] === "string" && HEX_COLOR.test(record[key]) ? record[key] : fallback
const adjustments: Partial<ChatAppearance> = {}
for (const [key, max] of [["brightness", 200], ["blur", 20], ["imageOpacity", 100], ["bottomFade", 100], ["overlayOpacity", 100], ["inputOpacity", 100]] as const) {
const number = record[key]
if (typeof number === "number" && Number.isFinite(number)) adjustments[key] = Math.max(0, Math.min(max, number))
}
return {
background: color("background", DEFAULT_CHAT_APPEARANCE.background),
ascii: color("ascii", DEFAULT_CHAT_APPEARANCE.ascii),
text: typeof record.text === "string" && HEX_COLOR.test(record.text) ? record.text : null,
...(record.image === "clouds" ? { image: "clouds" as const } : {}),
...(record.effect === "image" ? { effect: "image" as const } : {}),
...adjustments,
}
} catch {
return DEFAULT_CHAT_APPEARANCE
Expand Down
173 changes: 62 additions & 111 deletions apps/web/modules/nova-web/components/ascii-background.tsx
Original file line number Diff line number Diff line change
@@ -1,97 +1,79 @@
"use client"

import { memo, useEffect, useRef, useState, useSyncExternalStore } from "react"
import { motion, useReducedMotion } from "framer-motion"
import { Pause, Play } from "lucide-react"
import { memo, useEffect, useRef } from "react"

const GLYPHS = " .,:;~+=*#"
const FRAME_MS = 1000 / 30
import { BACKGROUND_DEFAULTS, type ChatAppearance } from "../chat-appearance"

const subscribeToHydration = () => () => {}
const clientSnapshot = () => true
const serverSnapshot = () => false
const GLYPHS = " .,:;+=xX#%@"

export const AsciiBackground = memo(function AsciiBackground({ color = "#a3aaa7" }: { color?: string }) {
/** Samples a bundled image into a bounded grid; redraws only when the image or viewport changes. */
export const AsciiBackground = memo(function AsciiBackground({
color = "#a3aaa7",
image = "/nova/ascii-night.webp",
appearance,
}: { color?: string; image?: string; appearance?: ChatAppearance }) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const elapsedRef = useRef(0)
const reducedMotion = useReducedMotion()
const hydrated = useSyncExternalStore(subscribeToHydration, clientSnapshot, serverSnapshot)
const [paused, setPaused] = useState(false)

useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const context = canvas.getContext("2d")
if (!context) return

const context = canvas?.getContext("2d")
if (!canvas || !context) return
const sample = document.createElement("canvas")
const sampler = sample.getContext("2d", { willReadFrequently: true })
if (!sampler) return
const source = new Image()
let width = 0
let height = 0
let frame = 0
let previous = 0
let lastPaint = 0
let visible = true
const animate = reducedMotion === false && !paused
let disposed = false

function draw() {
if (!context) return
if (!width || !height || !source.naturalWidth || !source.naturalHeight || !context || !sampler || !canvas) return
if (appearance?.effect === "image") {
const scale = Math.max(width / source.naturalWidth, height / source.naturalHeight)
const imageWidth = source.naturalWidth * scale
const imageHeight = source.naturalHeight * scale
context.clearRect(0, 0, width, height)
context.drawImage(source, (width - imageWidth) / 2, (height - imageHeight) / 2, imageWidth, imageHeight)
Comment on lines +31 to +36

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Automatic text blends into photos

Automatic text contrast still uses only appearance.background, but Original image covers that color at full opacity by default. The heading and project controls have no solid backing. For example, Paper keeps black text even when the brightness slider darkens the photo behind it. Add a contrast-preserving backing for this text, or account for the displayed image when choosing its automatic color.

return
}
const cell = Math.max(7, width / 180, height / 110)
const columns = Math.max(1, Math.ceil(width / cell))
const rows = Math.max(1, Math.ceil(height / (cell * 1.15)))
sample.width = columns
sample.height = rows
const scale = Math.max(columns / source.naturalWidth, rows / source.naturalHeight)
const imageWidth = source.naturalWidth * scale
const imageHeight = source.naturalHeight * scale
sampler.drawImage(source, (columns - imageWidth) / 2, (rows - imageHeight) / 2, imageWidth, imageHeight)
const pixels = sampler.getImageData(0, 0, columns, rows).data
context.clearRect(0, 0, width, height)
context.font = "10px ui-monospace, SFMono-Regular, Menlo, monospace"
context.font = `${cell * 1.05}px ui-monospace, SFMono-Regular, Menlo, monospace`
context.textAlign = "center"
context.textBaseline = "middle"
context.fillStyle = color
const time = elapsedRef.current * 0.0003
const cell = Math.max(12, width / 130, height / 80)
const scale = Math.max(Math.min(width, height), 1)

for (let y = cell / 2; y < height; y += cell) {
for (let x = cell / 2; x < width; x += cell) {
const nx = (x - width / 2) / Math.max(width, 1)
const ny = (y - height / 2) / Math.max(height, 1)
const px = (x - width / 2) / scale
const py = (y - height / 2) / scale
// Domain-warped contour bands drift like a living topographic map.
const flowX = px + Math.sin(py * 3.5 + time * 0.45) * 0.24
const flowY = py + Math.cos(px * 3 - time * 0.35) * 0.2
const field = Math.sin(flowX * 4 + time * 0.55)
+ Math.cos(flowY * 5 - time * 0.4)
+ Math.sin((flowX + flowY) * 3 + time * 0.3) * 0.5
const contour = Math.pow(0.5 + 0.5 * Math.cos(field * 9 - time), 8)
const mist = (Math.sin(flowX * 8 - flowY * 6 + time) + 1) * 0.5
const density = Math.min(1, contour * 0.85 + mist * 0.15)
const glyph = GLYPHS[Math.min(GLYPHS.length - 1, Math.floor(density * GLYPHS.length))]
const tint = /^#[0-9a-f]{6}$/i.test(color) ? [1, 3, 5].map((offset) => parseInt(color.slice(offset, offset + 2), 16)) : [163, 170, 167]
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
const i = (y * columns + x) * 4
const red = pixels[i], green = pixels[i + 1], blue = pixels[i + 2]
const luminance = (red * 0.2126 + green * 0.7152 + blue * 0.0722) / 255
const glyph = GLYPHS[Math.min(GLYPHS.length - 1, Math.floor(luminance * GLYPHS.length))]
if (glyph === " ") continue
const edge = Math.max(0, 1 - Math.pow(Math.abs(nx) * 2, 4))
* Math.max(0, 1 - Math.pow(Math.abs(ny) * 2, 4))
// Leave a quiet pocket behind the composer and project controls.
const pocket = 1 - 0.92 * Math.exp(-(nx * nx * 18 + (ny + 0.06) ** 2 * 26))
context.globalAlpha = (0.025 + density * 0.13) * edge * pocket
context.fillText(glyph, x, y)
const nx = (x / columns - 0.5) * 2
const ny = (y / rows - 0.5) * 2
const centerFade = 1 - 0.45 * Math.exp(-(nx * nx * 4 + (ny + 0.05) ** 2 * 6))
context.globalAlpha = (0.3 + luminance * 0.45) * centerFade
context.fillStyle = `rgb(${Math.round(red * 0.8 + tint[0] * 0.2)}, ${Math.round(green * 0.8 + tint[1] * 0.2)}, ${Math.round(blue * 0.8 + tint[2] * 0.2)})`
context.fillText(glyph, (x + 0.5) * cell, (y + 0.5) * cell * 1.15)
}
}
context.globalAlpha = 1
}

function tick(now: number) {
frame = 0
if (document.hidden || !visible || !animate) return
if (previous) elapsedRef.current += Math.min(now - previous, 100)
previous = now
if (now - lastPaint >= FRAME_MS) {
draw()
lastPaint = now
}
frame = requestAnimationFrame(tick)
}

function syncAnimation() {
cancelAnimationFrame(frame)
frame = 0
previous = 0
if (animate && !document.hidden && visible) frame = requestAnimationFrame(tick)
}

source.onload = () => { if (!disposed) draw() }
source.onerror = () => { if (!disposed) { context.fillStyle = color; context.globalAlpha = 0.1; context.fillText("·", width / 2, height / 2); context.globalAlpha = 1 } }
source.src = image
const resize = new ResizeObserver(([entry]) => {
if (!entry || !context) return
if (!entry) return
width = entry.contentRect.width
height = entry.contentRect.height
const dpr = Math.min(window.devicePixelRatio || 1, 2)
Expand All @@ -100,46 +82,15 @@ export const AsciiBackground = memo(function AsciiBackground({ color = "#a3aaa7"
context.setTransform(dpr, 0, 0, dpr, 0, 0)
draw()
})
const intersection = new IntersectionObserver(([entry]) => {
visible = entry?.isIntersecting ?? false
syncAnimation()
})
resize.observe(canvas)
intersection.observe(canvas)
document.addEventListener("visibilitychange", syncAnimation)
syncAnimation()

return () => {
cancelAnimationFrame(frame)
resize.disconnect()
intersection.disconnect()
document.removeEventListener("visibilitychange", syncAnimation)
}
}, [color, paused, reducedMotion])
return () => { disposed = true; source.onload = null; source.onerror = null; resize.disconnect() }
}, [color, image, appearance?.effect])

return (
<>
<motion.div
aria-hidden="true"
className="pointer-events-none absolute inset-0 overflow-hidden select-none"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: hydrated && reducedMotion ? 0 : 1.4 }}
>
<canvas ref={canvasRef} className="block h-full w-full" />
</motion.div>
{hydrated && reducedMotion === false ? (
<button
type="button"
onClick={() => setPaused((value) => !value)}
aria-label={paused ? "Play background animation" : "Pause background animation"}
aria-pressed={paused}
title={paused ? "Play background animation" : "Pause background animation"}
className="absolute right-4 bottom-4 z-[2] flex size-8 items-center justify-center rounded-full border border-[var(--chat-border)] bg-[var(--chat-bg)] text-[var(--chat-muted)] transition hover:bg-[var(--chat-hover)] hover:text-[var(--chat-text)] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring"
>
{paused ? <Play className="size-3" /> : <Pause className="size-3" />}
</button>
) : null}
</>
)
const background = appearance?.background ?? "#0e0e10"
const fade = appearance?.bottomFade ?? BACKGROUND_DEFAULTS.bottomFade
return <div aria-hidden="true" className="pointer-events-none absolute inset-0 select-none overflow-hidden">
<canvas ref={canvasRef} className="block h-full w-full" style={{ opacity: (appearance?.imageOpacity ?? BACKGROUND_DEFAULTS.imageOpacity) / 100, filter: `brightness(${appearance?.brightness ?? BACKGROUND_DEFAULTS.brightness}%) blur(${appearance?.blur ?? BACKGROUND_DEFAULTS.blur}px)` }} />
<div className="absolute inset-0" style={{ backgroundColor: background, opacity: (appearance?.overlayOpacity ?? BACKGROUND_DEFAULTS.overlayOpacity) / 100 }} />
{fade > 0 && <div className="absolute inset-0" style={{ background: `linear-gradient(to bottom, transparent ${100 - fade}%, ${background} 100%)` }} />}
</div>
})
4 changes: 2 additions & 2 deletions apps/web/modules/nova-web/components/chat-appearance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,14 @@ export function ChatAppearancePicker({ appearance, onChange }: {
</div>
<div className="mb-4 flex gap-2">
{CHAT_APPEARANCE_PRESETS.map((preset) => (
<button key={preset.name} type="button" title={preset.name} aria-label={`${preset.name} color preset`} aria-pressed={appearance.background === preset.background && appearance.ascii === preset.ascii} onClick={() => onChange({ background: preset.background, ascii: preset.ascii, text: null })} style={{ backgroundColor: preset.background, color: preset.ascii }} className="flex size-9 items-center justify-center rounded-full border border-current/30 font-mono text-sm transition hover:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 aria-pressed:ring-2 aria-pressed:ring-ring aria-pressed:ring-offset-2 aria-pressed:ring-offset-popover">
<button key={preset.name} type="button" title={preset.name} aria-label={`${preset.name} color preset`} aria-pressed={appearance.background === preset.background && appearance.ascii === preset.ascii} onClick={() => onChange({ ...appearance, background: preset.background, ascii: preset.ascii, text: null })} style={{ backgroundColor: preset.background, color: preset.ascii }} className="flex size-9 items-center justify-center rounded-full border border-current/30 font-mono text-sm transition hover:scale-110 focus-visible:outline-2 focus-visible:outline-offset-2 aria-pressed:ring-2 aria-pressed:ring-ring aria-pressed:ring-offset-2 aria-pressed:ring-offset-popover">
#
</button>
))}
</div>
<fieldset className="mb-4"><legend className="mb-2 text-xs text-muted-foreground">Background image</legend><div className="grid grid-cols-2 gap-2">{([{ id: "night", label: "Night sky", src: "/nova/ascii-night.webp" }, { id: "clouds", label: "Clouds", src: "/cloudy.png" }] as const).map((item) => <button key={item.id} type="button" aria-pressed={(appearance.image ?? "night") === item.id} onClick={() => onChange({ ...appearance, image: item.id })} className="overflow-hidden rounded-lg border border-white/10 text-left text-xs text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white aria-pressed:ring-2 aria-pressed:ring-white/60"><span aria-hidden="true" className="block h-16 bg-cover bg-center" style={{ backgroundImage: `url(${item.src})` }} /><span className="block px-2 py-1.5">{item.label}</span></button>)}</div></fieldset>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Picker controls leave the screen

The new image section makes the appearance picker too tall for short browser windows. PopoverContent has a height cap but no scrolling; the shared overflow-y: auto rule applies only to dropdown menus. The bottom color and automatic-contrast controls can extend off-screen. Add overflow-y-auto to the picker so those controls remain reachable.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

<div className="space-y-3">
<ColorPicker label="Background" value={appearance.background} onChange={(background) => onChange({ ...appearance, background })} />
<ColorPicker label="ASCII animation" value={appearance.ascii} onChange={(ascii) => onChange({ ...appearance, ascii })} />
<ColorPicker label="Text" value={text} onChange={(color) => onChange({ ...appearance, text: color })} />
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted-foreground">
<input type="checkbox" checked={appearance.text === null} onChange={(event) => onChange({ ...appearance, text: event.target.checked ? null : text })} className="size-3.5 accent-current" />
Expand Down
4 changes: 2 additions & 2 deletions apps/web/modules/nova-web/components/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export function EmptyHome({
"--chat-text": text,
"--chat-muted": `color-mix(in srgb, ${text} 65%, ${appearance.background})`,
"--chat-border": `color-mix(in srgb, ${text} 8%, ${appearance.background})`,
"--chat-surface": `color-mix(in srgb, ${text} 3%, ${appearance.background})`,
"--chat-surface": `color-mix(in srgb, ${appearance.background} ${appearance.inputOpacity ?? 85}%, transparent)`,
"--chat-hover": `color-mix(in srgb, ${text} 12%, ${appearance.background})`,
backgroundColor: appearance.background,
color: text,
Expand All @@ -85,7 +85,7 @@ export function EmptyHome({

return (
<div style={theme} className="relative isolate flex h-full min-h-0 flex-col">
<AsciiBackground color={appearance.ascii} />
<AsciiBackground color={appearance.ascii} image={appearance.image === "clouds" ? "/cloudy.png" : "/nova/ascii-night.webp"} appearance={appearance} />
<ChatAppearancePicker appearance={appearance} onChange={update} />
<div className="pointer-events-none relative z-[1] flex min-h-0 flex-1 flex-col items-center justify-center px-5 pb-8 text-center">
<NovaIcon size="lg" alt="" className="mb-5 size-11" />
Expand Down
Loading
Loading