UNPKG

@thi.ng/imgui

Version:

Immediate mode GUI with flexible state handling & data only shape output

113 lines (112 loc) 2.53 kB
import { line } from "@thi.ng/geom/line"; import { rect } from "@thi.ng/geom/rect"; import { clamp2 } from "@thi.ng/vectors/clamp"; import { fit2 } from "@thi.ng/vectors/fit"; import { hash } from "@thi.ng/vectors/hash"; import { handleSlider2Keys, isHoverSlider, slider2Val } from "../behaviors/slider.js"; import { textLabelRaw } from "./textlabel.js"; import { tooltipRaw } from "./tooltip.js"; const xyPad = ({ gui, layout, id, min, max, step, value, mode = "square", yUp = true, label, info, fmt }) => { let box; const ch = layout.cellH; const gapY = layout.gapY; if (mode === "square") { box = layout.nextSquare(); } else { const rows = mode === "prop" ? layout.cellW / (ch + gapY) | 0 : mode; box = layout.next([1, rows + 1]); box.h -= ch + gapY; } return xyPadRaw( gui, id, box.x, box.y, box.w, box.h, min, max, step, value, yUp, 0, box.h + gapY + ch / 2 + gui.theme.baseLine, label, fmt, info ); }; const xyPadRaw = (gui, id, x, y, w, h, min, max, step, val, yUp = false, labelX, labelY, label, fmt, info) => { const maxX = x + w; const maxY = y + h; const pos = yUp ? [x, maxY] : [x, y]; const maxPos = yUp ? [maxX, y] : [maxX, maxY]; const key = hash([x, y, w, h]); gui.registerID(id, key); const box = gui.resource(id, key, () => rect([x, y], [w, h])); const col = gui.textColor(false); const hover = isHoverSlider(gui, id, box, "move"); const draw = gui.draw; let v = clamp2([], val, min, max); let res; if (hover) { if (gui.isMouseDown()) { gui.activeID = id; res = slider2Val( fit2([], gui.mouse, pos, maxPos, min, max), min, max, step ); } info && draw && tooltipRaw(gui, info); } const focused = gui.requestFocus(id); if (draw) { box.attribs = { fill: gui.bgColor(hover || focused), stroke: gui.focusColor(id) }; const { 0: cx, 1: cy } = fit2([], v, min, max, pos, maxPos); gui.add( box, line([x, cy], [maxX, cy], { stroke: col }), line([cx, y], [cx, maxY], { stroke: col }), textLabelRaw( [x + labelX, y + labelY], col, (label ? label + " " : "") + (fmt ? fmt(val) : `${val[0] | 0}, ${val[1] | 0}`) ) ); } if (focused && (v = handleSlider2Keys(gui, min, max, step, v, yUp)) !== void 0) { return v; } gui.lastID = id; return res; }; export { xyPad, xyPadRaw };