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
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/views/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@types/d3-scale": "^4.0.9",
"@types/d3-shape": "^3.2.0",
"@types/node": "catalog:tooling",
"happy-dom": "^21.0.4",
"typescript": "catalog:tooling",
"vite": "catalog:",
"vitest": "catalog:"
Expand Down
77 changes: 77 additions & 0 deletions packages/views/src/lib/findable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// @vitest-environment happy-dom
import { Virtualizer } from "@tanstack/virtual-core"
import { describe, expect, test } from "vitest"
import { bindFindable, type FindableMatch } from "./findable"
import { DOM_OPTIONS, type Instance } from "./virtualizer"

const ROW_HEIGHT = 30

/** A scroller with both stand-in layers, as `findableLayers` renders them, over a measured virtualizer. */
const setUp = (count: number, scrollMargin = 0) => {
const scroller = document.createElement("div")
scroller.innerHTML = `
<div role="log">
<div data-findable-side="before"><div hidden="until-found" data-group>
<div hidden="until-found" data-findable-index="3">row 3</div>
</div></div>
<div data-findable-side="after"><div hidden="until-found" data-group>
<div hidden="until-found" data-findable-index="40">row 40</div>
<div hidden="until-found" data-findable-index="99">row 99</div>
</div></div>
</div>`
document.body.append(scroller)
const virtualizer: Instance = new Virtualizer<HTMLElement, HTMLElement>({
count,
getScrollElement: () => scroller,
estimateSize: () => ROW_HEIGHT,
scrollMargin,
...DOM_OPTIONS,
})
virtualizer.getVirtualItems()
const matches: Array<FindableMatch> = []
const unbind = bindFindable(scroller, virtualizer, (match) => matches.push(match))
const standIn = (index: number) =>
scroller.querySelector<HTMLElement>(`[data-findable-index="${index}"]`) ??
document.createElement("div")
// The browser fires `beforematch` on the stand-in, then on its group; it bubbles.
const match = (index: number) => {
const target = standIn(index)
target.dispatchEvent(new Event("beforematch", { bubbles: true }))
target.parentElement?.dispatchEvent(new Event("beforematch", { bubbles: true }))
}
return { scroller, matches, unbind, standIn, match }
}

describe("bindFindable", () => {
test("a match moves the stand-in to its row's offset and reports the row and its side, once", () => {
const list = setUp(50)
list.match(40)
expect(list.standIn(40).style.top).toBe(`${40 * ROW_HEIGHT}px`)
expect(list.standIn(40).style.height).toBe(`${ROW_HEIGHT}px`)
list.match(3)
expect(list.matches).toEqual([
{ index: 40, side: "after" },
{ index: 3, side: "before" },
])
})

test("the offset is in the list's coordinates: the scroll margin is taken off", () => {
const list = setUp(50, 120)
list.match(40)
expect(list.standIn(40).style.top).toBe(`${40 * ROW_HEIGHT}px`)
})

test("a row the virtualizer has not counted yet is not reported or moved", () => {
const list = setUp(50)
list.match(99)
expect(list.matches).toEqual([])
expect(list.standIn(99).style.top).toBe("")
})

test("unbinding stops reporting matches", () => {
const list = setUp(50)
list.unbind()
list.match(40)
expect(list.matches).toEqual([])
})
})
196 changes: 196 additions & 0 deletions packages/views/src/lib/findable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import { Array as Arr, Option, Order, Schema } from "effect"
import { createKeyedLazy, type Html, type HtmlBuilder } from "foldkit/html"
import type { Instance } from "./virtualizer"

// Find in page (Cmd+F) for a virtualized list, after ui-sdk.dev's `findable`: rows outside the
// window get `hidden="until-found"` stand-ins before and after it, in list order. On `beforematch`
// the stand-in moves to its row's offset, so the browser's own scroll brings the row on screen.

export const FindableSide = Schema.Literals(["before", "after"])
export type FindableSide = typeof FindableSide.Type

/** The row the browser matched, and the layer its stand-in is in. */
export const FindableMatch = Schema.Struct({ index: Schema.Number, side: FindableSide })
export type FindableMatch = typeof FindableMatch.Type

/** The found row; `isRendered` once a window held it, so the next window without it ends the find. */
export const Found = Schema.Struct({ ...FindableMatch.fields, isRendered: Schema.Boolean })
export type Found = typeof Found.Type

export const foundOf = (match: FindableMatch): Found => ({ ...match, isRendered: false })

