1
0
mirror of https://github.com/mum4k/termdash.git synced 2025-05-08 19:29:25 +08:00

Refactor RequiredWidth off the Y object.

This commit is contained in:
Jakub Sobon 2019-02-15 21:05:43 -05:00
parent 6ace35ee15
commit 9b3edb42b9
No known key found for this signature in database
GPG Key ID: F2451A77FB05D3B7
3 changed files with 14 additions and 8 deletions

View File

@ -76,14 +76,15 @@ func (y *Y) Update(minVal, maxVal float64) {
}
// RequiredWidth calculates the minimum width required in order to draw the Y
// axis and its labels.
func (y *Y) RequiredWidth() int {
// axis and its labels when displaying values that have this minimum and
// maximum among all the series.
func RequiredWidth(minVal, maxVal float64) int {
// This is an estimation only, it is possible that more labels in the
// middle will be generated and might be wider than this. Such cases are
// handled on the call to Details when the size of canvas is known.
return longestLabel([]*Label{
{Value: y.min},
{Value: y.max},
{Value: NewValue(minVal, nonZeroDecimals)},
{Value: NewValue(maxVal, nonZeroDecimals)},
}) + axisWidth
}
@ -94,7 +95,7 @@ func (y *Y) Details(cvsAr image.Rectangle, reqXHeight int, mode YScaleMode) (*YD
cvsWidth := cvsAr.Dx()
cvsHeight := cvsAr.Dy()
maxWidth := cvsWidth - 1 // Reserve one column for the line chart itself.
if req := y.RequiredWidth(); maxWidth < req {
if req := RequiredWidth(y.min.Value, y.max.Value); maxWidth < req {
return nil, fmt.Errorf("the available maxWidth %d is smaller than the reported required width %d", maxWidth, req)
}

View File

@ -186,7 +186,7 @@ func TestY(t *testing.T) {
y.Update(tc.update.minVal, tc.update.maxVal)
}
gotWidth := y.RequiredWidth()
gotWidth := RequiredWidth(tc.minVal, tc.maxVal)
if gotWidth != tc.wantWidth {
t.Errorf("RequiredWidth => got %v, want %v", gotWidth, tc.wantWidth)
}

View File

@ -81,6 +81,8 @@ type LineChart struct {
// yAxis is the Y axis of the line chart.
yAxis *axes.Y
// yMin are the min and max values for the Y axis.
yMin, yMax float64
// opts are the provided options.
opts *options
@ -188,7 +190,10 @@ func (lc *LineChart) Series(label string, values []float64, opts ...SeriesOption
}
lc.series[label] = series
lc.yAxis = axes.NewY(lc.yMinMax())
yMin, yMax := lc.yMinMax()
lc.yAxis = axes.NewY(yMin, yMax)
lc.yMin = yMin
lc.yMax = yMax
return nil
}
@ -335,7 +340,7 @@ func (lc *LineChart) minSize() image.Point {
// At the very least we need:
// - n cells width for the Y axis and its labels as reported by it.
// - at least 1 cell width for the graph.
reqWidth := lc.yAxis.RequiredWidth() + 1
reqWidth := axes.RequiredWidth(lc.yMin, lc.yMax) + 1
// And for the height:
// - n cells width for the X axis and its labels as reported by it.