Files
cutdex/packages/cutdex_timeline_ui/ARCHITECTURE.md
T
lingjhf 38ca180cf7
Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s
refactor(core): own editor UI and pin verified native releases
2026-10-12 03:20:29 +08:00

285 lines
17 KiB
Markdown

# Timeline UI Architecture
[简体中文](ARCHITECTURE.zh-CN.md)
## Authority boundary
`TimelineScrollbars` is a Camera adapter, not a `ScrollController` or document
owner. Bounds are cached by Layout version, opened storyline and geometry.
Refreshing them reads O(P + S) partition/stack aggregates plus Kernel's storyline
span query; it never enumerates bodies. Camera-only updates use O(1) scrollbar
work. A drag freezes its range and grab offset, and is invalidated by external
camera changes, root/geometry changes, controller replacement or viewport resize.
The dependency and authority flow is one-way:
```text
TimelineView -> TimelineViewController -> TimelineViewportEngine
-> LayoutVersion
-> TimelineVersion
```
- Kernel owns time, topology, edit validity, transactions, and history.
- Layout owns physical lanes, avoidance, drop resolution, and geometry.
- UI owns camera state, paint appearance, focus, and pointer lifecycle.
- UI never writes DTOs, derives lanes, or repairs a rejected edit.
`TimelineViewController` is a presentation controller, not a second timeline
state machine. Read-only views retain the supplied Layout root. Editable views
bind to `TimelineLayoutEngine` with a published definition component root, so
the engine retains the canonical projection across undo/redo. UI never keeps a
parallel projection history. All publication uses Layout's prepared edit APIs.
## Viewport camera lifecycle
The host session saves and restores each timeline's presentation state before
publishing that session to the view. `TimelineViewport` supplies the measured
dimensions and cached content bounds. `timeline_camera_layout.dart` resolves
an immutable camera result from those bounds and the previous camera; it has
no widget, persistence or notification side effects. Initialization, restored
views, resize, focus, pan and zoom share this calculation.
`configureViewport` marks changed bounds for preparation. During layout,
`prepareViewport` applies the resolved camera silently before the ruler,
scrollbars and content paint. Only a fresh, uninitialized empty view receives
the twenty-second default scale; restored and cached views retain their scale.
Zero-sized layouts defer initialization. Unchanged bounds skip preparation.
After layout, `reconcileViewport` publishes any pending change without moving
the already prepared camera again. Repeating preparation or reconciliation is
idempotent. The scheduled callback belongs to the captured controller and must
still match the mounted viewport; it cannot update a replacement controller.
Camera-only reconciliation does not invalidate inspected editing values or add
document history. Camera constraint calculation is constant work and has no ticker.
## Connected-clip selection drag
`TimelineInteractionRegion` adapts pointer, focus and Escape events. It records
the initial grab before Flutter's pan threshold, while `TimelineViewportDragAnchor`
resolves every update with the current camera. Input rounds to the nearest
runtime tick; frame/sample snapping is not implemented yet.
- Same-side avoidance uses `TimelineLayoutPreview.connectedSelection` and
`LayoutRigidConnectionMove.previewResolved`.
- Crossing sides uses `LayoutConnectedSideMove`, including time translation.
- Entering the Primary band uses `LayoutPrimaryDropEdit` with a version-bound
`LayoutPrimaryDropTarget`. Pointer front/back halves choose before/after
(midpoint chooses after); outside the span clamps to begin/end. No split/gap IDs
or time-insertion commands are available on this drag/drop path.
UI supplies movement roots ordered by start time (same-time roots within a
stack retain semantic order). Roots are inserted back-to-back without a
container or inter-root gaps, preserving the grabbed member's pointer offset.
Selected descendants are carried, not inserted a second time. One private
Kernel transaction publishes the whole group. Overlap coverage uses the frontmost
serial body, matching paint order, and still selects only a member boundary.
Same-time roots on different sides have no implied serial order and remain
rejected in UI; the Layout API accepts a caller-supplied explicit order.
- Each valid frame renders the prepared canonical Layout version, hiding the
active body's landing projection. Its themed pointer ghost and connection
line remain visible; the line uses the prepared connection and the ghost edge.
Primary insertion has no connection line and outlines each serial landing with
the shared transparent, rounded reservation border, including incoming connected
clips. Leaving Primary removes those incoming reservations. Occupancy still drives avoidance and
exact commit. No separate UI collision solver or lane state exists.
- A release with unchanged camera/coordinates commits that exact prepared root.
A changed release is re-resolved first. Invalid drops retain the original
placement, omit ghosts and create no history.
- Escape, pointer cancellation, focus loss, app deactivation, controller
replacement and disposal discard private previews. External coordinated
history invalidates a stale drag; an unmatched Kernel root fails closed.
- Call `synchronize()` after host-side edits to notify the view. Editable
`applyLayout`/`replaceLayout` accept only the engine's published root.
`LayoutMovementPlan` normalizes same-definition Primary, connected and mixed
selections into direct roots, independent accompanying roots, carried descendants
and a body-to-root map. `LayoutMovementBounds` supplies the shared zero-origin
constraint for both pointer projection and connected edit APIs. UI chooses the
explicit insertion order and rejects expanded components and ambiguous ordering;
it does not traverse connection ancestry or calculate a second movement limit.
Instance-context editing remains unsupported by this gesture path.
## Explicit selection commands
Explicit `cutSelectionAtPlayhead`/`deleteSelection` use version-bound
`LayoutBladeEdit.selectionAtTime`/`LayoutCascadeDeleteEdit.selection`. Selection
planning consumes Kernel local times, ownership intervals and anchor queries;
no lane, media mapping or ownership rule is implemented in UI. The controller
supplies fresh IDs for blade and publishes exactly one prepared result.
Blade adds right halves to selection; delete clears it. Unsupported mixed
selections (transition items, expanded components, foreign/stale handles or
instance contexts) reject as a whole. Non-intersecting selected clips are not
cut; endpoint-only cuts and empty selections create no history. A right half
requires an exact Primary anchor at the cut; the existing Kernel rule that the
left connection point remain inside the left half still applies. Invalid source,
transition or anchor constraints reject atomically, without repair or extension.
The controller's element-ID factory is never passed to the drag session.
## Keyframe Editing
Hosts enable `TimelineInteractionRegion.keyframes` alongside
`TimelineView.showKeyframes`. A marker click selects its merged channels and
seeks to its exact time. Horizontal dragging uses `LayoutKeyframeMove` for
frame snapping, clip limits, source mapping and collision validation. Vertical
pointer movement does not alter the key or clip. Values and interpolation are
preserved. Dragging clamps to the intersection of the moved channels' neighboring
key ranges, retaining at least one project frame of spacing. A range with no
available frame leaves the key in place. Direct edits outside these bounds are
rejected; dragging against a neighbor remains a valid preview.
The same private preview drives the marker and, through
`TimelineViewController.keyframePreviewVersion`, the host's video renderer.
The playhead remains fixed during dragging. The host samples temporary values
at that time and renders them through its interactive frame context, coalescing
pending renders to the latest values. Only published edits update the playback
plan; pointer updates must not replace the playback session.
Release publishes one history entry; Escape, pointer cancellation, focus loss
and external history discard it. Delete applies to selected key channels, not
the enclosing clip. Held or repeated source visits remain selectable for seeking
but reject independent moves rather than changing other occurrences implicitly.
## Edge Trimming
`TimelineInteractionRegion` passes the theme's inner edge hit band to `beginDrag`.
The closest edge wins on narrow clips (midpoint: trailing). Content, gaps and
collapsed containers expose grips; instance-context/expanded components and
transition items do not. A multi-selection edge edits only the hit clip.
Move and trim are mutually exclusive private sessions under the same controller
lifecycle. `isDragging` covers either; `isTrimming` and `trimEdge` distinguish trim.
Each pointer/Camera update resolves a duration from the immutable grab anchor and
base duration, at runtime-tick precision, then calls `LayoutIntervalEdit.previewTrim`.
This pure-Dart entry point constrains source availability and chooses the Kernel
leading/trailing or container-view trim. Serial trim ripples the suffix; connected
left trim keeps its right edge. When its start passes the original anchor, Layout
resolves a valid storyline anchor and reattaches before shortening in the same
private transaction. Kernel validates source, retime, transition and connection
constraints. Invalid outgoing anchors reject atomically; children are not deleted.
Layout handles changed intervals and avoidance. The painter displays only this
canonical preview and its connection lines, without a move ghost or projection.
Unchanged release commits exactly that prepared version. Invalid/no-motion release
creates no history. Camera navigation, edge scrolling, cancellation, focus loss
and external root invalidation share the move lifecycle. Frame/sample snapping,
roll/slip/slide gestures and transition resizing are not part of this basic trim.
Grip width/hit band and outline colors come from `TimelineThemeData`; put the
extension above both the input region and painter when customizing edge behavior.
## Primary-to-connected drag
`beginDrag` / `updateDrag` / `finishDrag` allow Primary reordering with connected
descendants, but ordinary dragging into or out of Primary requires each moved
root to have no outgoing connections. Container contents do not count as outer
connections. Both transfer commands enforce this using Kernel's direct anchor
index; UI cannot bypass the precondition. `LayoutPrimaryDetachEdit`
rejects the ownership conversion, not pointer movement: owners with connections
use the same free ghost and Primary reservation path as gaps. A valid Primary
drop moves that reservation; an off-axis release does not publish.
For an eligible unconnected source, `LayoutPrimaryDetachEdit`
composes Kernel link and placement primitives into one unpublished result. A→B→C
becomes A→C when B is detached; its old span is not replaced by a gap. Anchoring uses the
post-ripple rope, including any adjacent transition adjustment. Connection IDs
come from the host's `createConnectionId` factory and are reused during a gesture.
The detached body receives pointer priority; passively translated suffix bodies
do not. Their canonical time index is updated before collision discovery. The same
prepared Kernel/Layout bundle supplies preview and drop. Returning to Primary
rebuilds the boundary reorder from the original version while carrying forward
the generated/extended gap in the same transaction. The source's own boundaries
are no-ops only when there is no pending gap edit. Cancel and invalid drop
leave history unchanged. Tail dragging clamps the accepted start to the current
tail T. Only when the clip's start reaches T does the same terminal gap extend
by the moved clip's duration. Moving within the gap, even with the clip's end
beyond T, does not extend it.
Layout retains the last raw/accepted start and gap extent in its preview; later
pointer deltas advance from that accepted start. Repeated frames cannot consume
the newly extended tail. Gap end is monotonic during connected dragging, including
backward movement. Existing terminal gaps retain their IDs across gestures.
Otherwise IDs come from the host element-ID factory. A sole Primary clip can
use T=0. For connected multi-selections, the rightmost movement root's start
triggers and clamps at T; every root receives the same translation. The gap
extends by max(root end) - max(root start), covering the group's remaining
time envelope without waiting for its leftmost root. Committing publishes the gap and
connections together; cancel publishes neither. Moving a connected clip away
does not delete its committed gap. Other missing-anchor cases remain rejected. Pointer
ghosts and connection lines remain visible; connected landing bodies remain hidden.
Both membership directions share canonical projection and passive-ripple targeting.
Primary drop invokes only Kernel `splice` or `unlink` by index, never blade. Explicit
arbitrary-time insertion remains separate. Display-only Primary ghosts never enter
the Layout solver; pointer offsets remain independent of hidden snapped landings.
## Rendering contract
### Drag edge scrolling
One vsync ticker runs only for an active single-pointer clip drag inside an edge
zone. Defaults: 48 logical pixels and maximum 600 logical pixels/second per axis;
zone width is capped at half the viewport dimension. For signed edge penetration
`p ∈ [-1,1]`, `v = vmax * p * |p|` and each frame applies
`ΔcameraPixels = v * min(Δseconds, 0.05)`. Corners combine axes. Zero extent/speed
disables scrolling. Idle, ruler, marquee and hand navigation never start it;
suspended frames do not produce catch-up jumps.
Each tick calls existing controller `panBy` once, re-resolving the retained grab
and pointer with the current Camera. No history or second placement implementation
is added. Ghosts and connection lines use the same preview; release commits that
latest prepared root. Cancel retains the scrolled Camera but not the edit. Camera
bounds remain those of manual pan; scrolling does not bypass semantic validation.
Leaving the edge/view, release, cancellation, focus/lifecycle loss, controller
replacement, external drag cancellation and a second touch stop the ticker.
Viewport resize cancels the old-coordinate gesture after layout; dispose releases
the ticker. Input work per frame is O(1), plus existing affected-region preview
and resident paint costs; no traversal of total N is introduced.
The input region uses one ScaleGestureRecognizer for clip drag, touch pinch and
native trackpad navigation, with explicit press-time routing for ruler seek and
hand navigation. Pointer cancellation/focus loss discard edit state. All combined
pan/zoom transforms call `controller.navigate` and then the existing Layout
Camera APIs; the time under the old focal point moves to the new focal point.
`TimelineRuler` paints a bounded number of adaptive elapsed-time ticks proportional
to viewport width. It never walks Kernel elements. Its playhead is presentation
state, has no undo history, and does not implement playback. The ruler is fixed
vertically while the clip surface can pan vertically.
The painter requests one transient `TimelineViewportFrame` during paint and
consumes it immediately. The frame references a reusable buffer and must not be
retained across another projection. One canvas surface paints all resident
items; element count does not affect the widget-tree size.
For `V` resident items:
```text
widget build = O(1)
camera update without active drag = O(1)
resident cache hit = O(1) projection + O(V) paint
resident cache miss = Layout viewport query + O(V) projection/paint
hit test = O(V), reverse paint order
active drag update = Layout target/semantic preview cost + viewport paint
```
Media thumbnails, waveforms, text, selections, and drag overlays must extend
this bulk rendering pipeline or use bounded viewport overlays. They must not
introduce one persistent widget per project element.
All painters and overlays consume `TimelineThemeData`. The widget layer
resolves the Flutter theme once per build and passes immutable visual tokens to
the painter; the resident-item loop performs no inherited-theme lookup.
Opaque Primary payload classification reuses the host's exact
`LayoutMediaClassifier`. Connected audio/visual classification is read from
Layout's solved placement class;
structural gap/container state is read from the exact Kernel version. UI never
parses `PayloadRef` or recursively inspects a container.
## Publication contract
- `applyLayout(result)` is for an adjacent, atomically published Layout update.
The viewport cache survives only when Layout proves it is geometry-neutral.
- `replaceLayout(version)` explicitly invalidates the cache for opening another
scene, non-adjacent history movement, or a global rebuild.
- Camera changes re-resolve an active drag, otherwise only notify painting.
Neither path creates Kernel history.
- A compound clip opens by supplying its independent Storyline/Layout scene to
the controller; it is not expanded inside the parent timeline surface.