summaryrefslogtreecommitdiffhomepage
path: root/packages/ui/src/components/tool-utils.ts
blob: 171649e3dc68a81bc733dd80b189b3ba5fbd0163 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js"
import {
  animate,
  type AnimationPlaybackControls,
  clearFadeStyles,
  clearMaskStyles,
  COLLAPSIBLE_SPRING,
  GROW_SPRING,
  WIPE_MASK,
} from "./motion"
import { prefersReducedMotion } from "../hooks/use-reduced-motion"
import type { ToolPart } from "@opencode-ai/sdk/v2"

export const TEXT_RENDER_THROTTLE_MS = 100

export function createThrottledValue(getValue: () => string) {
  const [value, setValue] = createSignal(getValue())
  let timeout: ReturnType<typeof setTimeout> | undefined
  let last = 0

  createEffect(() => {
    const next = getValue()
    const now = Date.now()

    const remaining = TEXT_RENDER_THROTTLE_MS - (now - last)
    if (remaining <= 0) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = undefined
      }
      last = now
      setValue(next)
      return
    }
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      last = Date.now()
      setValue(next)
      timeout = undefined
    }, remaining)
  })

  onCleanup(() => {
    if (timeout) clearTimeout(timeout)
  })

  return value
}

export function busy(status: string | undefined) {
  return status === "pending" || status === "running"
}

export function hold(state: () => boolean, wait = 2000) {
  const [live, setLive] = createSignal(state())
  let timer: ReturnType<typeof setTimeout> | undefined

  createEffect(() => {
    if (state()) {
      if (timer) clearTimeout(timer)
      timer = undefined
      setLive(true)
      return
    }

    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      timer = undefined
      setLive(false)
    }, wait)
  })

  onCleanup(() => {
    if (timer) clearTimeout(timer)
  })

  return live
}

export function updateScrollMask(el: HTMLElement, fade = 12) {
  const { scrollTop, scrollHeight, clientHeight } = el
  const overflow = scrollHeight - clientHeight
  if (overflow <= 1) {
    el.style.maskImage = ""
    el.style.webkitMaskImage = ""
    return
  }
  const top = scrollTop > 1
  const bottom = scrollTop < overflow - 1
  const mask =
    top && bottom
      ? `linear-gradient(to bottom, transparent 0, black ${fade}px, black calc(100% - ${fade}px), transparent 100%)`
      : top
        ? `linear-gradient(to bottom, transparent 0, black ${fade}px)`
        : bottom
          ? `linear-gradient(to bottom, black calc(100% - ${fade}px), transparent 100%)`
          : ""
  el.style.maskImage = mask
  el.style.webkitMaskImage = mask
}

export function useCollapsible(options: {
  content: () => HTMLElement | undefined
  body: () => HTMLElement | undefined
  open: () => boolean
  measure?: () => number
  onOpen?: () => void
}) {
  let heightAnim: AnimationPlaybackControls | undefined
  let fadeAnim: AnimationPlaybackControls | undefined
  let gen = 0

  createEffect(
    on(
      options.open,
      (isOpen) => {
        const content = options.content()
        const body = options.body()
        if (!content || !body) return
        heightAnim?.stop()
        fadeAnim?.stop()
        const id = ++gen
        if (isOpen) {
          content.style.display = ""
          content.style.height = "0px"
          body.style.opacity = "0"
          body.style.filter = "blur(2px)"
          fadeAnim = animate(body, { opacity: [0, 1], filter: ["blur(2px)", "blur(0px)"] }, COLLAPSIBLE_SPRING)
          queueMicrotask(() => {
            if (gen !== id) return
            const c = options.content()
            if (!c) return
            const h = options.measure?.() ?? Math.ceil(body.getBoundingClientRect().height)
            heightAnim = animate(c, { height: ["0px", `${h}px`] }, COLLAPSIBLE_SPRING)
            heightAnim.finished.then(
              () => {
                if (gen !== id) return
                c.style.height = "auto"
                options.onOpen?.()
              },
              () => {},
            )
          })
          return
        }

        const h = content.getBoundingClientRect().height
        heightAnim = animate(content, { height: [`${h}px`, "0px"] }, COLLAPSIBLE_SPRING)
        fadeAnim = animate(body, { opacity: [1, 0], filter: ["blur(0px)", "blur(2px)"] }, COLLAPSIBLE_SPRING)
        heightAnim.finished.then(
          () => {
            if (gen !== id) return
            content.style.display = "none"
          },
          () => {},
        )
      },
      { defer: true },
    ),
  )

  onCleanup(() => {
    ++gen
    heightAnim?.stop()
    fadeAnim?.stop()
  })
}

