Debian Codegraph @

shiny/widget/flex/flex.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package flex provides a container widget that lays out its children
6 // following the CSS flexbox algorithm.
7 //
8 // As the shiny widget model does not provide all of the layout features
9 // of CSS, the flex package diverges in several ways. There is no item
10 // inline-axis, no item margins or padding to be accounted for, and the
11 // container size provided by the outer widget is taken as gospel and
12 // never expanded.
13 package flex
14
15 import (
16 "fmt"
17 "image"
18 "math"
19
20 "golang.org/x/exp/shiny/widget/node"
21 "golang.org/x/exp/shiny/widget/theme"
22 )
23
24 // Direction is the direction in which flex items are laid out.
25 //
26 // https://www.w3.org/TR/css-flexbox-1/#flex-direction-property
27 type Direction uint8
28
29 const (
30 Row Direction = iota
31 RowReverse
32 Column
33 ColumnReverse
34 )
35
36 // FlexWrap controls whether the container is single- or multi-line,
37 // and the direction in which the lines are laid out.
38 //
39 // https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property
40 type FlexWrap uint8
41
42 const (
43 NoWrap FlexWrap = iota
44 Wrap
45 WrapReverse
46 )
47
48 // Justify aligns items along the main axis.
49 //
50 // https://www.w3.org/TR/css-flexbox-1/#justify-content-property
51 type Justify uint8
52
53 const (
54 JustifyStart Justify = iota // pack to start of line
55 JustifyEnd // pack to end of line
56 JustifyCenter // pack to center of line
57 JustifySpaceBetween // even spacing
58 JustifySpaceAround // even spacing, half-size on each end
59 )
60
61 // AlignItem aligns items along the cross axis.
62 //
63 // It is the 'align-items' property when applied to a Flex container,
64 // and the 'align-self' property when applied to an item in LayoutData.
65 //
66 // https://www.w3.org/TR/css-flexbox-1/#align-items-property
67 // https://www.w3.org/TR/css-flexbox-1/#propdef-align-self
68 type AlignItem uint8
69
70 const (
71 AlignItemAuto AlignItem = iota
72 AlignItemStart
73 AlignItemEnd
74 AlignItemCenter
75 AlignItemBaseline // TODO requires introducing inline-axis concept
76 AlignItemStretch
77 )
78
79 // AlignContent is the 'align-content' property.
80 // It aligns container lines when there is extra space on the cross-axis.
81 //
82 // https://www.w3.org/TR/css-flexbox-1/#align-content-property
83 type AlignContent uint8
84
85 const (
86 AlignContentStretch AlignContent = iota
87 AlignContentStart
88 AlignContentEnd
89 AlignContentCenter
90 AlignContentSpaceBetween
91 AlignContentSpaceAround
92 )
93
94 // Basis sets the base size of a flex item.
95 //
96 // A default basis of Auto means the flex container uses the
97 // MeasuredSize of an item. Otherwise a Definite Basis will
98 // override the MeasuredSize with BasisPx.
99 //
100 // TODO: do we (or will we )have a useful notion of Content in the
101 // widget layout model that is separate from MeasuredSize? If not,
102 // we could consider completely removing this concept from this
103 // flex implementation.
104 type Basis uint8
105
106 const (
107 Auto Basis = iota
108 Definite
109 )
110
111 // Flex is a container widget that lays out its children following the
112 // CSS flexbox algorithm.
113 type Flex struct {
114 node.ContainerEmbed
115
116 Direction Direction
117 Wrap FlexWrap
118 Justify Justify
119 AlignItems AlignItem
120 AlignContent AlignContent
121 }
122
123 // NewFlex returns a new Flex widget containing the given children.
124 func NewFlex(children ...node.Node) *Flex {
125 w := new(Flex)
126 w.Wrapper = w
127 for _, c := range children {
128 w.Insert(c, nil)
129 }
130 return w
131 }
132
133 func (w *Flex) Measure(t *theme.Theme, widthHint, heightHint int) {
134 // As Measure is a bottom-up calculation of natural size, we have no
135 // hint yet as to how we should flex. So we ignore Wrap, Justify,
136 // AlignItem, AlignContent.
137 for c := w.FirstChild; c != nil; c = c.NextSibling {
138 // TODO: pass down width/height hints?
139 c.Wrapper.Measure(t, node.NoHint, node.NoHint)
140 if d, ok := c.LayoutData.(LayoutData); ok {
141 _ = d
142 // TODO Measure
143 }
144 }
145 }
146
147 func (w *Flex) Layout(t *theme.Theme) {
148 var children []element
149 for c := w.FirstChild; c != nil; c = c.NextSibling {
150 children = append(children, element{
151 flexBaseSize: float64(w.flexBaseSize(c)),
152 n: c,
153 })
154 }
155
156 containerMainSize := float64(w.mainSize(w.Rect.Size()))
157 containerCrossSize := float64(w.crossSize(w.Rect.Size()))
158
159 // §9.3.5 collect children into flex lines
160 var lines []flexLine
161 if w.Wrap == NoWrap {
162 line := flexLine{child: make([]*element, len(children))}
163 for i := range children {
164 child := &children[i]
165 line.child[i] = child
166 line.mainSize += child.flexBaseSize
167 }
168 lines = []flexLine{line}
169 } else {
170 var line flexLine
171
172 for i := range children {
173 child := &children[i]
174
175 hypotheticalMainSize := w.clampSize(child.flexBaseSize, child.n)
176
177 if line.mainSize > 0 && line.mainSize+hypotheticalMainSize > containerMainSize {
178 lines = append(lines, line)
179 line = flexLine{}
180 }
181 line.child = append(line.child, child)
182 line.mainSize += hypotheticalMainSize
183
184 if d, ok := child.n.LayoutData.(LayoutData); ok && d.BreakAfter {
185 lines = append(lines, line)
186 line = flexLine{}
187 }
188 }
189 if len(line.child) > 0 || len(children) == 0 {
190 lines = append(lines, line)
191 }
192
193 if w.Wrap == WrapReverse {
194 for i := 0; i < len(lines)/2; i++ {
195 lines[i], lines[len(lines)-i-1] = lines[len(lines)-i-1], lines[i]
196 }
197 }
198 }
199
200 // §9.3.6 resolve flexible lengths (details in section §9.7)
201 for l := range lines {
202 line := &lines[l]
203 grow := line.mainSize < containerMainSize // §9.7.1
204
205 // §9.7.2 freeze inflexible children.
206 for _, child := range line.child {
207 mainSize := float64(w.mainSize(child.n.MeasuredSize))
208 hypotheticalMainSize := w.clampSize(mainSize, child.n)
209 if grow {
210 if growFactor(child.n) == 0 || float64(w.flexBaseSize(child.n)) > hypotheticalMainSize {
211 child.frozen = true
212 child.mainSize = hypotheticalMainSize
213 }
214 } else {
215 if shrinkFactor(child.n) == 0 || float64(w.flexBaseSize(child.n)) < hypotheticalMainSize {
216 child.frozen = true
217 child.mainSize = hypotheticalMainSize
218 }
219 }
220 }
221
222 // §9.7.3 calculate initial free space
223 initFreeSpace := float64(w.mainSize(w.Rect.Size()))
224 for _, child := range line.child {
225 if child.frozen {
226 initFreeSpace -= child.mainSize
227 } else {
228 initFreeSpace -= float64(w.flexBaseSize(child.n))
229 }
230 }
231
232 // §9.7.4 flex loop
233 for {
234 // Check for flexible items.
235 allFrozen := true
236 for _, child := range line.child {
237 if !child.frozen {
238 allFrozen = false
239 break
240 }
241 }
242 if allFrozen {
243 break
244 }
245
246 // Calculate remaining free space.
247 remFreeSpace := float64(w.mainSize(w.Rect.Size()))
248 unfrozenFlexFactor := 0.0
249 for _, child := range line.child {
250 if child.frozen {
251 remFreeSpace -= child.mainSize
252 } else {
253 remFreeSpace -= float64(w.flexBaseSize(child.n))
254 if grow {
255 unfrozenFlexFactor += growFactor(child.n)
256 } else {
257 unfrozenFlexFactor += shrinkFactor(child.n)
258 }
259 }
260 }
261 if unfrozenFlexFactor < 1 {
262 p := initFreeSpace * unfrozenFlexFactor
263 if math.Abs(p) < math.Abs(remFreeSpace) {
264 remFreeSpace = p
265 }
266 }
267
268 // Distribute free space proportional to flex factors.
269 if grow {
270 for _, child := range line.child {
271 if child.frozen {
272 continue
273 }
274 r := growFactor(child.n) / unfrozenFlexFactor
275 child.mainSize = float64(w.flexBaseSize(child.n)) + r*remFreeSpace
276 }
277 } else {
278 sumScaledShrinkFactor := 0.0
279 for _, child := range line.child {
280 if child.frozen {
281 continue
282 }
283 scaledShrinkFactor := float64(w.flexBaseSize(child.n)) * shrinkFactor(child.n)
284 sumScaledShrinkFactor += scaledShrinkFactor
285 }
286 for _, child := range line.child {
287 if child.frozen {
288 continue
289 }
290 scaledShrinkFactor := float64(w.flexBaseSize(child.n)) * shrinkFactor(child.n)
291 r := float64(scaledShrinkFactor) / sumScaledShrinkFactor
292 child.mainSize = float64(w.flexBaseSize(child.n)) - r*math.Abs(float64(remFreeSpace))
293 }
294 }
295
296 // Fix min/max violations.
297 sumClampDiff := 0.0
298 for _, child := range line.child {
299 // TODO: we work in whole pixels but flex calculations are done in
300 // fractional pixels. Take this opportunity to clamp us to whole
301 // pixels and make sure we sum correctly.
302 if child.frozen {
303 continue
304 }
305 child.unclamped = child.mainSize
306 child.mainSize = w.clampSize(child.mainSize, child.n)
307
308 sumClampDiff += child.mainSize - child.unclamped
309 }
310
311 // Freeze over-flexed items.
312 switch {
313 case sumClampDiff == 0:
314 for _, child := range line.child {
315 child.frozen = true
316 }
317 case sumClampDiff > 0:
318 for _, child := range line.child {
319 if child.mainSize > child.unclamped {
320 child.frozen = true
321 }
322 }
323 case sumClampDiff < 0:
324 for _, child := range line.child {
325 if child.mainSize < child.unclamped {
326 child.frozen = true
327 }
328 }
329 }
330 }
331
332 // §9.7.5 set main size
333 // At this point, child.mainSize is right.
334 }
335
336 // §9.4 determine cross size
337 // §9.4.7 calculate hypothetical cross size of each element
338 for l := range lines {
339 for _, child := range lines[l].child {
340 child.crossSize = float64(w.crossSize(child.n.MeasuredSize))
341 if child.mainSize < float64(w.mainSize(child.n.MeasuredSize)) {
342 if r, ok := aspectRatio(child.n); ok {
343 child.crossSize = child.mainSize / r
344 }
345 }
346 if d, ok := child.n.LayoutData.(LayoutData); ok {
347 minSize := float64(w.crossSize(d.MinSize))
348 if minSize > child.crossSize {
349 child.crossSize = minSize
350 } else if d.MaxSize != nil {
351 maxSize := float64(w.crossSize(*d.MaxSize))
352 if child.crossSize > maxSize {
353 child.crossSize = maxSize
354 }
355 }
356 }
357 }
358 }
359 if len(lines) == 1 {
360 // §9.4.8 single line
361 switch w.Direction {
362 case Row, RowReverse:
363 lines[0].crossSize = float64(w.Rect.Size().Y)
364 case Column, ColumnReverse:
365 lines[0].crossSize = float64(w.Rect.Size().X)
366 }
367 } else {
368 // §9.4.8 multi-line
369 for l := range lines {
370 line := &lines[l]
371 // TODO §9.4.8.1, no concept of inline-axis yet
372 max := 0.0
373 for _, child := range line.child {
374 if child.crossSize > max {
375 max = child.crossSize
376 }
377 }
378 line.crossSize = max
379 }
380 }
381 off := 0.0
382 for l := range lines {
383 line := &lines[l]
384 line.crossOffset = off
385 off += line.crossSize
386 }
387 // §9.4.9 align-content: stretch
388 remCrossSize := containerCrossSize - off
389 if w.AlignContent == AlignContentStretch && remCrossSize > 0 {
390 add := remCrossSize / float64(len(lines))
391 for l := range lines {
392 line := &lines[l]
393 line.crossOffset += float64(l) * add
394 line.crossSize += add
395 }
396 }
397 // Note: no equiv. to §9.4.10 "visibility: collapse".
398 // §9.4.11 align-item: stretch
399 for l := range lines {
400 line := &lines[l]
401 for _, child := range line.child {
402 align := w.alignItem(child.n)
403 if align == AlignItemStretch && child.crossSize < line.crossSize {
404 child.crossSize = line.crossSize
405 }
406 }
407 }
408
409 // §9.5 main axis alignment
410 for l := range lines {
411 line := &lines[l]
412 total := 0.0
413 for _, child := range line.child {
414 total += child.mainSize
415 }
416 remFree := containerMainSize - total
417 off, spacing := 0.0, 0.0
418 switch w.Justify {
419 case JustifyStart:
420 case JustifyEnd:
421 off = remFree
422 case JustifyCenter:
423 off = remFree / 2
424 case JustifySpaceBetween:
425 spacing = remFree / float64(len(line.child)-1)
426 case JustifySpaceAround:
427 spacing = remFree / float64(len(line.child))
428 off = spacing / 2
429 }
430 for _, child := range line.child {
431 child.mainOffset = off
432 off += spacing + child.mainSize
433 }
434 }
435
436 // §9.6 cross axis alignment
437 // §9.6.13 no 'auto' margins
438 // §9.6.14 align items inside line, 'align-self'.
439 for l := range lines {
440 line := &lines[l]
441 for _, child := range line.child {
442 child.crossOffset = line.crossOffset
443 if child.crossSize == line.crossSize {
444 continue
445 }
446 diff := line.crossSize - child.crossSize
447 switch w.alignItem(child.n) {
448 case AlignItemStart:
449 // already laid out correctly
450 case AlignItemEnd:
451 child.crossOffset = line.crossOffset + diff
452 case AlignItemCenter:
453 child.crossOffset = line.crossOffset + diff/2
454 case AlignItemBaseline:
455 // TODO requires introducing inline-axis concept
456 case AlignItemStretch:
457 // handled earlier, so child.crossSize == line.crossSize
458 }
459 }
460 }
461 // §9.6.15 determine container cross size used
462 crossSize := lines[len(lines)-1].crossOffset + lines[len(lines)-1].crossSize
463 remFree := containerCrossSize - crossSize
464
465 // §9.6.16 align flex lines, 'align-content'.
466 if remFree > 0 {
467 spacing, off := 0.0, 0.0
468 switch w.AlignContent {
469 case AlignContentStart:
470 // already laid out correctly
471 case AlignContentEnd:
472 off = remFree
473 case AlignContentCenter:
474 off = remFree / 2
475 case AlignContentSpaceBetween:
476 spacing = remFree / float64(len(lines)-1)
477 case AlignContentSpaceAround:
478 spacing = remFree / float64(len(lines))
479 off = spacing / 2
480 case AlignContentStretch:
481 // handled earlier, why is remFree > 0?
482 }
483 if w.AlignContent != AlignContentStart && w.AlignContent != AlignContentStretch {
484 for l := range lines {
485 line := &lines[l]
486 line.crossOffset += off
487 for _, child := range line.child {
488 child.crossOffset += off
489 }
490 off += spacing
491 }
492 }
493 }
494
495 switch w.Direction {
496 case RowReverse, ColumnReverse:
497 // Invert main-start and main-end.
498 for l := range lines {
499 line := &lines[l]
500 for _, child := range line.child {
501 child.mainOffset = containerMainSize - child.mainOffset - child.mainSize
502 }
503 }
504 }
505
506 // Layout complete. Generate child Rect values.
507 for l := range lines {
508 line := &lines[l]
509 for _, child := range line.child {
510 switch w.Direction {
511 case Row, RowReverse:
512 child.n.Rect.Min.X = round(child.mainOffset)
513 child.n.Rect.Max.X = round(child.mainOffset + child.mainSize)
514 child.n.Rect.Min.Y = round(child.crossOffset)
515 child.n.Rect.Max.Y = round(child.crossOffset + child.crossSize)
516 case Column, ColumnReverse:
517 child.n.Rect.Min.Y = round(child.mainOffset)
518 child.n.Rect.Max.Y = round(child.mainOffset + child.mainSize)
519 child.n.Rect.Min.X = round(child.crossOffset)
520 child.n.Rect.Max.X = round(child.crossOffset + child.crossSize)
521 default:
522 panic(fmt.Sprint("flex: bad direction ", w.Direction))
523 }
524 child.n.Wrapper.Layout(t)
525 }
526 }
527 }
528
529 func round(f float64) int {
530 return int(math.Floor(f + .5))
531 }
532
533 type element struct {
534 n *node.Embed
535 flexBaseSize float64
536 frozen bool
537 unclamped float64
538 mainSize float64
539 mainOffset float64
540 crossSize float64
541 crossOffset float64
542 }
543
544 type flexLine struct {
545 mainSize float64
546 crossSize float64
547 crossOffset float64
548 child []*element
549 }
550
551 func (w *Flex) alignItem(n *node.Embed) AlignItem {
552 align := w.AlignItems
553 if d, ok := n.LayoutData.(LayoutData); ok {
554 align = d.Align
555 }
556 return align
557 }
558
559 // flexBaseSize calculates flex base size as per §9.2.3
560 func (w *Flex) flexBaseSize(n *node.Embed) int {
561 basis := Auto
562 if d, ok := n.LayoutData.(LayoutData); ok {
563 basis = d.Basis
564 }
565 // TODO Content §9.2.3.B, C, D
566 switch basis {
567 case Definite: // A
568 return n.LayoutData.(LayoutData).BasisPx
569 case Auto: // E
570 return w.mainSize(n.MeasuredSize)
571 default:
572 panic(fmt.Sprintf("flex: unknown flex-basis %v", basis))
573 }
574 }
575
576 func growFactor(n *node.Embed) float64 {
577 if d, ok := n.LayoutData.(LayoutData); ok {
578 return d.Grow
579 }
580 return 0
581 }
582
583 func shrinkFactor(n *node.Embed) float64 {
584 if d, ok := n.LayoutData.(LayoutData); ok && d.Shrink != nil {
585 return *d.Shrink
586 }
587 return 1
588 }
589
590 func aspectRatio(n *node.Embed) (ratio float64, ok bool) {
591 // TODO: source a formal description of "intrinsic aspect ratio"
592 d, ok := n.LayoutData.(LayoutData)
593 if ok && d.MinSize.X != 0 && d.MinSize.Y != 0 {
594 return float64(d.MinSize.X) / float64(d.MinSize.Y), true
595 }
596 return 0, false
597 }
598
599 func (w *Flex) clampSize(size float64, n *node.Embed) float64 {
600 if d, ok := n.LayoutData.(LayoutData); ok {
601 minSize := float64(w.mainSize(d.MinSize))
602 if minSize > size {
603 size = minSize
604 } else if d.MaxSize != nil {
605 maxSize := float64(w.mainSize(*d.MaxSize))
606 if size > maxSize {
607 size = maxSize
608 }
609 }
610 }
611 if size < 0 {
612 return 0
613 }
614 return size
615 }
616
617 func (w *Flex) mainSize(p image.Point) int {
618 switch w.Direction {
619 case Row, RowReverse:
620 return p.X
621 case Column, ColumnReverse:
622 return p.Y
623 default:
624 panic(fmt.Sprint("flex: bad direction ", w.Direction))
625 }
626 }
627
628 func (w *Flex) crossSize(p image.Point) int {
629 switch w.Direction {
630 case Row, RowReverse:
631 return p.Y
632 case Column, ColumnReverse:
633 return p.X
634 default:
635 panic(fmt.Sprint("flex: bad direction ", w.Direction))
636 }
637 }
638
639 // LayoutData is the node LayoutData type for a Flex's children.
640 type LayoutData struct {
641 MinSize image.Point // TODO use unit.Value
642 MaxSize *image.Point // TODO use unit.Value
643
644 // Grow determines how much a node will grow relative to its siblings.
645 Grow float64
646
647 // Shrink is the flex shrink factor which determines how much a node
648 // will shrink relative to its siblings. If nil, a default shrink
649 // factor of 1 is used.
650 Shrink *float64
651
652 // Basis determines the initial size of the node in the direction
653 // of the flex container (the main axis).
654 //
655 // If set to Definite, the value stored in BasisPx is used.
656 Basis Basis
657 BasisPx int // TODO use unit package?
658
659 Align AlignItem
660
661 // BreakAfter forces the next node onto the next flex line.
662 BreakAfter bool
663 }