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
11 changes: 11 additions & 0 deletions docs/guides/host-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,17 @@ provides the headless pair picker. It returns:
`presentation` defaults.
- Actions: `setBefore`, `setAfter`, `swap`, and `retry`.

`useComparisonSession(options)` keeps what the person chooses while they move
between pairs: the mode, the swipe divider, highlighting, the scope, find, the
connector and loop. A pair picker's view remounts for each new comparison, so
call it above the view, with `presentation: pair.presentation`, and spread its
result (controlled values with their handlers) into `useProjection` or a view.
Each setting starts from its `initial…` option, else the definition's
`presentation`, else the shared default: the renderer's default mode, the
divider centred, animated highlighting, **the Changes scope**
(`initialChangesOnly` changes it), no find, no connector and loop on
(`comparisonSessionDefaults`). Each is also controllable, with its `on…Change`.

Comparisons run in the browser using the projection's comparator, with failures
surfaced explicitly. Companion helpers (`subjectRows`, `rowItems`,
`describeChange`, `rowStatusCounts`) feed table, text, and detail views.
Expand Down
144 changes: 144 additions & 0 deletions packages/host/core/src/comparison-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import {useRef, useState} from 'react'
import type {Highlighting, PresentationDefaults} from './projection/types.js'
import type {ComparisonMode} from './modes.js'
import {offeredModes} from './view-model.js'
import type {ProjectionFeatures} from './view-model.js'

/**
* The options of `useComparisonSession`: the definition's defaults, the features (for the modes offered), and each
* setting, controlled (with its `on…Change`) or left to the session (optionally seeded with `initial…`).
*/
export interface ComparisonSessionOptions {
/** The definition's defaults (`ComparisonPair.presentation`), applied as initial values. */
presentation?: PresentationDefaults | undefined
/** Only `modes` is read: an initial mode the features don't offer gives way to the first they offer. */
features?: Pick<ProjectionFeatures, 'modes'> | undefined
mode?: ComparisonMode | undefined
initialMode?: ComparisonMode | undefined
onModeChange?: ((mode: ComparisonMode) => void) | undefined
swipePosition?: number | undefined
onSwipePositionChange?: ((position: number) => void) | undefined
highlighting?: Highlighting | undefined
onHighlightingChange?: ((highlighting: Highlighting) => void) | undefined
changesOnly?: boolean | undefined
/** The scope a session starts in: the definition's `presentation.changesOnly`, else Changes (`true`). */
initialChangesOnly?: boolean | undefined
onChangesOnlyChange?: ((changesOnly: boolean) => void) | undefined
search?: string | undefined
onSearchChange?: ((search: string) => void) | undefined
connector?: boolean | undefined
initialConnector?: boolean | undefined
onConnectorChange?: ((connector: boolean) => void) | undefined
loop?: boolean | undefined
initialLoop?: boolean | undefined
onLoopChange?: ((loop: boolean) => void) | undefined
}

/**
* The settings a session keeps across pairs, as controlled values with their handlers, ready for `useProjection` or a
* view. `mode` is absent until one is chosen, so the renderer's default applies.
*/
export interface ComparisonSessionSettings {
mode?: ComparisonMode
onModeChange: (mode: ComparisonMode) => void
swipePosition: number
onSwipePositionChange: (position: number) => void
highlighting: Highlighting
onHighlightingChange: (highlighting: Highlighting) => void
changesOnly: boolean
onChangesOnlyChange: (changesOnly: boolean) => void
search: string
onSearchChange: (search: string) => void
connector: boolean
onConnectorChange: (connector: boolean) => void
loop: boolean
onLoopChange: (loop: boolean) => void
}

/** The settings a session keeps, and the handler each reports its changes to. */
const handlerOf = {
mode: 'onModeChange',
swipePosition: 'onSwipePositionChange',
highlighting: 'onHighlightingChange',
changesOnly: 'onChangesOnlyChange',
search: 'onSearchChange',
connector: 'onConnectorChange',
loop: 'onLoopChange',
} as const satisfies Partial<Record<keyof ComparisonSessionOptions, keyof ComparisonSessionOptions>>
type Controlled = keyof typeof handlerOf

/**
* Where a session's settings start: each `initial…` option, else the definition's `presentation`, else the shared
* default (no mode, so the renderer's default applies; the divider centred; animated highlighting; Changes; no find,
* no connector; loop on). An initial mode the features don't offer gives way to the first they offer.
*/
export function comparisonSessionDefaults(
options: Pick<
ComparisonSessionOptions,
'presentation' | 'features' | 'initialMode' | 'initialChangesOnly' | 'initialConnector' | 'initialLoop'
>,
): Omit<ComparisonSessionSettings, `on${string}`> {
const {presentation, features} = options
const initial = options.initialMode ?? presentation?.mode
const modes = offeredModes(features)
const mode = initial && modes.includes(initial) ? initial : features?.modes ? modes[0] : undefined
return {
...(mode ? {mode} : {}),
swipePosition: 0.5,
highlighting: presentation?.highlighting ?? 'animated',
changesOnly: options.initialChangesOnly ?? presentation?.changesOnly ?? true,
search: '',
connector: options.initialConnector ?? false,
loop: options.initialLoop ?? true,
}
}