export function useContextToolPending(parts: () => ToolPart[], working?: () => boolean) {
  const anyRunning = createMemo(() => parts().some((part) => busy(part.state.status)))
  const [settled, setSettled] = createSignal(false)
  createEffect(() => {
    if (!anyRunning() && !working?.()) setSettled(true)
  })
  return createMemo(() => !settled() && (!!working?.() || anyRunning()))
}

export function useRowWipe(opts: {
  id: () => string
  text: () => string | undefined
  ref: () => HTMLElement | undefined
  seen: Set<string>
}) {
  const reduce = prefersReducedMotion

  createEffect(() => {
    const id = opts.id()
    const txt = opts.text()
    const el = opts.ref()
    if (!el) return
    if (!txt) {
      clearFadeStyles(el)
      clearMaskStyles(el)
      return
    }
    if (reduce() || typeof window === "undefined") {
      clearFadeStyles(el)
      clearMaskStyles(el)
      return
    }
    if (opts.seen.has(id)) {
      clearFadeStyles(el)
      clearMaskStyles(el)
      return
    }
    opts.seen.add(id)

    el.style.maskImage = WIPE_MASK
    el.style.webkitMaskImage = WIPE_MASK
    el.style.maskSize = "240% 100%"
    el.style.webkitMaskSize = "240% 100%"
    el.style.maskRepeat = "no-repeat"
    el.style.webkitMaskRepeat = "no-repeat"
    el.style.maskPosition = "100% 0%"
    el.style.webkitMaskPosition = "100% 0%"
    el.style.opacity = "0"
    el.style.filter = "blur(2px)"
    el.style.transform = "translateX(-0.06em)"

    let done = false
    const clear = () => {
      if (done) return
      done = true
      clearFadeStyles(el)
      clearMaskStyles(el)
    }
    if (typeof requestAnimationFrame !== "function") {
      clear()
      return
    }
    let anim: AnimationPlaybackControls | undefined
    let frame: number | undefined = requestAnimationFrame(() => {
      frame = undefined
      const node = opts.ref()
      if (!node) return
      anim = animate(
        node,
        {
          opacity: [0, 1],
          filter: ["blur(2px)", "blur(0px)"],
          transform: ["translateX(-0.06em)", "translateX(0)"],
          maskPosition: "0% 0%",
        },
        GROW_SPRING,
      )

      anim.finished.catch(() => {}).finally(clear)
    })

    onCleanup(() => {
      if (frame !== undefined) {
        cancelAnimationFrame(frame)
        clear()
      }
    })
  })
}

export function useToolFade(
  ref: () => HTMLElement | undefined,
  options?: { delay?: number; wipe?: boolean; animate?: boolean },
) {
  let anim: AnimationPlaybackControls | undefined
  let frame: number | undefined
  const delay = options?.delay ?? 0
  const wipe = options?.wipe ?? false
  const active = options?.animate !== false

  onMount(() => {
    if (!active) return

    const el = ref()
    if (!el || typeof window === "undefined") return
    if (prefersReducedMotion()) return

    const mask =
      wipe &&
      typeof CSS !== "undefined" &&
      (CSS.supports("mask-image", "linear-gradient(to right, black, transparent)") ||
        CSS.supports("-webkit-mask-image", "linear-gradient(to right, black, transparent)"))

    el.style.opacity = "0"
    el.style.filter = wipe ? "blur(3px)" : "blur(2px)"
    el.style.transform = wipe ? "translateX(-0.06em)" : "translateY(0.04em)"

    if (mask) {
      el.style.maskImage = WIPE_MASK
      el.style.webkitMaskImage = WIPE_MASK
      el.style.maskSize = "240% 100%"
      el.style.webkitMaskSize = "240% 100%"
      el.style.maskRepeat = "no-repeat"
      el.style.webkitMaskRepeat = "no-repeat"
      el.style.maskPosition = "100% 0%"
      el.style.webkitMaskPosition = "100% 0%"
    }

    frame = requestAnimationFrame(() => {
      frame = undefined
      const node = ref()
      if (!node) return

      anim = wipe
        ? mask
          ? animate(
              node,
              { opacity: 1, filter: "blur(0px)", transform: "translateX(0)", maskPosition: "0% 0%" },
              { ...GROW_SPRING, delay },
            )
          : animate(node, { opacity: 1, filter: "blur(0px)", transform: "translateX(0)" }, { ...GROW_SPRING, delay })
        : animate(node, { opacity: 1, filter: "blur(0px)", transform: "translateY(0)" }, { ...GROW_SPRING, delay })

      anim?.finished.then(() => {
        const value = ref()
        if (!value) return
        clearFadeStyles(value)
        if (mask) clearMaskStyles(value)
      })
    })
  })

  onCleanup(() => {
    if (frame !== undefined) cancelAnimationFrame(frame)
    anim?.stop()
  })
}