/** The found row after a new window: kept until its row has rendered and then left the window. */
export const foundAfterWindow = (
found: Option.Option<Found>,
rendered: ReadonlyArray<number>,
): Option.Option<Found> =>
Option.flatMap(found, (row) => {
const isRendered = rendered.includes(row.index)
if (isRendered === row.isRendered) return found
return isRendered ? Option.some({ ...row, isRendered }) : Option.none()
})

const INDEX_ATTRIBUTE = "findable-index"
const SIDE_ATTRIBUTE = "findable-side"
/** Stand-ins are grouped so the browser skips style and layout for a group until it matches. */
const CHUNK = 64

// Zero-size and invisible: the stand-in only has to be found, its row shows the text.
const LAYER_STYLE = {
position: "absolute",
top: "0px",
left: "0px",
width: "100%",
height: "0px",
overflow: "clip",
opacity: "0",
"pointer-events": "none",
contain: "strict",
} as const
const STAND_IN_STYLE = { position: "absolute", left: "0px", width: "100%" } as const

export interface FindableLayers<A> {
readonly items: ReadonlyArray<A>
/** The row's searchable text: what it shows, not timestamps. Module-level, so groups memoize. */
readonly textOf: (item: A, variant: string) => ReadonlyArray<string>
/** Anything `textOf` reads besides the item (wrap mode, columns); a change rebuilds the groups. */
readonly variant: string
/** The rendered rows' indices: their own text is what the browser finds. */
readonly rendered: ReadonlyArray<number>
readonly found: Option.Option<Found>
}

// Keyed by side and chunk: bounded by the row count / CHUNK.
const lazyGroup = createKeyedLazy()

const standIn = <A, Message>(
h: HtmlBuilder<Message>,
index: number,
isFound: boolean,
item: A,
textOf: (item: A, variant: string) => ReadonlyArray<string>,
variant: string,
): Html =>
h.keyed("div")(
String(index),
[
h.DataAttribute(INDEX_ATTRIBUTE, String(index)),
h.Style(STAND_IN_STYLE),
...(isFound ? [] : [h.Attribute("hidden", "until-found")]),
],
// One text node per row: a stand-in costs two DOM nodes.
[Arr.join(textOf(item, variant), " ")],
)

const group = <A, Message>(
h: HtmlBuilder<Message>,
side: FindableSide,
chunk: number,
from: number,
to: number,
found: number,
items: ReadonlyArray<A>,
textOf: (item: A, variant: string) => ReadonlyArray<string>,
variant: string,
): Html =>
h.keyed("div")(
`${side}-${chunk}`,
found >= 0 ? [] : [h.Attribute("hidden", "until-found")],
Arr.flatMap(Arr.range(chunk * CHUNK, chunk * CHUNK + CHUNK - 1), (index) => {
const item = items[index]
if (item === undefined || ((index < from || index > to) && index !== found)) return []
return [standIn(h, index, index === found, item, textOf, variant)]
}),
)

const layer = <A, Message>(
h: HtmlBuilder<Message>,
side: FindableSide,
from: number,
to: number,
input: FindableLayers<A>,
): Html => {
const found = Option.match(input.found, {
onNone: () => -1,
onSome: (match) => (match.side === side ? match.index : -1),
})
const rangeChunks = from <= to ? Arr.range(Math.floor(from / CHUNK), Math.floor(to / CHUNK)) : []
const chunks = Arr.sort(
Arr.dedupe(found < 0 ? rangeChunks : [...rangeChunks, Math.floor(found / CHUNK)]),
Order.Number,
)
return h.keyed("div")(
side,
[h.DataAttribute(SIDE_ATTRIBUTE, side), h.Style(LAYER_STYLE)],
Arr.flatMap(chunks, (chunk) => {
const first = chunk * CHUNK
const last = first + CHUNK - 1
// Only the part of the range inside this chunk is a lazy argument, so moving the window
// rebuilds the one or two chunks at its edges.
const clippedFrom = Math.max(from, first)
const clippedTo = Math.min(to, last)
const foundHere = found >= first && found <= last ? found : -1
const vnode = lazyGroup(`${side}-${chunk}`, group, [
h,
side,
chunk,
clippedFrom,
clippedTo,
foundHere,
input.items,
input.textOf,
input.variant,
])
return vnode === null ? [] : [vnode]
}),
)
}

/**
* The two stand-in layers, placed in the list container (positioned, as tall as the list): the
* `before` layer ahead of the rendered rows, the `after` layer behind them.
*/
export const findableLayers = <A, Message>(
h: HtmlBuilder<Message>,
input: FindableLayers<A>,
): Readonly<{ before: Html; after: Html }> => {
const first = Arr.match(input.rendered, {
onEmpty: () => input.items.length,
onNonEmpty: (r) => Math.min(...r),
})
const last = Arr.match(input.rendered, {
onEmpty: () => input.items.length - 1,
onNonEmpty: (r) => Math.max(...r),
})
return {
before: layer(h, "before", 0, first - 1, input),
after: layer(h, "after", last + 1, input.items.length - 1, input),
}
}

