1// Scrolling: a scroll moving its one child under a clip, and the2// virtualized list, which makes only the rows in view and around them,3// keeping its place on a row as it scrolls.45import std::string;6import std::vector;7import std::option;8import std::math;9import std::map;10import pkg::alloy::window;11import pkg::alloy::gpu;12import pkg::alloy::draw;1314import ui;15import store;16import tree;17import layout;1819const BAR: f32 = 5.0; // the bar's width20exp const BAR_REACH: f32 = 12.0; // how near the edge a press takes the bar21const MIN_THUMB: f32 = 24.0;2223// The part of a bar the thumb covers.24exp type Thumb = struct {25 exp start: f32,26 exp length: f32,27};2829// The thumb along a bar of the length, for the view `offset` into30// `content`.31exp fn thumb(offset: f32, content: f32, length: f32) -> Thumb {32 if (content <= length || length <= 0.0) {33 return Thumb { .start = 0.0, .length = length };34 }35 const size = clamp(length * length / content, min(MIN_THUMB, length), length);36 const start = (length - size) * clamp(offset / (content - length), 0.0, 1.0);37 return Thumb { .start = start, .length = size };38}3940// The offset that puts the thumb's start at `along` on the bar.41exp fn offset_at(along: f32, t: &Thumb, content: f32, length: f32) -> f32 {42 return along / max(length - t.length, 1.0) * (content - length);43}4445// The bar, over the content, along the end edge (the right, or the left46// right to left) or the bottom, a horizontal one's thumb from the start.47exp fn paint_bar(look: &Look, paint: &var Paint, offset: f32, content: f32, axis: Axis) {48 const size = look.size;49 const length = axis.main(size.width, size.height);50 if (content <= length + 0.5) {51 return;52 }53 const t = thumb(offset, content, length);54 var color = look.theme.muted;55 color.a = if (look.hovered || look.pressed) 0.75 else 0.45;56 const at = axis.point(t.start, axis.cross(size.width, size.height) - BAR - 2.0);57 const extent = axis.extent(t.length, BAR);58 paint.rounded_rect(59 Rect::at(look.from_start(at.x, extent.width), at.y, extent.width, extent.height),60 Radii::all(BAR / 2.0),61 Fill::Color(color)62 );63}6465// A point in the element's coordinates as measured from its start edge:66// x from the right right to left.67fn from_start(p: Point, width: f32, rtl: bool) -> Point {68 return if (rtl) Point { .x = width - p.x, .y = p.y } else p;69}7071/* --- Scroll --- */7273fn axis(self s: &Scroll) -> Axis => if (s.horizontal) Axis::Horizontal else Axis::Vertical;7475pub fn layout(self s: &var Scroll, arrange: &var Arrange, limits: Limits) -> Extent {76 const axis = s.axis();77 var child = Extent::zero();78 if (arrange.count() > 0) {79 child = arrange.lay_out(0, axis.limits(80 0.0,81 UNBOUNDED,82 axis.cross(limits.min_width, limits.min_height),83 axis.cross(limits.max_width, limits.max_height)84 ));85 }86 const size = limits.constrain(child);87 s.content = axis.main(child.width, child.height);88 s.length = axis.main(size.width, size.height);89 s.offset = clamp(s.offset, 0.0, max(s.content - s.length, 0.0));90 if (arrange.count() > 0) {91 arrange.place(0, axis.point(-s.offset, 0.0));92 }93 return size;94}9596exp fn paint(self s: &Scroll, look: &Look, paint: &var Paint) {}9798pub fn overlay(self s: &Scroll, look: &Look, paint: &var Paint) {99 paint_bar(&look, &var paint, s.offset, s.content, s.axis());100}101102pub fn event(self s: &var Scroll, ui: &var Ui, input: &Input) -> bool {103 const axis = s.axis();104 const size = ui.handling_size();105 // offsets and the bar from the start edge: the right right to left106 const rtl = ui.handling_rtl();107 match (input) {108 ::Scroll |delta| {109 // a wheel turned without Shift scrolls a horizontal scroll too;110 // turned sideways it moves what shows with the fingers, so111 // toward the start right to left112 const sideways = if (rtl) -delta.x else delta.x;113 const d = if (s.horizontal && delta.x != 0.0) sideways else delta.y;114 return s.scroll_to(&var ui, s.offset + d);115 }116 ::Press |pressed| {117 const p = from_start(pressed, size.width, rtl);118 const along = axis.main(p.x, p.y);119 const side = axis.cross(p.x, p.y);120 if (s.content <= s.length || side < axis.cross(size.width, size.height) - BAR_REACH) {121 return false;122 }123 const t = thumb(s.offset, s.content, s.length);124 if (along < t.start || along > t.start + t.length) {125 // the track: the thumb centered on the press126 s.scroll_to(&var ui, offset_at(along - t.length / 2.0, &t, s.content, s.length));127 }128 s.grab = ::Some(along - thumb(s.offset, s.content, s.length).start);129 ui.refresh(Change::Paint);130 return true;131 }132 ::Moved |moved| {133 const grab = if (s.grab is ::Some |g|) g else {134 return false;135 };136 const p = from_start(moved, size.width, rtl);137 const t = thumb(s.offset, s.content, s.length);138 s.scroll_to(&var ui, offset_at(axis.main(p.x, p.y) - grab, &t, s.content, s.length));139 return true;140 }141 ::Release {142 const grabbed = s.grab is ::Some;143 s.grab = ::None;144 return grabbed;145 }146 else {147 return false;148 }149 }150}151152// Moves the content to the offset, within its ends; whether it moved.153fn scroll_to(self s: &var Scroll, ui: &var Ui, offset: f32) -> bool {154 const next = clamp(offset, 0.0, max(s.content - s.length, 0.0));155 if (next == s.offset) {156 return false;157 }158 s.offset = next;159 ui.refresh(Change::Layout);160 return true;161}162163exp fn renew(self s: &var Scroll, next: Scroll) -> Change {164 s.horizontal = next.horizontal;165 s.sizing = next.sizing;166 return Change::Layout;167}168169pub fn children(self s: &Scroll) -> &[Element] => &s.children;170pub fn sizing(self s: &Scroll) -> Sizing => s.sizing;171pub fn interactive(self s: &Scroll) -> bool => true;172pub fn clips(self s: &Scroll) -> bool => true;173pub fn semantics(self s: &Scroll) -> Semantics => Semantics { .role = Role::ScrollView };174175// Scrolls the scrolls holding the node so it shows, as when the176// keyboard focuses it.177exp fn reveal(self ui: &var Ui, index: u32) {178 for (ui.reveal_offsets(index).view()) |&t| {179 ui.set_scroll_offset(t.scroll, t.offset);180 }181}182183// A scroll and the offset it takes.184pub type ScrollTarget = struct {185 pub scroll: u32,186 pub offset: f32,187};188189// The offsets the scrolls holding the node take so it shows, innermost190// first, those it already shows in left out.191pub fn reveal_offsets(self ui: &Ui, index: u32) -> Vector<ScrollTarget> {192 var targets = Vector<ScrollTarget>::empty();193 const size = ui.node(index).size;194 var at = ui.node(index).position; // the node's top left in the coordinates of `above`195 var above = ui.node(index).parent;196 while (above is ::Some |k|) {197 if (ui.node(k).widget is ::Some |&widget| && widget is Scroll |&s|) {198 const axis = s.axis();199 // a horizontal scroll's offset from its start, the right right200 // to left201 const flipped = s.horizontal && ui.node(k).direction is ::RightToLeft;202 const near = if (flipped) ui.node(k).size.width - at.x - size.width else at.x;203 const start = axis.main(near, at.y) + s.offset;204 const length = axis.main(size.width, size.height);205 var offset = s.offset;206 if (start < offset) {207 offset = start;208 } else if (start + length > offset + s.length) {209 offset = start + length - s.length;210 }211 offset = clamp(offset, 0.0, max(s.content - s.length, 0.0));212 if (offset != s.offset) {213 const moved = if (flipped) offset - s.offset else s.offset - offset;214 const shift = axis.point(moved, 0.0);215 at = Point { .x = at.x + shift.x, .y = at.y + shift.y };216 targets.push(ScrollTarget { .scroll = k, .offset = offset });217 }218 }219 const position = ui.node(k).position;220 at = Point { .x = at.x + position.x, .y = at.y + position.y };221 above = ui.node(k).parent;222 }223 return move targets;224}225226// A scroll's offset.227exp fn scroll_offset(self ui: &Ui, index: u32) -> f32 {228 if (ui.node(index).widget is ::Some |&widget| && widget is Scroll |&s|) {229 return s.offset;230 }231 return 0.0;232}233234// Moves a scroll's content to the offset, laying it out again.235pub fn set_scroll_offset(self ui: &var Ui, index: u32, offset: f32) {236 if (ui.node_var(index).widget is ::Some |&var widget| && widget is Scroll |&var s|) {237 if (s.offset != offset) {238 s.offset = offset;239 ui.mark_layout(index);240 }241 }242}243244/* --- The virtualized list --- */245246// The rows from `first` up to `end`, which the list makes.247pub type RowSpan = struct {248 pub first: u64,249 pub end: u64,250};251252pub type BuiltRow = struct {253 pub index: u64,254 pub owner: u32,255 pub node: u32,256};257258pub type ListView : Widget = struct {259 pub options: ListOptions,260 pub count: u64,261 pub built: Vector<BuiltRow>, // by index, as its children are262 pub heights: Map<u64, f32>, // the rows measured263 pub measured: f32, // their heights' sum264 pub anchor: u64, // the row the view keeps its place on265 above: f32, // the heights measured of the rows before the anchor266 above_count: u64, // how many they are267 pub offset: f32, // the view's top below the anchor's top268 pub width: f32,269 pub height: f32,270 pub wanted: Option<Signal<RowSpan>>,271 pub grab: Option<f32>, // where the bar was grabbed, while dragged272};273274pub fn ListView::create(options: ListOptions) -> ListView => ListView {275 .options = options,276 .count = 0,277 .built = Vector<BuiltRow>::empty(),278 .heights = Map<u64, f32>::empty(),279 .measured = 0.0,280 .anchor = 0,281 .above = 0.0,282 .above_count = 0,283 .offset = 0.0,284 .width = 0.0,285 .height = 0.0,286 .wanted = ::None,287 .grab = ::None288};289290// A row's height: measured, else the average of those measured, else291// the estimate.292fn row_height(self l: &ListView, index: u64) -> f32 {293 if (l.options.fixed) {294 return l.options.estimate;295 }296 if (l.heights.try_get(&index) is ::Some |&h|) {297 return h;298 }299 const n = l.heights.length();300 return if (n > 0) l.measured / n to f32 else l.options.estimate;301}302303fn step(self l: &ListView, index: u64) -> f32 => l.row_height(index) + l.options.gap;304305// Moves the anchor up a row, the offset kept within the view's top.306fn anchor_up(self l: &var ListView) {307 l.anchor -= 1;308 if (l.heights.try_get(&l.anchor) is ::Some |&h|) {309 l.above -= h;310 l.above_count -= 1;311 }312 l.offset += l.step(l.anchor);313}314315fn anchor_down(self l: &var ListView) {316 l.offset -= l.step(l.anchor);317 if (l.heights.try_get(&l.anchor) is ::Some |&h|) {318 l.above += h;319 l.above_count += 1;320 }321 l.anchor += 1;322}323324// Puts the anchor at the row, summing the heights above it again.325fn set_anchor(self l: &var ListView, row: u64) {326 l.anchor = row;327 l.above = 0.0;328 l.above_count = 0;329 for (l.heights.entries()) |&e| {330 if (e.key < row) {331 l.above += e.value;332 l.above_count += 1;333 }334 }335}336337// Moves the anchor to the row at the view's top, the offset within it.338fn normalize(self l: &var ListView) {339 if (l.count == 0) {340 l.set_anchor(0);341 l.offset = 0.0;342 return;343 }344 if (l.anchor >= l.count) {345 l.set_anchor(l.count - 1);346 }347 while (l.offset < 0.0 && l.anchor > 0) {348 l.anchor_up();349 }350 if (l.offset < 0.0) {351 l.offset = 0.0;352 }353 while (l.anchor + 1 < l.count && l.offset >= l.step(l.anchor)) {354 l.anchor_down();355 }356 // past the end: the last row's bottom at the view's357 var below: f32 = -l.offset;358 var k = l.anchor;359 while (k < l.count && below < l.height) {360 below += l.step(k);361 k += 1;362 }363 if (k == l.count && below - l.options.gap < l.height) {364 l.offset -= l.height - (below - l.options.gap);365 while (l.offset < 0.0 && l.anchor > 0) {366 l.anchor_up();367 }368 if (l.offset < 0.0) {369 l.offset = 0.0;370 }371 }372}373374// How far a view is scrolled into its content, and the content's length.375pub type Scrolled = struct {376 pub offset: f32,377 pub content: f32,378};379380// How far the view's top is from the first row's, estimated, and the381// whole list's length.382pub fn extent(self l: &ListView) -> Scrolled {383 if (l.options.fixed) {384 const step = l.options.estimate + l.options.gap;385 return Scrolled {386 .offset = l.anchor to f32 * step + l.offset,387 .content = l.count to f32 * step388 };389 }390 const n = l.heights.length();391 const average = (if (n > 0) l.measured / n to f32 else l.options.estimate) + l.options.gap;392 const before = l.above393 + l.above_count to f32 * l.options.gap394 + (l.anchor - l.above_count) to f32 * average;395 const total = l.measured + n to f32 * l.options.gap + (l.count - n) to f32 * average;396 return Scrolled { .offset = before + l.offset, .content = total };397}398399pub fn layout(self l: &var ListView, arrange: &var Arrange, limits: Limits) -> Extent {400 l.width = if (limits.max_width < UNBOUNDED) limits.max_width else max(limits.min_width, 320.0);401 l.height = if (limits.max_height < UNBOUNDED) limits.max_height else max(402 limits.min_height,403 min(l.count to f32 * (l.options.estimate + l.options.gap), 400.0)404 );405 // measure the rows made406 for ([..arrange.count()]) |k| {407 const index = l.built.get(k).index;408 const row_limits = if (l.options.fixed) Limits::tight(409 l.width,410 l.options.estimate411 ) else Limits {412 .min_width = l.width,413 .max_width = l.width,414 .max_height = UNBOUNDED415 };416 const size = arrange.lay_out(k, row_limits);417 if (!l.options.fixed) {418 const old = l.heights.insert(index, size.height);419 if (old is ::Some |h|) {420 l.measured -= h;421 }422 l.measured += size.height;423 if (index < l.anchor) {424 if (old is ::Some |h|) {425 l.above -= h;426 } else {427 l.above_count += 1;428 }429 l.above += size.height;430 }431 }432 }433 l.normalize();434 // place them from the anchor, in order435 var y = -l.offset;436 var at = l.anchor;437 for ([..arrange.count()]) |k| {438 const index = l.built.get(k).index;439 while (at < index) {440 y += l.step(at);441 at += 1;442 }443 while (at > index) {444 at -= 1;445 y -= l.step(at);446 }447 arrange.place(k, Point { .x = 0.0, .y = y });448 }449 // the rows in view, and a screen's worth either side450 var first = l.anchor;451 var reach: f32 = l.offset;452 while (first > 0 && reach < l.height) {453 first -= 1;454 reach += l.step(first);455 }456 var last = l.anchor;457 var down: f32 = -l.offset;458 while (last < l.count && down < 2.0 * l.height) {459 down += l.step(last);460 last += 1;461 }462 const span = RowSpan { .first = first, .end = last };463 if (l.wanted is ::Some |wanted| && wanted.peek(&arrange.ui) != span) {464 wanted.set(&var arrange.ui, span);465 }466 return Extent { .width = l.width, .height = l.height };467}468469exp fn paint(self l: &ListView, look: &Look, paint: &var Paint) {}470471pub fn overlay(self l: &ListView, look: &Look, paint: &var Paint) {472 const e = l.extent();473 paint_bar(&look, &var paint, e.offset, e.content, Axis::Vertical);474}475476pub fn event(self l: &var ListView, ui: &var Ui, input: &Input) -> bool {477 match (input) {478 ::Scroll |delta| {479 return l.scroll_by(&var ui, delta.y);480 }481 ::Press |p| {482 const e = l.extent();483 // the bar along the end edge, the left right to left484 const off_bar = if (ui.handling_rtl()) p.x > BAR_REACH else p.x < l.width - BAR_REACH;485 if (e.content <= l.height || off_bar) {486 return false;487 }488 const t = thumb(e.offset, e.content, l.height);489 if (p.y < t.start || p.y > t.start + t.length) {490 // the track: the thumb centered on the press491 const target = offset_at(p.y - t.length / 2.0, &t, e.content, l.height);492 l.scroll_by(&var ui, target - e.offset);493 }494 l.grab = ::Some(p.y - thumb(l.extent().offset, e.content, l.height).start);495 ui.refresh(Change::Paint);496 return true;497 }498 ::Moved |p| {499 const grab = if (l.grab is ::Some |g|) g else {500 return false;501 };502 const e = l.extent();503 const t = thumb(e.offset, e.content, l.height);504 l.scroll_by(&var ui, offset_at(p.y - grab, &t, e.content, l.height) - e.offset);505 return true;506 }507 ::Release {508 const grabbed = l.grab is ::Some;509 l.grab = ::None;510 return grabbed;511 }512 else {513 return false;514 }515 }516}517518// Scrolls by the distance; whether the view moved.519fn scroll_by(self l: &var ListView, ui: &var Ui, distance: f32) -> bool {520 const anchor = l.anchor;521 const offset = l.offset;522 l.offset += distance;523 l.normalize();524 if (l.anchor == anchor && l.offset == offset) {525 return false;526 }527 ui.refresh(Change::Layout);528 return true;529}530531exp fn renew(self l: &var ListView, next: ListView) -> Change => Change::Nothing;532pub fn sizing(self l: &ListView) -> Sizing => l.options.sizing;533pub fn interactive(self l: &ListView) -> bool => true;534pub fn clips(self l: &ListView) -> bool => true;535pub fn semantics(self l: &ListView) -> Semantics => Semantics { .role = Role::List };536537pub fn list_view(self ui: &var Ui, element: Element) -> &var ListView {538 if (ui.node_var(element.index).widget is ::Some |&var widget| && widget is ListView |&var l|) {539 return &var l;540 }541 panic "pkg::alloy::ui: not a list";542}543544pub fn set_list_wanted(self ui: &var Ui, element: Element, wanted: Signal<RowSpan>) {545 ui.list_view(element).wanted = ::Some(wanted);546}547548// The list's row count changed: the rows past it go.549pub fn set_list_count(self ui: &var Ui, element: Element, count: u64) {550 if (!ui.exists(element)) {551 return;552 }553 const l = &var ui.list_view(element);554 l.count = count;555 // the heights of rows past the end go with them556 var past = Vector<u64>::empty();557 for (l.heights.entries()) |&e| {558 if (e.key >= count) {559 past.push(e.key);560 }561 }562 for (past.view()) |row| {563 if (l.heights.remove(&row) is ::Some |height|) {564 l.measured -= height;565 }566 }567 if (l.anchor >= count) {568 l.set_anchor(if (count > 0) count - 1 else 0);569 l.offset = 0.0;570 }571 var gone = Vector<u32>::empty();572 var kept = Vector<BuiltRow>::empty();573 for (l.built.view()) |&b| {574 if (b.index < count) {575 kept.push(b);576 } else {577 gone.push(b.owner);578 }579 }580 l.built = move kept;581 if (gone.length() > 0) {582 ui.place_rows(element);583 }584 for (gone.view()) |&owner| {585 ui.free_owner(owner);586 }587 ui.mark_layout(element.index);588}589590// Makes the rows of the span not made yet, and frees those outside it.591pub fn build_rows(592 self ui: &var Ui,593 element: Element,594 span: &RowSpan,595 row: &|&| (&var Ui, u64) -> Element596) {597 if (!ui.exists(element)) {598 return;599 }600 const first = span.first;601 const end = min(span.end, ui.list_view(element).count);602 var gone = Vector<u32>::empty();603 var kept = Vector<BuiltRow>::empty();604 for (ui.list_view(element).built.view()) |&b| {605 if (b.index < first || b.index >= end) {606 gone.push(b.owner);607 } else {608 kept.push(b);609 }610 }611 var next = Vector<BuiltRow>::empty();612 var k: u64 = 0;613 for ([first..max(first, end)]) |index| {614 if (k < kept.length() && kept.get(k).index == index) {615 next.push(kept.get(k));616 k += 1;617 continue;618 }619 const made = ui.new_owner(ui.owner);620 const built = ui.owned(made, &|&row, index| (ui: &var Ui) -> Element {621 return row(&var ui, index);622 });623 next.push(BuiltRow { .index = index, .owner = made, .node = built.index });624 }625 ui.list_view(element).built = move next;626 ui.place_rows(element);627 for (gone.view()) |&owner| {628 ui.free_owner(owner);629 }630 ui.mark_layout(element.index);631}632633// The list's children: its rows in order.634fn place_rows(self ui: &var Ui, element: Element) {635 ui.disown_children(element.index);636 const rows = copy ui.list_view(element).built;637 for (rows.view()) |&b| {638 ui.adopt_index(element.index, b.node);639 }640}