# popover_anchor.ludic - `
` sits beside the element with that id (the
# nearest), a bare `anchor` beside the one before it: `placement` right, left, bottom or top (its margin
# is the gap), `align` start, center or end along that side, flipped and kept within its bounds.
function pp_anchor_all(ui_st: mut UiState, n: UiNode) -> void {
if n.children == null { return }
for i in 0 .. len(n.children) {
let c = n.children[i]
if c.popover and Value.kind(ui_attr(c, "anchor")) != 0 { pp_anchor(ui_st, c, pp_anchor_of(ui_st, n, i)) }
pp_anchor_all(ui_st, c)
}
}
# the element a popover (the i-th child of `parent`) is anchored to, or null
function pp_anchor_of(ui_st: mut UiState, parent: UiNode, i: int) -> UiNode {
let pop = parent.children[i]
let id = ui_attr_text(pop, "anchor")
if id == "" or id == "true" {
var k = i - 1
while k >= 0 and parent.children[k].popover { k -= 1 }
if k < 0 { return null }
return parent.children[k]
}
var at = parent
while at != null {
let f = pp_by_id(at, id, pop)
if f != null { return f }
at = at.parent
}
@alloc_ok("only when a template is wrong: a broken screen, never a working one")
ui_err(ui_st, `anchor="{id}": no element has that id`)
return null
}
function pp_by_id(n: UiNode, id: string, skip: UiNode) -> UiNode {
if n == skip { return null }
if n.id == id { return n }
if n.children == null { return null }
for i in 0 .. len(n.children) {
let f = pp_by_id(n.children[i], id, skip)
if f != null { return f }
}
return null
}
function pp_anchor(ui_st: mut UiState, p: UiNode, a: UiNode) -> void {
if a == null { return }
let side = ui_attr_text(p, "placement")
let align = ui_attr_text(p, "align")
pp_bounds(ui_st, p)
let w = p.cw
let h = p.ch
var x = a.x
var y = a.y
if side == "top" or side == "bottom" {
let below = a.y + a.ch + p.mt
let above = a.y - h - p.mb
y = pp_side(side == "top", above, below, h, ui_st.pp_by, ui_st.pp_bh)
x = pp_along(align, a.x, a.cw, w) + p.ml
} else {
let right = a.x + a.cw + p.ml
let left = a.x - w - p.mr
x = pp_side(side == "left", left, right, w, ui_st.pp_bx, ui_st.pp_bw)
y = pp_along(align, a.y, a.ch, h) + p.mt
}
x = Math.max(ui_st.pp_bx, Math.min(x, ui_st.pp_bx + ui_st.pp_bw - w))
y = Math.max(ui_st.pp_by, Math.min(y, ui_st.pp_by + ui_st.pp_bh - h))
ly_place(ui_st, p, x, y, w, h)
sc_apply(ui_st, p)
}
# where along one axis: the side asked for (`low` first when `first_low`), else the other when the
# first leaves the screen and the other does not
function pp_side(first_low: bool, low: float, high: float, size: float, v0: float, vsize: float) -> float {
let low_fits = low >= v0
let high_fits = high + size <= v0 + vsize
if first_low {
if low_fits or not high_fits { return low }
return high
}
if high_fits or not low_fits { return high }
return low
}