/**
* The settings a person chooses while comparing (the mode, the swipe divider, highlighting, the scope, find, the
* connector and loop), kept while they move between pairs: a pair picker's view remounts for each new comparison, so
* the settings live here, above it. They start from `comparisonSessionDefaults`; each is controllable.
*/
export function useComparisonSession(options: ComparisonSessionOptions): ComparisonSessionSettings {
const latest = useRef(options)
latest.current = options
const [defaults] = useState(() => comparisonSessionDefaults(options))
const [mode, setMode] = useState<ComparisonMode | undefined>(defaults.mode)
const [swipePosition, setSwipePosition] = useState(defaults.swipePosition)
const [highlighting, setHighlighting] = useState<Highlighting>(defaults.highlighting)
const [changesOnly, setChangesOnly] = useState(defaults.changesOnly)
const [search, setSearch] = useState(defaults.search)
const [connector, setConnector] = useState(defaults.connector)
const [loop, setLoop] = useState(defaults.loop)
// One handler per setting for the session's life, so views don't see new callbacks on every render. A setting the
// embedder controls keeps its value: the change is only requested, so a refused one isn't kept for later.
const [handlers] = useState(() => {
const changed =
<K extends Controlled>(key: K, set: (value: NonNullable<ComparisonSessionOptions[K]>) => void) =>
(value: NonNullable<ComparisonSessionOptions[K]>) => {
const current = latest.current
const notify = current[handlerOf[key]] as ((value: NonNullable<ComparisonSessionOptions[K]>) => void) | undefined
if (current[key] === undefined) set(value)
notify?.(value)
}
return {
onModeChange: changed('mode', setMode),
onSwipePositionChange: changed('swipePosition', setSwipePosition),
onHighlightingChange: changed('highlighting', setHighlighting),
onChangesOnlyChange: changed('changesOnly', setChangesOnly),
onSearchChange: changed('search', setSearch),
onConnectorChange: changed('connector', setConnector),
onLoopChange: changed('loop', setLoop),
}
})
const shownMode = options.mode ?? mode
return {
...(shownMode ? {mode: shownMode} : {}),
swipePosition: options.swipePosition ?? swipePosition,
highlighting: options.highlighting ?? highlighting,
changesOnly: options.changesOnly ?? changesOnly,
search: options.search ?? search,
connector: options.connector ?? connector,
loop: options.loop ?? loop,
...handlers,
}
}
2 changes: 2 additions & 0 deletions packages/host/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ export type {ProjectionStageProps} from './stage.js'
export type {PaneArrangement} from './stage/arrangement.js'
export type {PaneEdge, PaneLabels} from './stage/layout.js'
export {useComparisonPair} from './pair.js'
export {comparisonSessionDefaults, useComparisonSession} from './comparison-session.js'
export type {ComparisonSessionOptions, ComparisonSessionSettings} from './comparison-session.js'
export type {ComparisonPair, ComparisonPairOptions, ExtractionChoice, PairOutcome} from './pair.js'
export {
clampMode,
Expand Down
57 changes: 8 additions & 49 deletions packages/host/core/src/ui/explorer.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import {useCallback, useRef, useState} from 'react'
import {CircleAlert} from 'lucide-react'
import {ComparisonError} from '../compare.js'
import {useComparisonPair} from '../pair.js'
import type {ComparisonPairOptions} from '../pair.js'
import {LoadingStatus} from '../loading.js'
import {ProjectionView} from './view.js'
import type {ProjectionViewProps} from './view/props.js'
import type {ComparisonMode} from '../modes.js'
import type {Highlighting} from '../projection.js'
import {useComparisonSession} from '../comparison-session.js'
import {Alert, AlertDescription, AlertTitle} from './components/alert.js'
import {Button} from './components/button.js'
import {ScopedRoot} from './components/scoped-root.js'
Expand Down Expand Up @@ -72,7 +70,10 @@ export interface ComparisonExplorerProps
| 'utility'
| 'fill'
| 'className'
> {}
> {
/** The scope the explorer starts in: the definition's `presentation.changesOnly`, else Changes (`useComparisonSession`). */
initialChangesOnly?: boolean
}

/**
* The default pair picker: lets a user choose any two extractions from a set
Expand All @@ -83,41 +84,9 @@ export interface ComparisonExplorerProps
*/
export function ComparisonExplorer(props: ComparisonExplorerProps) {
const pair = useComparisonPair(props)
const callbacks = useRef(props)
callbacks.current = props
const colorMode = useColorMode(props.colorMode)
// The view unmounts while a new pair is computed, so the explorer keeps the uncontrolled mode and divider.
// Undefined until chosen: the renderer's default mode applies.
const [mode, setMode] = useState<ComparisonMode | undefined>(props.initialMode ?? pair.presentation?.mode)
const [swipe, setSwipe] = useState(0.5)
const [highlighting, setHighlighting] = useState<Highlighting>(pair.presentation?.highlighting ?? 'animated')
const [changesOnly, setChangesOnly] = useState(pair.presentation?.changesOnly ?? true)
const [search, setSearch] = useState('')
const settings = {
highlighting: props.highlighting ?? highlighting,
onHighlightingChange: (value: Highlighting) => {
setHighlighting(value)
callbacks.current.onHighlightingChange?.(value)
},
changesOnly: props.changesOnly ?? changesOnly,
onChangesOnlyChange: (value: boolean) => {
setChangesOnly(value)
callbacks.current.onChangesOnlyChange?.(value)
},
search: props.search ?? search,
onSearchChange: (value: string) => {
setSearch(value)
callbacks.current.onSearchChange?.(value)
},
}
const changeMode = useCallback((value: ComparisonMode) => {
setMode(value)
callbacks.current.onModeChange?.(value)
}, [])
const changeSwipe = useCallback((value: number) => {
setSwipe(value)
callbacks.current.onSwipePositionChange?.(value)
}, [])
// The view remounts while a new pair is computed, so the session above it keeps the settings across pairs.
const session = useComparisonSession({...props, presentation: pair.presentation})
const {after, outcome, subject, document, resolution} = pair
const fill = props.fill !== false
if (!after || !document)
Expand Down Expand Up @@ -202,17 +171,11 @@ export function ComparisonExplorer(props: ComparisonExplorerProps) {
{...(props.progress !== undefined ? {progress: props.progress} : {})}
{...(props.playing !== undefined ? {playing: props.playing} : {})}
{...(props.onPlayingChange ? {onPlayingChange: props.onPlayingChange} : {})}
{...(props.loop !== undefined ? {loop: props.loop} : {})}
{...(props.initialLoop !== undefined ? {initialLoop: props.initialLoop} : {})}
{...(props.onLoopChange ? {onLoopChange: props.onLoopChange} : {})}
{...(props.initialHolds ? {initialHolds: props.initialHolds} : {})}
{...(props.connector !== undefined ? {connector: props.connector} : {})}
{...(props.initialConnector !== undefined ? {initialConnector: props.initialConnector} : {})}
{...(props.onConnectorChange ? {onConnectorChange: props.onConnectorChange} : {})}
{...session}
renderers={pair.renderers}
rendererDocuments={pair.rendererDocuments}
presentation={pair.presentation}
{...settings}
toolbarStart={picker}
fill={fill}
{...(comparator ? {comparator} : {})}
Expand All @@ -229,10 +192,6 @@ export function ComparisonExplorer(props: ComparisonExplorerProps) {
{...(props.details ? {details: props.details} : {})}
{...(props.evidenceLink ? {evidenceLink: props.evidenceLink} : {})}
{...(props.controllerRef ? {controllerRef: props.controllerRef} : {})}
{...((props.mode ?? mode) ? {mode: (props.mode ?? mode)!} : {})}
onModeChange={changeMode}
swipePosition={props.swipePosition ?? swipe}
onSwipePositionChange={changeSwipe}
{...(props.initialView ? {initialView: props.initialView} : {})}
{...(props.playbackInViews ? {playbackInViews: props.playbackInViews} : {})}
/>
Expand Down
31 changes: 31 additions & 0 deletions packages/host/core/test/comparison-session.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {comparisonSessionDefaults} from '../dist/index.js'

test('a session starts in Changes with the shared defaults, and no mode until one is chosen', () => {
assert.deepEqual(comparisonSessionDefaults({}), {
swipePosition: 0.5,
highlighting: 'animated',
changesOnly: true,
search: '',
connector: false,
loop: true,
})
})

test('the definition’s presentation seeds a session, and a host’s initial values win over it', () => {
const presentation = {mode: 'side-by-side', highlighting: 'on', changesOnly: false}
const seeded = comparisonSessionDefaults({presentation})
assert.equal(seeded.mode, 'side-by-side')
assert.equal(seeded.highlighting, 'on')
assert.equal(seeded.changesOnly, false)
const chosen = comparisonSessionDefaults({presentation, initialMode: 'swipe', initialChangesOnly: true, initialLoop: false})
assert.equal(chosen.mode, 'swipe')
assert.equal(chosen.changesOnly, true)
assert.equal(chosen.loop, false)
})

test('an initial mode the features don’t offer gives way to the first they offer', () => {
assert.equal(comparisonSessionDefaults({initialMode: 'swipe', features: {modes: ['animated', 'side-by-side']}}).mode, 'side-by-side')
assert.equal(comparisonSessionDefaults({features: {modes: ['animated']}}).mode, 'animated')
})
Loading
Loading