diff --git a/packages/app/component-tests/new-session-wordmark.spec.ts b/packages/app/component-tests/new-session-wordmark.spec.ts index e068db191d9..b4a8bc389a5 100644 --- a/packages/app/component-tests/new-session-wordmark.spec.ts +++ b/packages/app/component-tests/new-session-wordmark.spec.ts @@ -9,7 +9,7 @@ const EMPTY = { x: 5.5 / 78, y: 0.5 / 14 } story("draws the wordmark as pins and stops animating once settled", async ({ mount, page }) => { await page.emulateMedia({ reducedMotion: "no-preference" }) - await mount("app-new-session-wordmark--pin-board") + await mount("plugins-wordmark--pin-board") const empty = await pinPixel(page, EMPTY) await expect.poll(() => pinPixel(page)).not.toEqual(empty) @@ -18,7 +18,7 @@ story("draws the wordmark as pins and stops animating once settled", async ({ mo story("knocks pins out from the panel but never from the composer", async ({ mount, page }) => { await page.emulateMedia({ reducedMotion: "no-preference" }) - await mount("app-new-session-wordmark--pin-board") + await mount("plugins-wordmark--pin-board") await expect.poll(() => requestedFrames(page)).toBe(0) const before = await pinPixel(page) @@ -33,7 +33,7 @@ story("knocks pins out from the panel but never from the composer", async ({ mou story("shows a static pin board with reduced motion", async ({ mount, page }) => { await page.emulateMedia({ reducedMotion: "reduce" }) - await mount("app-new-session-wordmark--pin-board") + await mount("plugins-wordmark--pin-board") const empty = await pinPixel(page, EMPTY) await expect.poll(() => pinPixel(page)).not.toEqual(empty) await expect.poll(() => requestedFrames(page)).toBe(0) diff --git a/packages/app/src/new-session/pin-sound.ts b/packages/app/src/new-session/pin-sound.ts deleted file mode 100644 index 3bb39ba5729..00000000000 --- a/packages/app/src/new-session/pin-sound.ts +++ /dev/null @@ -1,193 +0,0 @@ -// Synthesised stone sounds for the new session pin board. Nothing is loaded from disk; every sound is a -// short burst of filtered noise, optionally with a low thud, so the whole palette reads as pebbles on stone. - -const PENTATONIC = [0, 2, 4, 7, 9] - -type Audio = { context: AudioContext; bus: GainNode; noise: AudioBuffer; recent: number[] } - -let shared: Audio | undefined - -/** Returns a running audio graph, or nothing when the browser would block or has not been interacted with. */ -function audio() { - if (typeof AudioContext === "undefined" || document.hidden) return - if (!navigator.userActivation?.hasBeenActive) return - if (!shared) shared = createAudio() - if (shared.context.state === "suspended") void shared.context.resume() - if (shared.context.state !== "running") return - return shared -} - -function createAudio(): Audio { - const context = new AudioContext() - const limiter = context.createDynamicsCompressor() - limiter.threshold.value = -24 - limiter.ratio.value = 4 - limiter.connect(context.destination) - const master = context.createGain() - master.gain.value = 0.9 - master.connect(limiter) - const bus = context.createGain() - bus.connect(master) - const room = context.createConvolver() - room.buffer = impulse(context, 1.2, 3.2) - const wet = context.createGain() - wet.gain.value = 0.18 - bus.connect(room) - room.connect(wet) - wet.connect(master) - const noise = context.createBuffer(1, context.sampleRate, context.sampleRate) - noise.getChannelData(0).forEach((_, i, data) => (data[i] = Math.random() * 2 - 1)) - return { context, bus, noise, recent: [] } -} - -function impulse(context: AudioContext, seconds: number, decay: number) { - const length = Math.floor(context.sampleRate * seconds) - const buffer = context.createBuffer(2, length, context.sampleRate) - for (let channel = 0; channel < 2; channel++) { - const data = buffer.getChannelData(channel) - for (let i = 0; i < length; i++) data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / length, decay) - } - return buffer -} - -// Caps bursts of collision sounds so a crumble stays a patter rather than a roar. -function allow(a: Audio) { - const now = performance.now() - while (a.recent.length && now - a.recent[0] > 80) a.recent.shift() - if (a.recent.length >= 5) return false - a.recent.push(now) - return true -} - -/** One pebble click: band-passed noise with a resonant body and an optional low thud. */ -function pebble( - a: Audio, - at: number, - input: { freq: number; q: number; gain: number; decay: number; pan: number; thud?: number }, -) { - const c = a.context - const source = c.createBufferSource() - source.buffer = a.noise - const band = c.createBiquadFilter() - band.type = "bandpass" - band.frequency.value = input.freq - band.Q.value = input.q - const env = c.createGain() - env.gain.setValueAtTime(0.0001, at) - env.gain.exponentialRampToValueAtTime(input.gain, at + 0.002) - env.gain.exponentialRampToValueAtTime(0.0001, at + input.decay) - const pan = c.createStereoPanner() - pan.pan.value = Math.max(-0.9, Math.min(0.9, input.pan)) - source.connect(band).connect(env).connect(pan).connect(a.bus) - source.start(at, Math.random() * 0.8, input.decay + 0.02) - if (!input.thud) return - const body = c.createOscillator() - body.frequency.setValueAtTime(input.thud * 1.6, at) - body.frequency.exponentialRampToValueAtTime(input.thud, at + 0.03) - const thud = c.createGain() - thud.gain.setValueAtTime(0.0001, at) - thud.gain.exponentialRampToValueAtTime(input.gain * 0.5, at + 0.003) - thud.gain.exponentialRampToValueAtTime(0.0001, at + input.decay * 2.5) - body.connect(thud).connect(pan) - body.start(at) - body.stop(at + input.decay * 2.5 + 0.02) -} - -const note = (step: number) => - 440 * Math.pow(2, (74 + 12 * Math.floor(step / 5) + PENTATONIC[((step % 5) + 5) % 5] - 69) / 12) -const panOf = (x: number, width: number) => (width ? (x / width) * 1.6 - 0.8 : 0) - -export const PinSound = { - /** The wordmark rising in: a gritty stone slide sweeping across with pebbles settling under it. */ - sweep(input: { duration: number; columns: number; reverse?: boolean }) { - const a = audio() - if (!a) return - const c = a.context - const at = c.currentTime + 0.02 - const end = at + input.duration - - const source = c.createBufferSource() - source.buffer = a.noise - source.loop = true - const grit = c.createBiquadFilter() - grit.type = "bandpass" - grit.Q.value = 1.4 - grit.frequency.setValueAtTime(input.reverse ? 1500 : 260, at) - grit.frequency.exponentialRampToValueAtTime(input.reverse ? 260 : 1500, end) - const body = c.createBiquadFilter() - body.type = "lowpass" - body.frequency.value = 2400 - const env = c.createGain() - env.gain.setValueAtTime(0.0001, at) - env.gain.exponentialRampToValueAtTime(0.03, at + 0.12) - env.gain.setValueAtTime(0.03, end - 0.18) - env.gain.exponentialRampToValueAtTime(0.0001, end + 0.12) - const pan = c.createStereoPanner() - pan.pan.setValueAtTime(-0.7, at) - pan.pan.linearRampToValueAtTime(0.7, end) - source.connect(grit).connect(body).connect(env).connect(pan).connect(a.bus) - source.start(at) - source.stop(end + 0.15) - - const clicks = 22 - for (let i = 0; i < clicks; i++) { - const k = (i + Math.random() * 0.6) / clicks - pebble(a, at + k * (input.duration - 0.1) + 0.06, { - freq: 1800 + Math.random() * 1600, - q: 5, - gain: 0.02 + Math.random() * 0.018, - decay: 0.02 + Math.random() * 0.015, - pan: k * 1.4 - 0.7, - }) - } - }, - - /** A click that knocks pins out: one solid stone clack. */ - knock(x: number, width: number) { - const a = audio() - if (!a) return - pebble(a, a.context.currentTime, { freq: 1100, q: 2.2, gain: 0.14, decay: 0.05, pan: panOf(x, width), thud: 95 }) - }, - - /** The brick breaker ball smashing pins: a clack whose ring climbs the scale with each hit before the paddle. */ - brick(x: number, width: number, combo: number) { - const a = audio() - if (!a) return - const at = a.context.currentTime - pebble(a, at, { freq: 1300, q: 2, gain: 0.1, decay: 0.04, pan: panOf(x, width), thud: 110 }) - pebble(a, at + 0.004, { freq: note(Math.min(14, combo)), q: 16, gain: 0.06, decay: 0.09, pan: panOf(x, width) }) - }, - - /** The brick breaker ball landing on the paddle: a soft, low knock. */ - paddle(x: number, width: number) { - const a = audio() - if (!a) return - pebble(a, a.context.currentTime, { freq: 520, q: 1.4, gain: 0.12, decay: 0.05, pan: panOf(x, width), thud: 72 }) - }, - - /** A loose pin bouncing off the composer or the floor. */ - bounce(x: number, width: number, speed: number) { - const a = audio() - if (!a || !allow(a)) return - pebble(a, a.context.currentTime, { - freq: 2200 + Math.random() * 1400, - q: 6, - gain: Math.min(0.07, 0.012 + speed / 40000), - decay: 0.02, - pan: panOf(x, width), - }) - }, - - /** A pin seating back into its socket; pitch rises across the wordmark so the return reads as a cascade. */ - slot(column: number, columns: number, x: number, width: number) { - const a = audio() - if (!a || !allow(a)) return - pebble(a, a.context.currentTime, { - freq: note(Math.floor((column / columns) * 10)), - q: 14, - gain: 0.05, - decay: 0.045, - pan: panOf(x, width), - }) - }, -} diff --git a/packages/app/src/new-session/view.tsx b/packages/app/src/new-session/view.tsx index 5d44390bb0b..c8f9d3b6358 100644 --- a/packages/app/src/new-session/view.tsx +++ b/packages/app/src/new-session/view.tsx @@ -1,6 +1,7 @@ import { useDialog } from "@opencode/ui/context/dialog" import { Tooltip } from "@opencode/ui/tooltip" import { Icon } from "@opencode/ui/icon" +import { Logo } from "@opencode/ui/logo" import { Slash } from "@opencode/ui/slash" import { Keybind } from "@opencode/ui/keybind" import { useCommand } from "@/shell/commands/command" @@ -33,11 +34,9 @@ import { NEW_SESSION_CONTENT_WIDTH } from "@/new-session/layout" import { Persist, persisted } from "@/runtime/persistence/storage" import { Persistence } from "@/runtime/persistence/schema" import { useSettings } from "@/settings/model" +import { PluginSlot } from "@/runtime/plugin/render" import type { NewSessionWorkspaceController } from "./workspace/controller" import { NewSessionBranch } from "./workspace/selector" -import { NewSessionBrickBreaker } from "./brick-breaker" -import { NewSessionPinBoard, type PinBoardHandle } from "./pin-board" -import { NewSessionWordmark, type LodgerBall } from "./wordmark" const providerTipDismissalDuration = 30 * 24 * 60 * 60 * 1000 @@ -49,15 +48,9 @@ export const ProviderTipSchema = Persistence.struct({ dismissedAt: Schema.Finite, }) -type WordmarkState = { - box?: HTMLDivElement - mode: "flat" | "open" | "closing" - game: boolean -} - -type BrickBreakerHandles = { - board?: PinBoardHandle - ball?: LodgerBall +type HeroState = { + stage?: HTMLDivElement + area?: HTMLDivElement } export function NewSessionView(props: { @@ -74,7 +67,7 @@ export function NewSessionView(props: { const settings = useSettings() - const [wordmark, setWordmark] = createStore({ mode: "flat", game: false }) + const [hero, setHero] = createStore({}) const location = (project?: PromptProject) => props.location({ @@ -84,14 +77,10 @@ export function NewSessionView(props: { }, }) - // Imperative handles for the brick breaker; they are not reactive state. - const handles: BrickBreakerHandles = {} - let panel!: HTMLDivElement - return (
setHero("stage", stage)} data-component="new-session" class="relative isolate flex-1 min-h-0 overflow-hidden rounded-[10px] bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]" > @@ -101,19 +90,33 @@ export function NewSessionView(props: { />
- setWordmark("box", box)} - sound={settings.sounds.interfaceEnabled} - onOpen={() => setWordmark("mode", "open")} - onClose={() => setWordmark("mode", "closing")} - onFlat={() => setWordmark("mode", "flat")} - onPlay={(ball) => { - handles.ball = ball - setWordmark("game", true) - }} - /> + + {(parts) => ( + } + input={{ + stage: parts().stage, + composer: { + area: parts().area, + get box() { + return parts().area.querySelector('[data-component="composer"]') ?? parts().area + }, + }, + get tip() { + return parts().stage.querySelector('[data-component="new-session-tip"]') ?? undefined + }, + get sounds() { + return settings.sounds.interfaceEnabled() + }, + focus: () => props.composer.restoreFocus(), + }} + /> + )} +
-
+
setHero("area", area)} data-slot="new-session-composer" class="flex flex-col gap-1">
@@ -137,37 +140,21 @@ export function NewSessionView(props: {
- - {(logo) => ( - (handles.board = board)} - /> - )} - - - {(game) => ( - { - setWordmark("game", false) - props.composer.restoreFocus() - }} - /> - )} -
) } +/** The plain wordmark, shown while no plugin fills the hero. */ +function NewSessionWordmark() { + return ( + + ) +} + function NewSessionTips(props: { selection: ComposerModel["model"]["selection"]; onDone: () => void }) { const language = useLanguage() const dialog = useDialog() diff --git a/packages/app/src/new-session/wordmark.stories.tsx b/packages/app/src/new-session/wordmark.stories.tsx deleted file mode 100644 index 2a87621b2c8..00000000000 --- a/packages/app/src/new-session/wordmark.stories.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { Show } from "solid-js" -import { createStore } from "solid-js/store" -import { NewSessionPinBoard } from "./pin-board" -import { NewSessionWordmark } from "./wordmark" - -export default { - title: "App/New Session/Wordmark", - id: "app-new-session-wordmark", - component: NewSessionWordmark, -} - -function Panel(props: { pins: boolean }) { - const [state, setState] = createStore({ - box: undefined as HTMLDivElement | undefined, - mode: (props.pins ? "open" : "flat") as "flat" | "open" | "closing", - }) - - return ( -
-
-
- setState("box", box)} - pins={props.pins} - sound={() => true} - onOpen={() => setState("mode", "open")} - onClose={() => setState("mode", "closing")} - onFlat={() => setState("mode", "flat")} - /> -
-
-
- - {(element) => ( - true} - entrance={props.pins ? "sweep" : "chain"} - closing={state.mode === "closing"} - /> - )} - -
- ) -} - -export const Flat = { - render: () => , -} - -export const PinBoard = { - render: () => , -} diff --git a/packages/app/src/runtime/plugin/render.tsx b/packages/app/src/runtime/plugin/render.tsx index bebf38f991e..f0ff64b8d31 100644 --- a/packages/app/src/runtime/plugin/render.tsx +++ b/packages/app/src/runtime/plugin/render.tsx @@ -35,19 +35,23 @@ export function Contribution(props: { plugin: string; children: () => JSX.Elemen ) } +/** Renders a slot's contributions in `order`. With `single`, only the last one renders: the slot has one owner. */ export function PluginSlot(props: { at: At input: BuiltinSlotMap[At] fallback?: JSX.Element + single?: boolean }) { const host = usePluginHost() - const items = createMemo(() => - host + const items = createMemo(() => { + const sorted = host .items(BuiltinSlot) .filter((item) => item.value.at === props.at) - .toSorted((a, b) => (a.value.order ?? 0) - (b.value.order ?? 0)), - ) + .toSorted((a, b) => (a.value.order ?? 0) - (b.value.order ?? 0)) + + return props.single ? sorted.slice(-1) : sorted + }) return ( diff --git a/packages/gui-plugins/README.md b/packages/gui-plugins/README.md index 3b4741fbd5d..56cd99c898f 100644 --- a/packages/gui-plugins/README.md +++ b/packages/gui-plugins/README.md @@ -250,7 +250,7 @@ SDK icon fields take an `IconName` from `@opencode/plugin/gui`: the names of the | [`LinkHandler`](../plugin/src/gui/registries.ts) | window | Opens local links, such as file paths in messages, and says whether their target exists | | [`TitlebarItem`](../plugin/src/gui/registries.ts) | window | A pill in the titlebar or the tabs footer | | [`ComposerPill`](../plugin/src/gui/registries.ts) | window | A pill in the row above a session's composer, optionally opening a menu of rows or a popover of your own content | -| [`Slot`](../plugin/src/gui/registries.ts) | window | Content for `window.bottom`, `session.header`, `session.location.menu`, `session.panel.end`; built-ins also fill `session.location.workspace`, `session.location.branch.menu` and `session.location.path.menu` through `BuiltinSlot` | +| [`Slot`](../plugin/src/gui/registries.ts) | window | Content for `window.bottom`, `session.header`, `session.location.menu`, `session.panel.end`, `new-session.hero`; built-ins also fill `session.location.workspace`, `session.location.branch.menu` and `session.location.path.menu` through `BuiltinSlot` | | [`Style`](../plugin/src/gui/registries.ts) | window | CSS imported with `?inline` | | [`MenubarItem`](../plugin/src/gui/main.ts) | main | An item of the native app menu | @@ -258,6 +258,12 @@ SDK icon fields take an `IconName` from `@opencode/plugin/gui`: the names of the the live `session`, and `shown`; keep data subscriptions active only while `shown` is true. Loading headers without an owning screen show the host's location details without this slot. +`new-session.hero` is the new session screen's wordmark. It has one owner: the contribution that sorts last by `order`, +so a plugin's hero at the default `order` replaces the built-in wordmark (`src/wordmark/`, `order: -1`). It renders in +the wordmark's place and receives the panel as `stage`, the composer's `box` and `area`, the bottom `tip`, the user's +interface `sounds` setting, and `focus()` to return the keyboard to the composer. Render effects that span the panel +into `stage` with `Portal`, and restore every host element you move, fade or disable. + `session.location.branch.menu` (built-ins only, through `BuiltinSlot`) contributes items after Copy branch name in the branch submenu, with the same `screen`, live `session`, and project-menu `shown` context. It renders only when a branch name and owning screen are available. Use it for actions on the branch's working directory, such as opening @@ -705,6 +711,7 @@ export const builtins = compose({ "microsoft-office": microsoftOffice, sources, goal, + wordmark, }) ``` @@ -730,6 +737,7 @@ export const builtins = compose({ "microsoft-office": { ...microsoftOffice, windowEntry: eager(microsoftOfficeRenderer) }, sources: { ...sources, windowEntry: eager(sourcesRenderer) }, goal: { ...goal, windowEntry: eager(goalRenderer) }, + wordmark: { ...wordmark, windowEntry: eager(wordmarkRenderer) }, }) ``` diff --git a/packages/gui-plugins/src/main.ts b/packages/gui-plugins/src/main.ts index 76cfe0cb248..1dfba6cfadc 100644 --- a/packages/gui-plugins/src/main.ts +++ b/packages/gui-plugins/src/main.ts @@ -14,6 +14,7 @@ import wsl from "./wsl" import microsoftOffice from "./microsoft-office" import sources from "./sources" import goal from "./goal" +import wordmark from "./wordmark" /** Built-in plugins with their main entries, by id. Lists every built-in so their ids stay reserved. */ export const builtins = compose({ @@ -32,4 +33,5 @@ export const builtins = compose({ "microsoft-office": microsoftOffice, sources, goal, + wordmark, }) diff --git a/packages/gui-plugins/src/renderer.ts b/packages/gui-plugins/src/renderer.ts index 5c131e235d0..f9b845c103e 100644 --- a/packages/gui-plugins/src/renderer.ts +++ b/packages/gui-plugins/src/renderer.ts @@ -29,6 +29,8 @@ import sources from "./sources" import sourcesRenderer from "./sources/renderer" import goal from "./goal" import goalRenderer from "./goal/renderer" +import wordmark from "./wordmark" +import wordmarkRenderer from "./wordmark/renderer" // The window renders once every built-in is active, so the small renderer entries load with the app, like the // features they replaced. Heavy UI stays behind `lazy()` inside them. @@ -52,4 +54,5 @@ export const builtins = compose({ "microsoft-office": { ...microsoftOffice, windowEntry: eager(microsoftOfficeRenderer) }, sources: { ...sources, windowEntry: eager(sourcesRenderer) }, goal: { ...goal, windowEntry: eager(goalRenderer) }, + wordmark: { ...wordmark, windowEntry: eager(wordmarkRenderer) }, }) diff --git a/packages/app/src/new-session/brick-breaker.tsx b/packages/gui-plugins/src/wordmark/brick-breaker.tsx similarity index 86% rename from packages/app/src/new-session/brick-breaker.tsx rename to packages/gui-plugins/src/wordmark/brick-breaker.tsx index 8ef2c9de02c..08088b873ea 100644 --- a/packages/app/src/new-session/brick-breaker.tsx +++ b/packages/gui-plugins/src/wordmark/brick-breaker.tsx @@ -1,7 +1,7 @@ import { For, onCleanup, onMount } from "solid-js" import type { PinBoardHandle } from "./pin-board" -import { PinSound } from "./pin-sound" -import type { LodgerBall } from "./wordmark" +import type { PinSound } from "./pin-sound" +import type { Hero, LodgerBall } from "./wordmark" const LIVES = 3 const ENTER = 0.85 @@ -15,10 +15,11 @@ type Box = { x: number; y: number; w: number; h: number; r: number } * into the paddle. Like Arkanoid, the ball waits on the paddle until it is served with a click or Space. */ export function NewSessionBrickBreaker(props: { - panel: HTMLElement + hero: Hero + logo: HTMLElement board: PinBoardHandle ball: LodgerBall - sound: () => boolean + sound: PinSound onDone: () => void }) { let paddle!: HTMLDivElement @@ -29,7 +30,13 @@ export function NewSessionBrickBreaker(props: { onMount(() => onCleanup( - mountGame({ panel: props.panel, paddle, hud, score, spares, walls }, props.board, props.ball, props.sound, props.onDone), + mountGame( + { hero: props.hero, logo: props.logo, paddle, hud, score, spares, walls }, + props.board, + props.ball, + props.sound, + props.onDone, + ), ), ) @@ -70,7 +77,8 @@ export function NewSessionBrickBreaker(props: { function mountGame( parts: { - panel: HTMLElement + hero: Hero + logo: HTMLElement paddle: HTMLDivElement hud: HTMLDivElement score: HTMLSpanElement @@ -79,14 +87,14 @@ function mountGame( }, board: PinBoardHandle, ball: LodgerBall, - sound: () => boolean, + sound: PinSound, onDone: () => void, ) { - const panel = parts.panel - const wrap = panel.querySelector('[data-slot="new-session-composer"]') - const form = wrap?.querySelector('[data-component="composer"]') - const tip = panel.querySelector('[data-component="new-session-tip"]') - const surface = form ? getComputedStyle(form).backgroundColor : "" + const panel = parts.hero.stage + const wrap = parts.hero.composer.area + const form = parts.hero.composer.box + const tip = parts.hero.tip + const surface = getComputedStyle(form).backgroundColor // The arena is exactly as wide as the wordmark, like Arkanoid's tall, narrow playfield. const view = { left: 0, top: 0, w: 0, h: 0, l: 0, r: 0 } const g = { phase: "enter" as Phase, t0: performance.now() / 1000, last: 0, raf: 0, lives: LIVES, score: 0 } @@ -107,12 +115,11 @@ function mountGame( view.h = r.height // Walls sit on the wordmark's outer pin edges, using the board's integer pitch and rounded origin, so the // ball can only reach the top by breaking through. - const logo = panel.querySelector('[data-slot="wordmark-box"]')?.getBoundingClientRect() - const pitch = logo ? Math.max(3, Math.round(logo.width / 78)) : 0 - const x0 = logo ? Math.round(logo.left - r.left + (logo.width - pitch * 78) / 2) : 0 - const c = composerBox() - view.l = logo ? x0 : Math.max(0, c.x) - view.r = logo ? x0 + pitch * 78 : Math.min(view.w, c.x + c.w) + const logo = parts.logo.getBoundingClientRect() + const pitch = Math.max(3, Math.round(logo.width / 78)) + const x0 = Math.round(logo.left - r.left + (logo.width - pitch * 78) / 2) + view.l = x0 + view.r = x0 + pitch * 78 parts.walls[0].style.transform = `translateX(${view.l - 1}px)` parts.walls[1].style.transform = `translateX(${view.r}px)` pad.w = Math.max(84, Math.min(136, (view.r - view.l) * 0.15)) @@ -123,9 +130,8 @@ function mountGame( function composerBox(): Box { const p = panel.getBoundingClientRect() - const r = form?.getBoundingClientRect() - if (!r) return { x: p.width / 2 - 60, y: p.height - 64, w: 120, h: 12, r: 6 } - const radius = form ? parseFloat(getComputedStyle(form).borderTopLeftRadius) : 12 + const r = form.getBoundingClientRect() + const radius = parseFloat(getComputedStyle(form).borderTopLeftRadius) return { x: r.left - p.left, y: r.top - p.top, w: r.width, h: r.height, r: radius || 12 } } @@ -182,7 +188,7 @@ function mountGame( if (k >= 1 && !b.landed) { b.landed = true bump(Math.PI / 2, 0.32) - if (sound()) PinSound.paddle(b.x, view.w) + sound.paddle(b.x, view.w) } // Once it has shrunk enough to read as a paddle, it takes on the colour of the pins it is about to break. if (t >= 0.3) parts.paddle.style.background = "var(--v2-icon-icon-muted)" @@ -205,7 +211,7 @@ function mountGame( if (drop >= 1 && !b.landed) { b.landed = true bump(Math.PI / 2, 0.36) - if (sound()) PinSound.paddle(b.x, view.w) + sound.paddle(b.x, view.w) } } @@ -219,7 +225,7 @@ function mountGame( rally.combo = 0 pad.kickAt = performance.now() / 1000 bump(Math.PI / 2, 0.3) - if (sound()) PinSound.paddle(b.x, view.w) + sound.paddle(b.x, view.w) setPhase("play") } @@ -235,20 +241,15 @@ function mountGame( b.x = Math.max(view.l + r, Math.min(view.r - r, b.x)) b.vx = b.x <= view.l + r ? Math.abs(b.vx) : -Math.abs(b.vx) bump(0, 0.22) - if (sound()) PinSound.bounce(b.x, view.w, 4000) + sound.bounce(b.x, view.w, 4000) } if (b.y < r) { b.y = r b.vy = Math.abs(b.vy) bump(Math.PI / 2, 0.22) - if (sound()) PinSound.bounce(b.x, view.w, 4000) + sound.bounce(b.x, view.w, 4000) } - if ( - b.vy > 0 && - b.y + r >= pad.y && - b.y - r < pad.y + pad.h && - Math.abs(b.x - pad.x) <= pad.w / 2 + r * 0.6 - ) { + if (b.vy > 0 && b.y + r >= pad.y && b.y - r < pad.y + pad.h && Math.abs(b.x - pad.x) <= pad.w / 2 + r * 0.6) { // Classic paddle control: where the ball lands sets its angle, up to 60° from vertical. const off = Math.max(-1, Math.min(1, (b.x - pad.x) / (pad.w / 2))) const a = off * (Math.PI / 3) + Math.max(-0.15, Math.min(0.15, pad.v / 6000)) @@ -260,7 +261,7 @@ function mountGame( b.y = pad.y - r pad.kickAt = now bump(Math.PI / 2, 0.34) - if (sound()) PinSound.paddle(b.x, view.w) + sound.paddle(b.x, view.w) } // Each hit carves a round bite out of the wordmark rather than a single pin. const hit = board.collide(b.x, b.y, r, r * 0.55, b.vx, b.vy) @@ -272,7 +273,7 @@ function mountGame( g.score += hit.count * 10 * Math.min(8, rally.combo) b.squintUntil = now + 0.14 bump(side ? 0 : Math.PI / 2, 0.26) - if (sound()) PinSound.brick(b.x, view.w, rally.combo) + sound.brick(b.x, view.w, rally.combo) if (!board.left()) return finish("win") } // A nearly flat rally never comes back down, so keep at least a quarter of the speed vertical. @@ -283,7 +284,7 @@ function mountGame( } if (b.y - r > view.h) { setPhase("miss") - if (sound()) PinSound.sweep({ duration: 0.45, columns: 78, reverse: true }) + sound.sweep({ duration: 0.45, columns: 78, reverse: true }) return } } @@ -311,7 +312,7 @@ function mountGame( parts.paddle.style.background = surface board.restore() ball.done() - if (sound()) PinSound.sweep({ duration: 0.9, columns: 78, reverse: kind !== "win" }) + sound.sweep({ duration: 0.9, columns: 78, reverse: kind !== "win" }) } // The paddle grows back into the composer, then the composer content fades in over it. @@ -329,7 +330,7 @@ function mountGame( pad.tilt * (1 - e), ) if (t >= 0.75) { - if (wrap) wrap.style.opacity = "" + wrap.style.opacity = "" if (tip) tip.style.opacity = "" parts.paddle.style.opacity = "0" } @@ -423,14 +424,12 @@ function mountGame( tip.style.opacity = "0" } draw(start.composer, 0) - if (wrap) { - if (wrap.contains(document.activeElement) && document.activeElement instanceof HTMLElement) - document.activeElement.blur() - wrap.style.transition = "opacity 160ms ease-out" - wrap.style.opacity = "0" - wrap.style.pointerEvents = "none" - wrap.inert = true - } + if (wrap.contains(document.activeElement) && document.activeElement instanceof HTMLElement) + document.activeElement.blur() + wrap.style.transition = "opacity 160ms ease-out" + wrap.style.opacity = "0" + wrap.style.pointerEvents = "none" + wrap.inert = true board.play() const resize = new ResizeObserver(layout) resize.observe(panel) @@ -455,7 +454,6 @@ function mountGame( tip.style.opacity = "" tip.style.transition = "" } - if (!wrap) return wrap.style.opacity = "" wrap.style.transition = "" wrap.style.pointerEvents = "" diff --git a/packages/gui-plugins/src/wordmark/hero.tsx b/packages/gui-plugins/src/wordmark/hero.tsx new file mode 100644 index 00000000000..5a58bb11d4f --- /dev/null +++ b/packages/gui-plugins/src/wordmark/hero.tsx @@ -0,0 +1,75 @@ +import { onCleanup, Show } from "solid-js" +import { Portal } from "solid-js/web" +import { createStore } from "solid-js/store" +import { NewSessionBrickBreaker } from "./brick-breaker" +import { NewSessionPinBoard, type PinBoardHandle } from "./pin-board" +import { createPinSound } from "./pin-sound" +import { NewSessionWordmark, type Hero, type LodgerBall } from "./wordmark" + +/** + * The new session wordmark and the easter eggs it hides: pull the pin out of the "e" to open the pin board, and drop + * the lodger on the composer to play brick breaker. The board and the game draw over the whole panel. + */ +export default function WordmarkHero(props: { hero: Hero }) { + const sound = createPinSound(() => props.hero.sounds) + const [state, setState] = createStore<{ box?: HTMLDivElement; mode: "flat" | "open"; game: boolean }>({ + mode: "flat", + game: false, + }) + // Imperative handles for the brick breaker; they are not reactive state. + const handles: { board?: PinBoardHandle; ball?: LodgerBall } = {} + + onCleanup(sound.dispose) + + return ( + <> + setState("box", box)} + hero={props.hero} + sound={sound} + onOpen={() => setState("mode", "open")} + onClose={() => handles.board?.close()} + onFlat={() => setState("mode", "flat")} + onPlay={(ball) => { + handles.ball = ball + setState("game", true) + }} + /> + + + {(logo) => ( + (handles.board = board)} + /> + )} + + + {(game) => ( + { + setState("game", false) + props.hero.focus() + }} + /> + )} + + + + ) +} diff --git a/packages/gui-plugins/src/wordmark/index.ts b/packages/gui-plugins/src/wordmark/index.ts new file mode 100644 index 00000000000..3a168e37c01 --- /dev/null +++ b/packages/gui-plugins/src/wordmark/index.ts @@ -0,0 +1,3 @@ +import { Plugin } from "@opencode/plugin/gui" + +export default Plugin.define({}) diff --git a/packages/app/src/new-session/pin-board.tsx b/packages/gui-plugins/src/wordmark/pin-board.tsx similarity index 92% rename from packages/app/src/new-session/pin-board.tsx rename to packages/gui-plugins/src/wordmark/pin-board.tsx index ef638e11b02..25b95435c88 100644 --- a/packages/app/src/new-session/pin-board.tsx +++ b/packages/gui-plugins/src/wordmark/pin-board.tsx @@ -1,7 +1,8 @@ -import { createEffect, onCleanup, onMount } from "solid-js" +import { onCleanup, onMount } from "solid-js" import { createQuads, type Quads, type Rgba } from "./pin-quads" -import { PinSound } from "./pin-sound" +import type { PinSound } from "./pin-sound" import { prefersReducedMotion } from "@opencode/ui/motion" +import type { Hero } from "./wordmark" // The wordmark as a 78×14 pin grid: 1 = counter shadow, 2 = "open", 3 = "code". const GRID = [ @@ -53,6 +54,8 @@ export type PinBoardHandle = { steer: (x: number, y: number) => void /** Ends game mode and flies every pin home. */ restore: () => void + /** Flies every pin home as the wordmark folds back; the board unmounts once the wordmark is flat. */ + close: () => void } const REST_TILT = [0.42, 0.7] as const @@ -60,8 +63,7 @@ const LIGHT = [0.55 / Math.hypot(0.55, 0.83), -0.83 / Math.hypot(0.55, 0.83)] as const SHADES = 16 const LOOSE = 4 const REVEAL = 0.75 -const INTERACTIVE = - 'button, a, input, textarea, select, label, [contenteditable], [role], [data-component="composer"], [data-component="new-session-tip"]' +const INTERACTIVE = "button, a, input, textarea, select, label, [contenteditable], [role]" type Pin = { c: number @@ -101,20 +103,17 @@ type Pin = { */ export function NewSessionPinBoard(props: { logo: HTMLElement - sound: () => boolean + hero: Hero + sound: PinSound entrance?: PinEntrance - closing?: boolean ref?: (board: PinBoardHandle) => void }) { let back!: HTMLCanvasElement let front!: HTMLCanvasElement onMount(() => { - const board = mountPinBoard(back, front, props.logo, props.sound, props.entrance) + const board = mountPinBoard(back, front, props.logo, props.hero, props.sound, props.entrance) props.ref?.(board.handle) - createEffect(() => { - if (props.closing) board.close() - }) onCleanup(board.dispose) }) @@ -140,10 +139,11 @@ function mountPinBoard( back: HTMLCanvasElement, front: HTMLCanvasElement, logo: HTMLElement, - sound: () => boolean, + hero: Hero, + sound: PinSound, entrance: PinEntrance = "sweep", ) { - const stage = back.parentElement! + const stage = hero.stage // The pins behind the composer and the ones popped in front of it are each one layer of quads. const layers = { back: createQuads(back, () => wake()), front: createQuads(front, () => wake()) } const still = prefersReducedMotion() @@ -196,7 +196,7 @@ function mountPinBoard( const layout = () => { const s = stage.getBoundingClientRect() const l = logo.getBoundingClientRect() - const composer = stage.querySelector('[data-component="composer"]')?.getBoundingClientRect() + const composer = hero.composer.box.getBoundingClientRect() const pitch = Math.max(3, Math.round(l.width / COLS)) const x0 = Math.round(l.left - s.left + (l.width - pitch * COLS) / 2) const y0 = Math.round(l.top - s.top + (l.height - pitch * ROWS) / 2) @@ -209,7 +209,7 @@ function mountPinBoard( view.pitch = pitch view.depth = view.pitch * 1.7 view.size = view.pitch * 0.8 - view.composer = composer && { + view.composer = { left: composer.left - s.left, right: composer.right - s.left, top: composer.top - s.top, @@ -290,7 +290,7 @@ function mountPinBoard( if (!hits.length) return clock.knocked = now setRegion(true) - if (sound()) PinSound.knock(x, view.w) + sound.knock(x, view.w) } // Hitting a piled pin topples everything stacked above it. @@ -364,8 +364,12 @@ function mountPinBoard( const cy = view.y0 + (ROWS * view.pitch) / 2 // In game mode the board leans only slightly after the ball, so the bricks stay readable. const lean = view.game ? 0.12 : 0.6 - const tx = pointer.inside ? lerp(REST_TILT[0], clamp(((cx - pointer.x) / (view.w * 0.5)) * 1.4), lean) : REST_TILT[0] - const ty = pointer.inside ? lerp(REST_TILT[1], clamp(((cy - pointer.y) / (view.h * 0.5)) * 1.4), lean) : REST_TILT[1] + const tx = pointer.inside + ? lerp(REST_TILT[0], clamp(((cx - pointer.x) / (view.w * 0.5)) * 1.4), lean) + : REST_TILT[0] + const ty = pointer.inside + ? lerp(REST_TILT[1], clamp(((cy - pointer.y) / (view.h * 0.5)) * 1.4), lean) + : REST_TILT[1] const ease = 1 - Math.exp(-dt * 4) tilt.x += (tx - tilt.x) * ease tilt.y += (ty - tilt.y) * ease @@ -416,7 +420,7 @@ function mountPinBoard( z: clock.closed ? -0.2 : -0.8, zv: 0, }) - if (sound()) PinSound.slot(p.c, COLS, p.hx, view.w) + sound.slot(p.c, COLS, p.hx, view.w) continue } const e = 1 - Math.pow(1 - k, 3) @@ -448,7 +452,7 @@ function mountPinBoard( continue } p.y = surface - cell / 2 - if (sound()) PinSound.bounce(p.x, view.w, p.vy) + sound.bounce(p.x, view.w, p.vy) p.vy = -p.vy * 0.34 p.vx *= 0.55 p.spin = -p.spin * 0.5 + (Math.random() - 0.5) * 4 @@ -570,12 +574,28 @@ function mountPinBoard( for (const p of band) { if (p.lv !== lv) continue const fx = p.hx + ox * p.fd + sx * half - quads.quad(fx, p.hy + oy * p.fd - half, ox * (p.bd - p.fd), oy * (p.bd - p.fd), 0, size, colors.side[lv][sideX]) + quads.quad( + fx, + p.hy + oy * p.fd - half, + ox * (p.bd - p.fd), + oy * (p.bd - p.fd), + 0, + size, + colors.side[lv][sideX], + ) } for (const p of band) { if (p.lv !== lv) continue const fy = p.hy + oy * p.fd + sy * half - quads.quad(p.hx + ox * p.fd - half, fy, size, 0, ox * (p.bd - p.fd), oy * (p.bd - p.fd), colors.side[lv][sideY]) + quads.quad( + p.hx + ox * p.fd - half, + fy, + size, + 0, + ox * (p.bd - p.fd), + oy * (p.bd - p.fd), + colors.side[lv][sideY], + ) } } for (const p of band) @@ -692,8 +712,7 @@ function mountPinBoard( // Capturing the pointer keeps a long drag alive; without it the browser can start a text // selection or native drag mid-gesture and cancel the pointer stream. const onDown = (event: PointerEvent) => { - if (view.game || event.button !== 0 || (event.target instanceof Element && event.target.closest(INTERACTIVE))) - return + if (view.game || event.button !== 0 || !(event.target instanceof Element) || controls(event.target)) return event.preventDefault() stage.setPointerCapture(event.pointerId) toStage(event) @@ -703,6 +722,9 @@ function mountPinBoard( knock(pointer.x, pointer.y, 24, 560, 0, 0, performance.now() / 1000) wake() } + // Presses on the panel's controls, the composer, or the tip are theirs; the board only plays on empty space. + const controls = (target: Element) => + !!target.closest(INTERACTIVE) || hero.composer.box.contains(target) || !!hero.tip?.contains(target) const onUp = (event: Event) => { pointer.down = false if (event instanceof PointerEvent && stage.hasPointerCapture(event.pointerId)) @@ -740,9 +762,31 @@ function mountPinBoard( } layout() // The reveal staggers columns over 0.45 s and each rises over 0.3 s; the sweep spans the same window. - if (!still && sound()) PinSound.sweep({ duration: entrance === "sweep" ? REVEAL : 0.9, columns: COLS }) + if (!still) sound.sweep({ duration: entrance === "sweep" ? REVEAL : 0.9, columns: COLS }) + + const close = () => { + if (clock.closed) return + const now = performance.now() / 1000 + clock.closed = now + pointer.down = false + piles.top.fill(0) + piles.floor.fill(0) + for (const p of pins) { + if (p.state === HOME) continue + p.state = RETURN + p.x0 = p.x + p.y0 = p.y + p.rot0 = p.rot + p.t0 = now + (p.c / COLS) * 0.18 + p.duration = 0.28 + Math.random() * 0.06 + p.lift = 24 + Math.random() * 42 + } + if (!still) sound.sweep({ duration: 0.95, columns: COLS, reverse: true }) + wake() + } const handle: PinBoardHandle = { + close, collide: (x, y, radius, blast, vx, vy) => { const half = view.size / 2 const reach = radius + blast + half @@ -832,26 +876,6 @@ function mountPinBoard( return { handle, - close: () => { - if (clock.closed) return - const now = performance.now() / 1000 - clock.closed = now - pointer.down = false - piles.top.fill(0) - piles.floor.fill(0) - for (const p of pins) { - if (p.state === HOME) continue - p.state = RETURN - p.x0 = p.x - p.y0 = p.y - p.rot0 = p.rot - p.t0 = now + (p.c / COLS) * 0.18 - p.duration = 0.28 + Math.random() * 0.06 - p.lift = 24 + Math.random() * 42 - } - if (!still && sound()) PinSound.sweep({ duration: 0.95, columns: COLS, reverse: true }) - wake() - }, dispose: () => { cancelAnimationFrame(raf) resize.disconnect() diff --git a/packages/app/src/new-session/pin-quads.ts b/packages/gui-plugins/src/wordmark/pin-quads.ts similarity index 100% rename from packages/app/src/new-session/pin-quads.ts rename to packages/gui-plugins/src/wordmark/pin-quads.ts diff --git a/packages/gui-plugins/src/wordmark/pin-sound.ts b/packages/gui-plugins/src/wordmark/pin-sound.ts new file mode 100644 index 00000000000..7f1979939e9 --- /dev/null +++ b/packages/gui-plugins/src/wordmark/pin-sound.ts @@ -0,0 +1,206 @@ +// Synthesised stone sounds for the new session pin board. Nothing is loaded from disk; every sound is a +// short burst of filtered noise, optionally with a low thud, so the whole palette reads as pebbles on stone. + +const PENTATONIC = [0, 2, 4, 7, 9] + +type Audio = { context: AudioContext; bus: GainNode; noise: AudioBuffer; recent: number[] } + +function createAudio(): Audio { + const context = new AudioContext() + const limiter = context.createDynamicsCompressor() + limiter.threshold.value = -24 + limiter.ratio.value = 4 + limiter.connect(context.destination) + const master = context.createGain() + master.gain.value = 0.9 + master.connect(limiter) + const bus = context.createGain() + bus.connect(master) + const room = context.createConvolver() + room.buffer = impulse(context, 1.2, 3.2) + const wet = context.createGain() + wet.gain.value = 0.18 + bus.connect(room) + room.connect(wet) + wet.connect(master) + const noise = context.createBuffer(1, context.sampleRate, context.sampleRate) + noise.getChannelData(0).forEach((_, i, data) => (data[i] = Math.random() * 2 - 1)) + return { context, bus, noise, recent: [] } +} + +function impulse(context: AudioContext, seconds: number, decay: number) { + const length = Math.floor(context.sampleRate * seconds) + const buffer = context.createBuffer(2, length, context.sampleRate) + for (let channel = 0; channel < 2; channel++) { + const data = buffer.getChannelData(channel) + for (let i = 0; i < length; i++) data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / length, decay) + } + return buffer +} + +// Caps bursts of collision sounds so a crumble stays a patter rather than a roar. +function allow(a: Audio) { + const now = performance.now() + while (a.recent.length && now - a.recent[0] > 80) a.recent.shift() + if (a.recent.length >= 5) return false + a.recent.push(now) + return true +} + +/** One pebble click: band-passed noise with a resonant body and an optional low thud. */ +function pebble( + a: Audio, + at: number, + input: { freq: number; q: number; gain: number; decay: number; pan: number; thud?: number }, +) { + const c = a.context + const source = c.createBufferSource() + source.buffer = a.noise + const band = c.createBiquadFilter() + band.type = "bandpass" + band.frequency.value = input.freq + band.Q.value = input.q + const env = c.createGain() + env.gain.setValueAtTime(0.0001, at) + env.gain.exponentialRampToValueAtTime(input.gain, at + 0.002) + env.gain.exponentialRampToValueAtTime(0.0001, at + input.decay) + const pan = c.createStereoPanner() + pan.pan.value = Math.max(-0.9, Math.min(0.9, input.pan)) + source.connect(band).connect(env).connect(pan).connect(a.bus) + source.start(at, Math.random() * 0.8, input.decay + 0.02) + if (!input.thud) return + const body = c.createOscillator() + body.frequency.setValueAtTime(input.thud * 1.6, at) + body.frequency.exponentialRampToValueAtTime(input.thud, at + 0.03) + const thud = c.createGain() + thud.gain.setValueAtTime(0.0001, at) + thud.gain.exponentialRampToValueAtTime(input.gain * 0.5, at + 0.003) + thud.gain.exponentialRampToValueAtTime(0.0001, at + input.decay * 2.5) + body.connect(thud).connect(pan) + body.start(at) + body.stop(at + input.decay * 2.5 + 0.02) +} + +const note = (step: number) => + 440 * Math.pow(2, (74 + 12 * Math.floor(step / 5) + PENTATONIC[((step % 5) + 5) % 5] - 69) / 12) +const panOf = (x: number, width: number) => (width ? (x / width) * 1.6 - 0.8 : 0) + +/** + * The pin board's sounds. Each plays only while `enabled` is true and the browser allows audio; the audio graph is + * built on the first sound and closed by `dispose`. + */ +export function createPinSound(enabled: () => boolean) { + const state = { audio: undefined as Audio | undefined } + + /** Returns a running audio graph, or nothing when sounds are off or the browser would block them. */ + const audio = () => { + if (!enabled() || typeof AudioContext === "undefined" || document.hidden) return + if (!navigator.userActivation?.hasBeenActive) return + state.audio ??= createAudio() + if (state.audio.context.state === "suspended") void state.audio.context.resume() + if (state.audio.context.state !== "running") return + return state.audio + } + + return { + /** The wordmark rising in: a gritty stone slide sweeping across with pebbles settling under it. */ + sweep(input: { duration: number; columns: number; reverse?: boolean }) { + const a = audio() + if (!a) return + const c = a.context + const at = c.currentTime + 0.02 + const end = at + input.duration + + const source = c.createBufferSource() + source.buffer = a.noise + source.loop = true + const grit = c.createBiquadFilter() + grit.type = "bandpass" + grit.Q.value = 1.4 + grit.frequency.setValueAtTime(input.reverse ? 1500 : 260, at) + grit.frequency.exponentialRampToValueAtTime(input.reverse ? 260 : 1500, end) + const body = c.createBiquadFilter() + body.type = "lowpass" + body.frequency.value = 2400 + const env = c.createGain() + env.gain.setValueAtTime(0.0001, at) + env.gain.exponentialRampToValueAtTime(0.03, at + 0.12) + env.gain.setValueAtTime(0.03, end - 0.18) + env.gain.exponentialRampToValueAtTime(0.0001, end + 0.12) + const pan = c.createStereoPanner() + pan.pan.setValueAtTime(-0.7, at) + pan.pan.linearRampToValueAtTime(0.7, end) + source.connect(grit).connect(body).connect(env).connect(pan).connect(a.bus) + source.start(at) + source.stop(end + 0.15) + + const clicks = 22 + for (let i = 0; i < clicks; i++) { + const k = (i + Math.random() * 0.6) / clicks + pebble(a, at + k * (input.duration - 0.1) + 0.06, { + freq: 1800 + Math.random() * 1600, + q: 5, + gain: 0.02 + Math.random() * 0.018, + decay: 0.02 + Math.random() * 0.015, + pan: k * 1.4 - 0.7, + }) + } + }, + + /** A click that knocks pins out: one solid stone clack. */ + knock(x: number, width: number) { + const a = audio() + if (!a) return + pebble(a, a.context.currentTime, { freq: 1100, q: 2.2, gain: 0.14, decay: 0.05, pan: panOf(x, width), thud: 95 }) + }, + + /** The brick breaker ball smashing pins: a clack whose ring climbs the scale with each hit before the paddle. */ + brick(x: number, width: number, combo: number) { + const a = audio() + if (!a) return + const at = a.context.currentTime + pebble(a, at, { freq: 1300, q: 2, gain: 0.1, decay: 0.04, pan: panOf(x, width), thud: 110 }) + pebble(a, at + 0.004, { freq: note(Math.min(14, combo)), q: 16, gain: 0.06, decay: 0.09, pan: panOf(x, width) }) + }, + + /** The brick breaker ball landing on the paddle: a soft, low knock. */ + paddle(x: number, width: number) { + const a = audio() + if (!a) return + pebble(a, a.context.currentTime, { freq: 520, q: 1.4, gain: 0.12, decay: 0.05, pan: panOf(x, width), thud: 72 }) + }, + + /** A loose pin bouncing off the composer or the floor. */ + bounce(x: number, width: number, speed: number) { + const a = audio() + if (!a || !allow(a)) return + pebble(a, a.context.currentTime, { + freq: 2200 + Math.random() * 1400, + q: 6, + gain: Math.min(0.07, 0.012 + speed / 40000), + decay: 0.02, + pan: panOf(x, width), + }) + }, + + /** A pin seating back into its socket; pitch rises across the wordmark so the return reads as a cascade. */ + slot(column: number, columns: number, x: number, width: number) { + const a = audio() + if (!a || !allow(a)) return + pebble(a, a.context.currentTime, { + freq: note(Math.floor((column / columns) * 10)), + q: 14, + gain: 0.05, + decay: 0.045, + pan: panOf(x, width), + }) + }, + + dispose() { + void state.audio?.context.close() + state.audio = undefined + }, + } +} + +export type PinSound = ReturnType diff --git a/packages/gui-plugins/src/wordmark/renderer.tsx b/packages/gui-plugins/src/wordmark/renderer.tsx new file mode 100644 index 00000000000..23e570a44ec --- /dev/null +++ b/packages/gui-plugins/src/wordmark/renderer.tsx @@ -0,0 +1,31 @@ +import { lazy, Suspense } from "solid-js" +import { Slot, Style, type Plugin } from "@opencode/plugin/gui" +import type definition from "./index" +import css from "./wordmark.css?inline" + +const setup: Plugin.Setup = (ctx) => { + const WordmarkHero = lazy(() => import("./hero")) + // The hero shows as soon as the app opens on a new session, so its chunk loads now rather than when idle. + void WordmarkHero.preload() + + ctx.add(Style, css) + + // Below the default order, so a plugin's hero replaces this one. + ctx.add(Slot, { + at: "new-session.hero", + order: -1, + render: (input) => ( + + ), + }) +} + +export default setup diff --git a/packages/app/src/new-session/wordmark.css b/packages/gui-plugins/src/wordmark/wordmark.css similarity index 93% rename from packages/app/src/new-session/wordmark.css rename to packages/gui-plugins/src/wordmark/wordmark.css index 6a01197f1b7..28922c1e095 100644 --- a/packages/app/src/new-session/wordmark.css +++ b/packages/gui-plugins/src/wordmark/wordmark.css @@ -28,11 +28,11 @@ } /* The composer gives a little under the lodger while it is carried over it, hinting it can be dropped there. */ -[data-component="new-session"] [data-slot="new-session-composer"] { +[data-lodger-drop] { transition: transform 260ms cubic-bezier(0.34, 1.56, 0.64, 1); } -[data-component="new-session"] [data-slot="new-session-composer"][data-lodger-over] { +[data-lodger-drop][data-lodger-over] { transform: translateY(3px) scale(0.985); } diff --git a/packages/gui-plugins/src/wordmark/wordmark.stories.tsx b/packages/gui-plugins/src/wordmark/wordmark.stories.tsx new file mode 100644 index 00000000000..41729fdcdec --- /dev/null +++ b/packages/gui-plugins/src/wordmark/wordmark.stories.tsx @@ -0,0 +1,82 @@ +import { onCleanup, Show } from "solid-js" +import { Portal } from "solid-js/web" +import { createStore } from "solid-js/store" +import WordmarkHero from "./hero" +import { NewSessionPinBoard } from "./pin-board" +import { createPinSound } from "./pin-sound" +import { NewSessionWordmark, type Hero } from "./wordmark" +import css from "./wordmark.css?inline" + +export default { + title: "Plugins/Wordmark", + id: "plugins-wordmark", + component: WordmarkHero, +} + +// The new session panel as the host lays it out: the hero above a composer, with the panel as the stage. +function Panel(props: { pins: boolean }) { + const [state, setState] = createStore<{ stage?: HTMLDivElement; area?: HTMLDivElement; box?: HTMLFormElement }>({}) + + return ( +
setState("stage", stage)} + data-component="new-session" + class="relative isolate h-[640px] w-full overflow-hidden rounded-[10px] bg-v2-background-bg-base" + > + +
+
+ + {(parts) => { + const hero: Hero = { + stage: parts().stage, + composer: { area: parts().area, box: parts().box }, + tip: undefined, + sounds: true, + focus: () => parts().box.focus(), + } + + return props.pins ? : + }} + +
setState("area", area)} class="mt-8"> + setState("box", box)} + data-component="composer" + class="h-24 w-full rounded-xl bg-v2-background-bg-base shadow-[var(--v2-elevation-raised)]" + /> +
+
+
+
+ ) +} + +// The board already open, as it is once the pin is pulled. +function OpenBoard(props: { hero: Hero }) { + const sound = createPinSound(() => props.hero.sounds) + const [state, setState] = createStore<{ box?: HTMLDivElement }>({}) + + onCleanup(sound.dispose) + + return ( + <> + setState("box", box)} hero={props.hero} pins sound={sound} /> + + + {(logo) => } + + + + ) +} + +export const Flat = { + render: () => , +} + +export const PinBoard = { + render: () => , +} diff --git a/packages/app/src/new-session/wordmark.tsx b/packages/gui-plugins/src/wordmark/wordmark.tsx similarity index 95% rename from packages/app/src/new-session/wordmark.tsx rename to packages/gui-plugins/src/wordmark/wordmark.tsx index 4874e223d9d..7bffdf79c4b 100644 --- a/packages/app/src/new-session/wordmark.tsx +++ b/packages/gui-plugins/src/wordmark/wordmark.tsx @@ -1,8 +1,10 @@ +import type { SlotMap } from "@opencode/plugin/gui" import { Logo } from "@opencode/ui/logo" import { prefersReducedMotion } from "@opencode/ui/motion" import { For, onCleanup, onMount, Show } from "solid-js" -import { PinSound } from "./pin-sound" -import "./wordmark.css" +import type { PinSound } from "./pin-sound" + +export type Hero = SlotMap["new-session.hero"] // Each letter in the 234×42 logo viewBox, with its counter shadow, stem, and bottom-centre pivot. const LETTERS = [ @@ -114,8 +116,9 @@ type Parts = { */ export function NewSessionWordmark(props: { ref: (element: HTMLDivElement) => void + hero: Hero pins?: boolean - sound?: () => boolean + sound: PinSound onOpen?: () => void onClose?: () => void onFlat?: () => void @@ -142,7 +145,8 @@ export function NewSessionWordmark(props: { false)} + hero={props.hero} + sound={props.sound} onOpen={() => props.onOpen?.()} onClose={() => props.onClose?.()} onFlat={() => props.onFlat?.()} @@ -161,7 +165,8 @@ export function NewSessionWordmark(props: { */ function WordmarkLodger(props: { box: HTMLDivElement - sound: () => boolean + hero: Hero + sound: PinSound onOpen: () => void onClose: () => void onFlat: () => void @@ -184,6 +189,7 @@ function WordmarkLodger(props: { onCleanup( mountLodger( { box: props.box, stage, svg, flat, notch, letters, grip, neck, pin, critter, body, eyes, blink }, + props.hero, props.sound, props.onOpen, props.onClose, @@ -263,7 +269,8 @@ function WordmarkLodger(props: { function mountLodger( parts: Parts, - sound: () => boolean, + hero: Hero, + sound: PinSound, onOpen: () => void, onClose: () => void, onFlat: () => void, @@ -307,7 +314,7 @@ function mountLodger( const pointer = { x: HOLE.x, y: HOLE.y, inside: false, downX: HOLE.x, downY: HOLE.y } const impacts: { at: number; amp: number }[] = [] const timers = { raf: 0, blink: 0, last: 0 } - const panel = parts.box.closest('[data-component="new-session"]') ?? document.documentElement + const panel = hero.stage // The lodger's screen rect, read on resize and pointer entry so pointer moves never force a layout. const rect = { left: 0, top: 0, scale: 1, px: 0, py: 0 } // The composer, in lodger units while carrying; dropping the lodger on it starts the brick breaker. @@ -333,10 +340,10 @@ function mountLodger( const fitStage = () => { const l = parts.box.getBoundingClientRect() if (!l.width) return - const s = parts.box.closest('[data-component="new-session"]')?.getBoundingClientRect() + const s = panel.getBoundingClientRect() const pitch = Math.max(3, Math.round(l.width / 78)) - const x = s ? Math.round(l.left - s.left + (l.width - pitch * 78) / 2) - (l.left - s.left) : (l.width - pitch * 78) / 2 - const y = s ? Math.round(l.top - s.top + (l.height - pitch * 14) / 2) - (l.top - s.top) : (l.height - pitch * 14) / 2 + const x = Math.round(l.left - s.left + (l.width - pitch * 78) / 2) - (l.left - s.left) + const y = Math.round(l.top - s.top + (l.height - pitch * 14) / 2) - (l.top - s.top) parts.stage.style.left = `${x}px` parts.stage.style.top = `${y}px` parts.stage.style.width = `${pitch * 78}px` @@ -437,7 +444,7 @@ function mountLodger( } if (out > 0.05 || Math.hypot(c.vx, c.vy) > 0.5) return restHidden() - if (sound()) PinSound.slot(70, 78, c.x, W) + sound.slot(70, 78, c.x, W) blinkOnce() } @@ -478,7 +485,7 @@ function mountLodger( }) placeGrip("none") onOpen() - if (sound()) PinSound.knock(c.x, W) + sound.knock(c.x, W) if (still) return settleIdle() wake() } @@ -494,7 +501,7 @@ function mountLodger( { at: 1.35, run: () => { - if (sound()) PinSound.slot(75, 78, PIN_SLOT.x, W) + sound.slot(75, 78, PIN_SLOT.x, W) }, }, { at: 1.72, run: () => land(0.32) }, @@ -690,7 +697,7 @@ function mountLodger( fromY: c.y, }) onClose() - if (sound()) PinSound.knock(c.x, W) + sound.knock(c.x, W) if (still) { onFlat() restHidden() @@ -703,7 +710,7 @@ function mountLodger( { at: 0.95, run: () => { - if (sound()) PinSound.slot(75, 78, HOLE.x, W) + sound.slot(75, 78, HOLE.x, W) }, }, { @@ -819,11 +826,11 @@ function mountLodger( } const land = (amp: number) => { impact(amp) - if (sound()) PinSound.knock(c.x, W) + sound.knock(c.x, W) } const tap = (amp: number) => { if (amp) impact(amp) - if (sound()) PinSound.bounce(c.x, W, 3000) + sound.bounce(c.x, W, 3000) } const blinkOnce = () => { if (still) return @@ -959,15 +966,13 @@ function mountLodger( parts.grip.setPointerCapture(event.pointerId) measure() if (c.phase === "idle") { - drop.el = panel.querySelector('[data-slot="new-session-composer"]') ?? undefined - const r = drop.el?.querySelector('[data-component="composer"]')?.getBoundingClientRect() - if (r) { - const p = panel.getBoundingClientRect() - drop.l = (r.left - p.left - rect.px) / rect.scale - drop.r = (r.right - p.left - rect.px) / rect.scale - drop.t = (r.top - p.top - rect.py) / rect.scale - drop.b = (r.bottom - p.top - rect.py) / rect.scale - } + drop.el = hero.composer.area + const r = hero.composer.box.getBoundingClientRect() + const p = panel.getBoundingClientRect() + drop.l = (r.left - p.left - rect.px) / rect.scale + drop.r = (r.right - p.left - rect.px) / rect.scale + drop.t = (r.top - p.top - rect.py) / rect.scale + drop.b = (r.bottom - p.top - rect.py) / rect.scale } toUnits(event) Object.assign(pointer, { downX: pointer.x, downY: pointer.y }) @@ -1018,6 +1023,7 @@ function mountLodger( parts.grip.addEventListener("pointerup", onRelease) parts.grip.addEventListener("pointercancel", onRelease) parts.grip.addEventListener("lostpointercapture", onRelease) + hero.composer.area.setAttribute("data-lodger-drop", "") render() return () => { @@ -1031,6 +1037,8 @@ function mountLodger( parts.grip.removeEventListener("pointerup", onRelease) parts.grip.removeEventListener("pointercancel", onRelease) parts.grip.removeEventListener("lostpointercapture", onRelease) + hero.composer.area.removeAttribute("data-lodger-drop") + hero.composer.area.removeAttribute("data-lodger-over") } } diff --git a/packages/plugin/src/gui/builtin.ts b/packages/plugin/src/gui/builtin.ts index 9536e589939..e12136c374b 100644 --- a/packages/plugin/src/gui/builtin.ts +++ b/packages/plugin/src/gui/builtin.ts @@ -119,7 +119,7 @@ export type BuiltinSlot = { [At in keyof BuiltinSlotMap]: { /** The slot; see `BuiltinSlotMap`. */ readonly at: At - /** Slot contents render in ascending order. Defaults to 0. */ + /** Slot contents render in ascending order; `new-session.hero` shows only the last. Defaults to 0. */ readonly order?: number /** * Renders the content once; its own reactivity updates it. diff --git a/packages/plugin/src/gui/registries.ts b/packages/plugin/src/gui/registries.ts index f649e38a9e4..e17fee2c234 100644 --- a/packages/plugin/src/gui/registries.ts +++ b/packages/plugin/src/gui/registries.ts @@ -708,6 +708,36 @@ export interface SlotMap { /** The routed session; a new object when another session is routed. */ readonly session: MountedSession } + /** + * The new session screen's hero: the wordmark above the composer, and any easter egg it hides. One contribution + * shows, the one that sorts last by `order` (ties go to the later contribution), so a plugin's hero at the default + * `order` replaces the built-in wordmark, which uses -1. Without one the host shows the plain wordmark. The render + * sits in the hero's place in the layout; draw effects that span the panel into `stage`. The elements are the host's: + * an effect that moves, fades or disables one restores what it changed when it ends or unmounts. + */ + readonly "new-session.hero": { + /** + * The new session panel. It clips its content and positions absolute children, so render full-panel effects into + * it with `Portal` from `solid-js/web`, and listen to its pointer events for play anywhere on it. + */ + readonly stage: HTMLElement + /** The composer below the hero. */ + readonly composer: { + /** The composer's rounded surface. Read its geometry and colours; do not restyle it. */ + readonly box: HTMLElement + /** + * The composer with its location row. An effect may move, fade or disable it, as a game that takes the panel + * does. + */ + readonly area: HTMLElement + } + /** The tip pinned to the panel's bottom edge, such as the hint to connect a provider, while one shows. */ + readonly tip: HTMLElement | undefined + /** Whether the user has interface sounds on (Settings › Notifications). Read it before each sound. */ + readonly sounds: boolean + /** Moves keyboard focus back to the composer, as when a game that took the keyboard ends. */ + focus(): void + } } /** Content for one of the host's slots, typed by `at`. */ @@ -715,7 +745,7 @@ export type Slot = { [At in keyof SlotMap]: { /** The slot; see `SlotMap`. */ readonly at: At - /** Slot contents render in ascending order. Defaults to 0. */ + /** Slot contents render in ascending order; `new-session.hero` shows only the last. Defaults to 0. */ readonly order?: number /** * Renders the content once; its own reactivity updates it. Session and active fields are reactive getters, so read diff --git a/services/www/src/docs/content/build/plugins/gui/index.mdx b/services/www/src/docs/content/build/plugins/gui/index.mdx index 2c2a391bdb5..ce215180df6 100644 --- a/services/www/src/docs/content/build/plugins/gui/index.mdx +++ b/services/www/src/docs/content/build/plugins/gui/index.mdx @@ -950,7 +950,7 @@ interface SettingEntry { ### Slots -`Slot` renders UI into one of four window slots. +`Slot` renders UI into one of five window slots. ```tsx import { Slot } from "@opencode/plugin/gui" @@ -967,6 +967,8 @@ ctx.add(Slot, { `false`. - `session.location.menu` adds items to the project menu, after its location details. - `session.panel.end` holds actions at the trailing end of the side region's tab strip. +- `new-session.hero` is the wordmark above the new session composer. It has one owner; see + [Easter eggs](#easter-eggs). - `order` sorts the items in one slot. `session.location.menu` receives `shown`, which is `true` while the project menu is open. Subscribe to location data @@ -979,6 +981,40 @@ ctx.add(Slot, { }) ``` +#### Easter eggs + +`new-session.hero` replaces the wordmark on the new session screen with your own, such as a game hidden in the logo. +One contribution shows: the one that sorts last by `order`, with ties going to the later contribution. The built-in +wordmark uses `order: -1`, so your hero replaces it at the default `order`. Disable your plugin to bring the built-in +back. + +```tsx +import { Portal } from "solid-js/web" +import { Slot } from "@opencode/plugin/gui" + +ctx.add(Slot, { + at: "new-session.hero", + render: (input) => ( + <> + input.sounds && chime()} /> + + + + + ), +}) +``` + +- The render takes the wordmark's place in the layout. Render effects that span the panel into `stage` with `Portal`. + The panel clips its content and positions absolute children. +- `composer.box` is the composer's rounded surface, for its geometry and colours. `composer.area` is the composer with + its location row; a game may move, fade or disable it. +- `tip` is the tip at the bottom of the panel while one shows. +- `sounds` is the user's interface sounds setting. Read it before each sound. +- `focus()` returns the keyboard to the composer, for example when a game ends. +- The panel's elements belong to the host. Restore everything you change on them when your effect ends or unmounts. +- Third-party heroes show in the desktop app only. The web app runs built-in plugins only. + #### Reference ```ts @@ -991,6 +1027,13 @@ interface SlotMap { "session.header": { screen: SessionScreen; session: MountedSession; active: boolean } "session.location.menu": { screen: SessionScreen; session: MountedSession; shown: boolean } "session.panel.end": { screen: SessionScreen; session: MountedSession } + "new-session.hero": { + stage: HTMLElement + composer: { box: HTMLElement; area: HTMLElement } + tip: HTMLElement | undefined + sounds: boolean + focus(): void + } } ```