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
16 changes: 13 additions & 3 deletions docs/design/proposals/headless-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ them:
shown panes, and the Inspector's snapshot page uses it (`paintState`) for its
readiness. #122's events depend on every shown pane, so they stay derived
from `rendererStatus` and `paint` until the store composes the panes (step
4), where they become its effects, with the same names.
5), where they become its effects, with the same names.
3. **Playback without React.** `createPlaybackController`
(`projection/playback-controller.ts`) drives `playbackLifecycle` with
`createActor`: the frame loop runs on an injectable scheduler
Expand All @@ -122,8 +122,18 @@ them:
step 5, with the settings store as its host. Node tests cover playing,
pausing, seeking, a new subject and a declined play with a hand-stepped
scheduler.
4. **Selectors and selection.** Rows, scope, summary, payloads and selection
move into the store; the remaining per-concern hooks go.
4. **Selectors and selection.** The row filter (`createRowFilter`) and the
renderer payloads (`createRendererPayloads`) become framework-free selectors,
built from one-slot memos (`projection/memo.ts`) so each result keeps its
identity while its inputs do. Selection is pure functions (`selectionOf`,
`selectedPaths`, `selectedTarget`, `targetSelection`, and
`createSelectionReport` for `onSelectionChange`), and the pinned target,
hover and anchors are one reducer (`interaction`) that `useProjection` runs
with `useReducer`. #122's events are told by `createStatusEvents`, which
`useStatusEvents` calls after each commit. The hooks keep only React's part:
one selector instance per component and the effects that report. The store
composes these in step 5, where the status events become its effects, with
the same names.
5. **The adapter.** `createProjection` is exported, `useProjection` becomes
`useSyncExternalStore` over it, and `controllerRef` hosts can `subscribe`.
6. **`mountStage` and a vanilla host.** The stage without React, a Storybook
Expand Down
154 changes: 101 additions & 53 deletions packages/host/core/src/projection/filtering.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useCallback, useMemo} from 'react'
import {useEffect, useState} from 'react'
import {changeContext, isScopeChange, regenerated, variedWithinTolerance} from '@githubnext/projections-renderer-sdk/presentation'
import type {ViewScope} from '@githubnext/projections-renderer-sdk/presentation'
import {humanizeKind} from '@githubnext/projections-renderer-sdk/presentation'
Expand All @@ -8,6 +8,8 @@ import type {Row, ViewSubject} from '../model.js'
import {rowInSummary} from '../summary.js'
import type {SummaryFigure} from '../summary.js'
import type {RequestChange, ValueOf} from './controllable.js'
import {selector} from './memo.js'
import type {Selector} from './memo.js'
import type {ProjectionController} from './types.js'