/**
* Listens for the browser's `beforematch` under `scroller`: the matched stand-in moves to its row's
* offset (in the list container's coordinates, `start - scrollMargin`), and the match is reported.
*/
export const bindFindable = (
scroller: HTMLElement,
virtualizer: Instance,
onMatch: (match: FindableMatch) => void,
): (() => void) => {
const onBeforeMatch = (event: Event) => {
Comment thread
Makisuo marked this conversation as resolved.
Resolved
const target = event.target
if (!(target instanceof HTMLElement)) return
const index = Number(target.dataset.findableIndex)
if (target.dataset.findableIndex === undefined || !Number.isInteger(index)) return
const side = target.closest<HTMLElement>(`[data-${SIDE_ATTRIBUTE}]`)?.dataset.findableSide
if (side !== "before" && side !== "after") return
// A row the virtualizer has not counted yet has no offset to scroll to.
const item = virtualizer.measurementsCache[index]
if (item === undefined) return
target.style.top = `${item.start - virtualizer.options.scrollMargin}px`
target.style.height = `${item.size}px`
onMatch({ index, side })
}
scroller.addEventListener("beforematch", onBeforeMatch)
return () => scroller.removeEventListener("beforematch", onBeforeMatch)
}
3 changes: 3 additions & 0 deletions packages/views/src/ui/logs/logs-stream-message.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Schema } from "effect"
import { defineMessageUnion } from "foldkit/message"
import { FindableMatch } from "../../lib/findable"
import * as AttributesPanel from "../attributes/attributes-panel"

/** A rendered row of the virtual window: which log, and where it sits in the list. */
Expand All @@ -12,6 +13,8 @@ export type NavigationKey = typeof NavigationKey.Type
export const Message = defineMessageUnion({
/** The virtualizer's window moved or a row was measured. */
ChangedVirtualWindow: { rows: Schema.Array(VirtualRow), totalSize: Schema.Number },
/** The browser's find in page matched a row that was not rendered. */
FoundRow: { match: FindableMatch },
/** The scroller left the newest rows, or came back to them. */
ChangedScrolledAway: { isScrolledAway: Schema.Boolean },
EnteredStream: {},
Expand Down
21 changes: 20 additions & 1 deletion packages/views/src/ui/logs/logs-stream-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { Message } from "./logs-stream-message"
import { eyebrow } from "../eyebrow"
import type * as AttributesPanel from "../attributes/attributes-panel"
import type { CopyStatus } from "../copy-button"
import { findableLayers } from "../../lib/findable"
import { ROW_LINE_CHARS, ROW_WRAPPED_CHARS, textWindow } from "../../lib/display-text"
import { COUNT_ATTRIBUTE, LAYOUT_ATTRIBUTE, STREAM_ATTRIBUTE, VirtualizeLogStream } from "./virtualize"

export interface ViewInputs {
Expand Down Expand Up @@ -143,6 +145,16 @@ const rowView = (
canFilter,
})

/** What find in page searches in a row that is not rendered: the text the row shows. */
const findableText = (row: LogRowView, variant: string): ReadonlyArray<string> => [
row.severity,
row.serviceName,
...Arr.flatMap(row.pinned, (cell) => (cell.isEmpty ? [] : [cell.value])),
variant === "wrap"
? textWindow(row.body, undefined, ROW_WRAPPED_CHARS)
: textWindow(row.firstLine, undefined, ROW_LINE_CHARS),
]

// Rows are keyed by index; the slot is `index % 256` so the cache stays bounded
// (a window never holds 256 rows) while each slot still renders at one position.
const lazyRow = createKeyedLazy()
Expand Down Expand Up @@ -173,6 +185,13 @@ export const view = defineView<Model, Message, ViewInputs>((model, inputs, h) =>
]),
]
})
const findable = findableLayers(h, {
items: model.rows,
textOf: findableText,
variant: inputs.wrap ? "wrap" : "nowrap",
rendered: Arr.map(model.window, (row) => row.index),
found: model.found,
})
return h.div(
inputs.isBare === true
? [h.Class("contents")]
Expand Down Expand Up @@ -213,7 +232,7 @@ export const view = defineView<Model, Message, ViewInputs>((model, inputs, h) =>
h.Style({ height: `${model.totalSize}px`, position: "relative" }),
h.Role("log"),
],
rows,
[findable.before, ...rows, findable.after],
),
],
),
Expand Down
Loading
Loading