Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 24 additions & 21 deletions help/src/main/scala/flatgraph/help/Table.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ case class Table(columnNames: Seq[String], rows: Seq[Row]) {

// calculate natural column widths: longest content per column, clamped to minWidth
val widths = (0 until numCols).map { col =>
val longest = allRows.map(row => if (col < row.size) row(col).length else 0).max
val longest = allRows.map(row => if (col < row.size) row(col).linesIterator.map(_.length).maxOption.getOrElse(0) else 0).max
math.max(longest, minWidth)
}.toArray

Expand Down Expand Up @@ -68,28 +68,31 @@ case class Table(columnNames: Seq[String], rows: Seq[Row]) {
}

private def wordWrap(text: String, width: Int): Seq[String] = {
if (text.length <= width) {
return Seq(text)
}
val words = text.split(" ", -1)
val lines = Seq.newBuilder[String]
val current = new StringBuilder()
for (word <- words) {
if (current.isEmpty) {
current.append(word)
} else if (current.length + 1 + word.length > width) {
lines += current.toString()
current.clear()
current.append(word)
text.linesIterator.flatMap { paragraph =>
if (paragraph.length <= width) {
Seq(paragraph)
} else {
current.append(' ')
current.append(word)
val words = paragraph.split(" ", -1)
val lines = Seq.newBuilder[String]
val current = new StringBuilder()
for (word <- words) {
if (current.isEmpty) {
current.append(word)
} else if (current.length + 1 + word.length > width) {
lines += current.toString()
current.clear()
current.append(word)
} else {
current.append(' ')
current.append(word)
}
}
if (current.nonEmpty) {
lines += current.toString()
}
lines.result()
}
}
if (current.nonEmpty) {
lines += current.toString()
}
lines.result()
}.toSeq
}
}

Expand Down
17 changes: 17 additions & 0 deletions help/src/test/scala/flatgraph/help/TableTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ class TableTests extends AnyWordSpec {
|""".stripMargin.trim
}

"handle newlines in cell content" in {
val table = Table(Seq("column a", "column b"), Seq(Seq("line1\nline2", "single"), Seq("no newline", "a\nb\nc")))

implicit val availableWidthProvider: AvailableWidthProvider = new Table.ConstantWidth(80)
table.render.trim shouldBe
"""┌──────────┬────────┐
|│column a │column b│
|├──────────┼────────┤
|│line1 │single │
|│line2 │ │
|│no newline│a │
|│ │b │
|│ │c │
|└──────────┴────────┘
|""".stripMargin.trim
}

"adapt to dynamically changing terminal width" in {
val table = Table(
Seq("lorem ipsum"),
Expand Down
Loading