function matches(row: Row, query: string): boolean {
Expand Down Expand Up @@ -54,61 +56,107 @@ function inScope(row: Row, scope: ViewScope, variedOnly: boolean, regeneratedOnl
return true
}

/** What the scope and filters keep (see `createRowFilter`). */
export interface RowFilter {
visibleRows: readonly Row[]
filter: FilterPayload
counts: ScopeCounts
hidden: ScopeHidden[]
}

/**
* The rows the scope and filters keep, the filter payload renderers apply, and each scope's count. The scope decides
* what renderers lay out: the Changes scope is the changes and the unchanged items that give them context
* (`changeContext`), and renderers fold or leave out the rest. The summary filter and find narrow within it
* (`visibleRows`) without removing anything from the layout: renderers recede what they leave out (the filter's
* `ids`), in either scope. The counts are of the kinds
* the summary bar's count figures name (so a table's structural relationships aren't counted beside its columns), else
* of every row: its changes, and every item of both revisions, so All is more than Changes whenever Changes hides any.
* The rows the scope and filters keep, the filter payload renderers apply, and each scope's count, as a selector that
* recomputes each part only when its inputs change. The scope decides what renderers lay out: the Changes scope is the
* changes and the unchanged items that give them context (`changeContext`), and renderers fold or leave out the rest.
* The summary filter and find narrow within it (`visibleRows`) without removing anything from the layout: renderers
* recede what they leave out (the filter's `ids`), in either scope. The counts are of the kinds the summary bar's count
* figures name (so a table's structural relationships aren't counted beside its columns), else of every row: its
* changes, and every item of both revisions, so All is more than Changes whenever Changes hides any.
*/
export function useRowFilter(rows: readonly Row[], subject: ViewSubject, state: FilterState, summary: readonly SummaryFigure[]) {
const {variedOnly, regeneratedOnly, summaryFilter, search} = state
const query = search.trim().toLocaleLowerCase()
// A comparison without changes has nothing to scope to: it shows every item (and the view says there are none).
const unchanged = useMemo(() => !rows.some(isScopeChange), [rows])
const scope = state.scope === 'changes' && unchanged ? 'all' : state.scope
// What the scope lays out: in Changes, the changes and their context, whatever the summary filter and find.
const scopedRows = useMemo(() => {
const kept = rows.filter(row => inScope(row, scope, variedOnly, regeneratedOnly))
if (scope !== 'changes' || subject.mode !== 'comparison') return kept
const {shown} = changeContext(rows, subject)
return rows.filter(row => shown.has(row.id))
}, [rows, subject, scope, variedOnly, regeneratedOnly])
const kept = useCallback(
(row: Row) => (!summaryFilter || rowInSummary(row, summaryFilter)) && matches(row, query),
[summaryFilter, query],
)
const visibleRows = useMemo(() => scopedRows.filter(kept), [scopedRows, kept])
const filter = useMemo<FilterPayload>(() => {
const ids = (list: readonly Row[]) => (list.length <= rendererLimits.filterIds ? list.map(row => row.id) : null)
// What is at full strength: what the summary filter and find keep of every item (the Changes scope lays out what it
// shows, `scope`, and draws some items between them besides), or of the noise, which is a filter too.
const narrowed = Boolean(query) || Boolean(summaryFilter) || scope === 'noise'
return {
query: search,
changesOnly: scope === 'changes',
ids: narrowed ? ids(scope === 'noise' ? visibleRows : rows.filter(kept)) : null,
scope: scope === 'changes' ? ids(scopedRows) : null,
export function createRowFilter(): Selector<
[rows: readonly Row[], subject: ViewSubject, state: FilterState, summary: readonly SummaryFigure[]],
RowFilter
> {
return selector(({memo}) => {
// A comparison without changes has nothing to scope to: it shows every item (and the view says there are none).
const unchangedOf = memo((rows: readonly Row[]) => !rows.some(isScopeChange))
// What the scope lays out: in Changes, the changes and their context, whatever the summary filter and find.
const scopedOf = memo((rows: readonly Row[], subject: ViewSubject, scope: ViewScope, variedOnly: boolean, regeneratedOnly: boolean) => {
const kept = rows.filter(row => inScope(row, scope, variedOnly, regeneratedOnly))
if (scope !== 'changes' || subject.mode !== 'comparison') return kept
const {shown} = changeContext(rows, subject)
return rows.filter(row => shown.has(row.id))
})
const keptOf = memo(
(summaryFilter: FilterState['summaryFilter'], query: string) => (row: Row) =>
(!summaryFilter || rowInSummary(row, summaryFilter)) && matches(row, query),
)
const visibleOf = memo((scoped: readonly Row[], kept: (row: Row) => boolean) => scoped.filter(kept))
const filterOf = memo(
(
query: string,
search: string,
scope: ViewScope,
summaryFilter: FilterState['summaryFilter'],
rows: readonly Row[],
kept: (row: Row) => boolean,
visibleRows: readonly Row[],
scopedRows: readonly Row[],
): FilterPayload => {
const ids = (list: readonly Row[]) => (list.length <= rendererLimits.filterIds ? list.map(row => row.id) : null)
// What is at full strength: what the summary filter and find keep of every item (the Changes scope lays out what
// it shows, `scope`, and draws some items between them besides), or of the noise, which is a filter too.
const narrowed = Boolean(query) || Boolean(summaryFilter) || scope === 'noise'
return {
query: search,
changesOnly: scope === 'changes',
ids: narrowed ? ids(scope === 'noise' ? visibleRows : rows.filter(kept)) : null,
scope: scope === 'changes' ? ids(scopedRows) : null,
}
},
)
// What the Changes scope leaves out, whatever the scope shown now: the scope switch and the view say so.
const hiddenRowsOf = memo((rows: readonly Row[], subject: ViewSubject, unchanged: boolean) => {
if (subject.mode !== 'comparison' || unchanged) return []
const {shown} = changeContext(rows, subject)
return rows.filter(row => !shown.has(row.id))
})
const hiddenOf = memo(scopeHidden)
const countsOf = memo((rows: readonly Row[], summary: readonly SummaryFigure[], hidden: ScopeHidden[]): ScopeCounts => {
const noise = rows.filter(row => variedWithinTolerance(row) || regenerated(row)).length
const left = hidden.reduce((total, item) => total + item.count, 0)
// Both over the same items, the union of the revisions, so All counts what Changes leaves out besides its changes.
const figures = summary.filter(figure => figure.type === 'count')
const counted = figures.length ? rows.filter(row => figures.some(figure => rowInSummary(row, {kinds: figure.kinds}))) : rows
return {changes: counted.filter(isScopeChange).length, all: counted.length, noise, hidden: left}
})
const resultOf = memo((visibleRows: readonly Row[], filter: FilterPayload, counts: ScopeCounts, hidden: ScopeHidden[]): RowFilter => ({
visibleRows,
filter,
counts,
hidden,
}))
return (rows, subject, state, summary) => {
const {variedOnly, regeneratedOnly, summaryFilter, search} = state
const query = search.trim().toLocaleLowerCase()
const unchanged = unchangedOf(rows)
const scope = state.scope === 'changes' && unchanged ? 'all' : state.scope
const scopedRows = scopedOf(rows, subject, scope, variedOnly, regeneratedOnly)
const kept = keptOf(summaryFilter, query)
const visibleRows = visibleOf(scopedRows, kept)
const filter = filterOf(query, search, scope, summaryFilter, rows, kept, visibleRows, scopedRows)
const hidden = hiddenOf(hiddenRowsOf(rows, subject, unchanged), summary)
return resultOf(visibleRows, filter, countsOf(rows, summary, hidden), hidden)
}
}, [query, search, scope, summaryFilter, rows, kept, visibleRows, scopedRows])
// What the Changes scope leaves out, whatever the scope shown now: the scope switch and the view say so.
const hiddenRows = useMemo(() => {
if (subject.mode !== 'comparison' || unchanged) return []
const {shown} = changeContext(rows, subject)
return rows.filter(row => !shown.has(row.id))
}, [rows, subject, unchanged])
const hidden = useMemo(() => scopeHidden(hiddenRows, summary), [hiddenRows, summary])
const counts = useMemo<ScopeCounts>(() => {
const noise = rows.filter(row => variedWithinTolerance(row) || regenerated(row)).length
const left = hidden.reduce((total, item) => total + item.count, 0)
// Both over the same items, the union of the revisions, so All counts what Changes leaves out besides its changes.
const figures = summary.filter(figure => figure.type === 'count')
const counted = figures.length ? rows.filter(row => figures.some(figure => rowInSummary(row, {kinds: figure.kinds}))) : rows
return {changes: counted.filter(isScopeChange).length, all: counted.length, noise, hidden: left}
}, [rows, summary, hidden])
return {visibleRows, filter, counts, hidden}
})
}

/** `createRowFilter` for a component's lifetime. */
export function useRowFilter(rows: readonly Row[], subject: ViewSubject, state: FilterState, summary: readonly SummaryFigure[]): RowFilter {
const [select] = useState(createRowFilter)
// Only a committed render's rows are what later renders compare with first.
useEffect(() => select.commit())
return select(rows, subject, state, summary)
}

/**
Expand Down
60 changes: 60 additions & 0 deletions packages/host/core/src/projection/interaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// What the viewer points at besides the selected row, as a reducer: the target pinned to the selected row, the hovered
// row and where each side's renderer shows items (anchors).
import type {AnchorRect} from '@githubnext/projections-renderer-sdk/protocol'
import type {Side} from '../modes.js'
import type {ProjectionTarget} from '../targets/target.js'

export type Anchors = Record<Side, {[id: string]: AnchorRect | null}>

/** The specific target chosen for a row: a property, or one the host selected. */
export type Pinned = {rowId: string; target: ProjectionTarget} | null

/** What the viewer points at besides the selected row: its pinned target, the hovered row and the renderers' anchors. */
export interface Interaction {
pinned: Pinned
hoveredId: string | null
anchors: Anchors
}

/** What happens to the interaction. */
export type InteractionEvent =
/** A row is selected, with the target chosen for it, if any. */
| {type: 'selected'; rowId: string | null; target?: ProjectionTarget | undefined}
| {type: 'hovered'; rowId: string | null}
/** A side's renderer reports where an item is, or that it doesn't show. */
| {type: 'anchored'; side: Side; rowId: string; rect: AnchorRect | null}
/**
* A side has a new frame (or none): its anchors belong to the old one's renderer. A frame that persists across a mode
* change keeps them, since its renderer only reports anchors that move.
*/
| {type: 'frameReplaced'; side: Side}
/** A new subject starts over. */
| {type: 'restarted'}

export const initialInteraction: Interaction = {pinned: null, hoveredId: null, anchors: {before: {}, after: {}}}

/** How the interaction changes; the same state when an event changes nothing. */
export function interaction(state: Interaction, event: InteractionEvent): Interaction {
switch (event.type) {
case 'selected': {
const pinned = event.rowId !== null && event.target ? {rowId: event.rowId, target: event.target} : null
return pinned === null && state.pinned === null ? state : {...state, pinned}
}
case 'hovered':
return state.hoveredId === event.rowId ? state : {...state, hoveredId: event.rowId}
case 'anchored': {
const side = state.anchors[event.side]
if (Object.hasOwn(side, event.rowId) && sameRect(side[event.rowId]!, event.rect)) return state
return {...state, anchors: {...state.anchors, [event.side]: {...side, [event.rowId]: event.rect}}}
}
case 'frameReplaced':
return Object.keys(state.anchors[event.side]).length ? {...state, anchors: {...state.anchors, [event.side]: {}}} : state
case 'restarted':
return state === initialInteraction ? state : initialInteraction
}
}

function sameRect(a: AnchorRect | null, b: AnchorRect | null): boolean {
if (a === null || b === null) return a === b
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height
}
73 changes: 73 additions & 0 deletions packages/host/core/src/projection/memo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Memoization without a framework that a render may abandon: a derived value keeps its identity while its inputs do, as
// React's memos keep it, so the store's snapshot changes only where something changed. Each memo compares first with
// the values last committed, then with the ones last computed; computing never replaces what was committed, so a render
// that is thrown away (React may render a state it never commits) costs the committed values nothing. `commit` keeps
// what the last computation used: React's adapter calls it after each committed render, a vanilla host after each read.

type Entry<A, R> = {readonly args: A; readonly result: R}

const sameArgs = (a: readonly unknown[], b: readonly unknown[]) =>
a.length === b.length && a.every((arg, index) => Object.is(arg, b[index]))

/** A set of memos and state committed together. */
export interface Memos {
/** `compute`, recomputed only when an argument differs (by `Object.is`) from the committed call's and the last one's. */
memo<A extends readonly unknown[], R>(compute: (...args: A) => R): (...args: A) => R
/**
* A value compared by its JSON: a copy taken when it changes, kept while it doesn't, so a value the host changes in
* place is still a change, and nothing it holds is shared. `undefined` stays `undefined`.
*/
byValue<T>(): (value: T) => T
/** A value carried from one computation to the next: `read` the committed one, `write` the next. */
cell<T>(initial: T): {read(): T; write(value: T): void}
/** Keeps what the last computation used, as what later ones compare with first. */
commit(): void
}

export function createMemos(): Memos {
const commits: (() => void)[] = []
const memo = <A extends readonly unknown[], R>(compute: (...args: A) => R) => {
let committed: Entry<A, R> | undefined
let current: Entry<A, R> | undefined
commits.push(() => {
committed = current
})
return (...args: A): R => {
if (committed && sameArgs(committed.args, args)) current = committed
else if (!current || !sameArgs(current.args, args)) current = {args, result: compute(...args)}
return current.result
}
}
return {
memo,
byValue: <T>() => {
const parsed = memo((key: string, missing: boolean) => (missing ? undefined : JSON.parse(key)) as T)
return (value: T) => parsed(JSON.stringify(value ?? null), value === undefined)
},
cell: <T>(initial: T): {read(): T; write(value: T): void} => {
let committed = initial
let next = initial
commits.push(() => {
committed = next
})
return {
read: () => committed,
write: (value: T) => {
next = value
},
}
},
commit: () => {
for (const commit of commits) commit()
},
}
}

/** A selector over memos: call it to compute, `commit` once what it computed is shown. */
export type Selector<A extends readonly unknown[], R> = ((...args: A) => R) & {commit(): void}

/** A selector from `build`, given its memos. */
export function selector<A extends readonly unknown[], R>(build: (memos: Memos) => (...args: A) => R): Selector<A, R> {
const memos = createMemos()
return Object.assign(build(memos), {commit: memos.commit})
}
Loading
Loading