s LearnSqueak.com

PRACTICAL SQUEAK WORKSHOP

Turn CSV data into interactive charts

Parse a small CSV table, scale positive and negative values, and inspect bars or line points.

9 construction stagesTested source & checkpointsNative screenshots & demos
Try the finished example

Run in the SqueakJS playground

The separate playground loads the real Smalltalk image on demand. This lesson keeps its native setup instructions; browser compatibility notes appear beside each demo.

Before you start

This chart laboratory connects text, data validation, geometry and mouse events. You will build an editable CSV pane above a chart, choose a numeric series, switch between bars and lines, and select a point to read its exact value. All data in the examples is fictional.

Work through the stages in order to understand the construction, or file in any checkpoint on its own. Each self-contained checkpoint includes the complete supporting class; the stage setting progressively reveals the interface. The displayed methods are the actual tested implementation, not pseudocode.

  • Stock Squeak 6.1 build 23976. Basic Workspace Do it and Browser method acceptance.
  • Use a practice image and tutorial-created files. Download a checkpoint, open it in File List and choose fileIn.

Classes and objects · Using Squeak’s tools

  • The screenshot captures use the native Morphic renderer in the installed Squeak image. They are not browser imitations.
  • An unaccepted text edit is a draft. Use the native text pane’s Accept command before expecting model changes.

01 · Create the chart model

The model holds the original CSV text, parsed headers and rows, current series, chart mode and selected row. Initialize a small fictional dataset so that a clean image immediately has something useful to inspect.

The initial checkpoint displays only the shell. Later controls reuse this state; drawing code never reparses the text. That avoids turning every repaint into a parsing operation.

LSCSVChart >> initialize
initialize
 super initialize.
 self color: (Color r: 0.09 g: 0.12 b: 0.18); extent: 880@650.
 stage := 9. mode := #bar. series := 2. selection := 0.
 csv := 'day,visits,signups', String lf, 'Mon,12,3', String lf, 'Tue,20,6', String lf, 'Wed,15,5', String lf, 'Thu,28,9', String lf, 'Fri,23,7'.
 self acceptCSV: csv.
 self installControls
Where to run this

File in csv-charts-01.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new stage: 1; openInWorld
Expected result

The panel opens without external data or packages.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Create the chart model executed in native Squeak 6.1
Real Squeak 6.1 capture.

02 · Add an editable text pane

PluggableTextMorph asks csv for the text and sends acceptCSV: when you accept an edit. Editing and accepting are separate actions in Squeak. Use the pane’s context-menu Accept command; the usual platform command shortcut is also shown by Squeak.

A draft can remain in the editor without changing the chart. This is deliberate: a half-typed number should not replace a valid dataset. The accepted value is copied into the model only after validation succeeds.

LSCSVChart >> installControls
installControls
 | pane x |
 self submorphs do: [:each | each delete].
 stage >= 2 ifTrue: [pane := PluggableTextMorph on: self text: #csv accept: #acceptCSV:.
 pane position: self position + (25@72); extent: 830@140. self addMorph: pane].
 stage >= 5 ifTrue: [x := 25.
 #('Bars' 'Lines' 'Next series' 'Load CSV' 'Example') with: #(bars lines nextSeries loadDialog sample) do: [:label :selector |
 | b | b := SimpleButtonMorph new label: label; target: self; actionSelector: selector; yourself.
 b position: self position + (x@230). self addMorph: b. x := x+155]]
Where to run this

File in csv-charts-02.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new stage: 2; openInWorld
Expected result

The sample CSV appears in a native editable pane.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Add an editable text pane executed in native Squeak 6.1
Real Squeak 6.1 capture.

03 · Parse first, validate second

The CSV state machine recognizes separators, quoted fields and doubled quote characters. Structural parsing alone is not enough: every row must have the same number of columns, labels and headers need bounded lengths, and numeric fields must parse completely.

All candidate rows are built before assignment. If the last row is invalid, the first four rows are not partially installed. Try replacing a value with a word and accept: the status explains the rejection while the last accepted model remains.

LSCSVChart >> acceptCSV:
acceptCSV: text
 | parsed newHeaders newRows |
 [text size > 16000 ifTrue: [self error: 'CSV exceeds 16000 characters'].
 parsed := self csvRows: text.
 (parsed size between: 2 and: 41) ifFalse: [self error: 'Use 1 to 40 data rows'].
 newHeaders := parsed first.
 (newHeaders size between: 2 and: 4) ifFalse: [self error: 'Use one label and one to three numeric series'].
 (newHeaders allSatisfy: [:h | h size between: 1 and: 20]) ifFalse: [self error: 'Headers must have 1 to 20 characters'].
 newRows := parsed allButFirst collect: [:row |
 row size = newHeaders size ifFalse: [self error: 'All rows need the same column count'].
 (row first size between: 1 and: 20) ifFalse: [self error: 'Labels must have 1 to 20 characters'].
 {row first}, (row allButFirst collect: [:field | self numericField: field])].
 ] on: Error do: [:e | status := 'Rejected: ', e messageText. self changed. ^ false].
 headers := newHeaders. rows := newRows. csv := text asString copy.
 series := 2. selection := 0. status := 'Accepted ', rows size printString, ' rows. Click a point or bar for its exact value'.
 self changed: #csv; changed. ^ true
Where to run this

File in csv-charts-03.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new stage: 3; openInWorld
Expected result

A row count and selected series name appear. Invalid input is rejected atomically.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Parse first, validate second executed in native Squeak 6.1
Real Squeak 6.1 capture.

04 · Map data onto a plot rectangle

The horizontal coordinate uses the row’s center within its equal-width category slot. The vertical coordinate normalizes the value within the minimum/maximum range and reverses the direction because screen y increases downward.

The range includes zero so bar lengths have a meaningful baseline. If every value is zero, use a one-unit range to avoid division by zero. Negative values lie below the zero line; they are not silently discarded.

LSCSVChart >> pointAt:
pointAt: index
 | range plot value x y |
 range := self range. plot := self plotBounds. value := (rows at: index) at: series.
 x := plot left + (((index-0.5) * plot width) / rows size).
 y := plot bottom - (((value-range first) / (range second-range first)) * plot height).
 ^ x rounded @ y rounded
Where to run this

File in csv-charts-04.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new stage: 4; openInWorld
Expected result

The first bar chart is drawn with a labeled zero-inclusive range.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Map data onto a plot rectangle executed in native Squeak 6.1
Real Squeak 6.1 capture.

05 · Switch between bars and lines

Both modes share pointAt:. Bars span between a value and zero; line mode joins adjacent points and paints small markers. Reusing the coordinate transform prevents two chart modes from disagreeing about the same data.

The buttons send ordinary messages to the same object. Changing mode only changes presentation, so the accepted CSV and selected series remain intact.

LSCSVChart >> drawOn:
drawOn: canvas
 | origin color plot range zero previous p box |
 super drawOn: canvas. origin := self position. color := Color white.
 canvas drawString: 'CSV CHART LAB / ACCEPT TEXT WITH ALT-S OR CMD-S' at: origin+(25@22) font: TextStyle defaultFont color: color.
 stage >= 3 ifTrue: [canvas drawString: ('Rows: ', rows size printString, '   Series: ', (headers at: series), '   Mode: ', mode) at: origin+(25@265) font: TextStyle defaultFont color: color].
 stage >= 4 ifTrue: [plot := self plotBounds. range := self range.
 canvas frameRectangle: plot width: 1 color: Color gray.
 canvas drawString: range second printString at: (plot left-60)@plot top font: TextStyle defaultFont color: color.
 canvas drawString: range first printString at: (plot left-60)@(plot bottom-16) font: TextStyle defaultFont color: color.
 zero := plot bottom - ((0-range first) / (range second-range first) * plot height).
 canvas line: plot left@zero to: plot right@zero width: 1 color: Color lightGray.
 1 to: rows size do: [:i |
 p := self pointAt: i.
 mode = #bar ifTrue: [box := ((p x - (plot width/rows size*0.3))@(p y min: zero)) corner: ((p x + (plot width/rows size*0.3))@(p y max: zero)).
 canvas fillRectangle: box color: (selection=i ifTrue: [Color yellow] ifFalse: [Color r: 0.12 g: 0.72 b: 0.65])]
 ifFalse: [previous ifNotNil: [canvas line: previous to: p width: 3 color: Color cyan]. canvas fillOval: ((p-4) extent: 8@8) color: (selection=i ifTrue: [Color yellow] ifFalse: [Color cyan])].
 rows size <= 10 ifTrue: [canvas drawString: (rows at: i) first at: p x-12@(plot bottom+8) font: TextStyle defaultFont color: color].
 previous := p]].
 canvas drawString: status at: origin+(25@605) font: TextStyle defaultFont color: color.
 selection > 0 ifTrue: [canvas drawString: ((rows at: selection) first, ' / ', (headers at: series), ' = ', ((rows at: selection) at: series) printString) at: origin+(25@630) font: TextStyle defaultFont color: Color yellow]
Where to run this

File in csv-charts-05.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
| app |
app := LSCSVChart new stage: 5; openInWorld.
app lines.
Expected result

The chart can switch between bars and connected line points.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Switch between bars and lines executed in native Squeak 6.1
Real Squeak 6.1 capture.

06 · Select data through mouse events

A click inside the plot identifies the category slot. The selection stores a row index, not a rounded screen value. The readout therefore uses the original parsed number.

Click near the left edge, the middle and the last bar. Clicks outside the plot do nothing. For dense datasets, exact values remain available even though category labels are intentionally omitted above ten rows to prevent overlap.

LSCSVChart >> mouseDown:
mouseDown: event
 | index |
 (stage >= 6 and: [self plotBounds containsPoint: event position]) ifTrue: [
 index := (((event position x-self plotBounds left) / self plotBounds width * rows size) floor + 1) min: rows size.
 selection := index. self changed]
Where to run this

File in csv-charts-06.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new stage: 6; openInWorld
Expected result

A clicked bar or point is highlighted yellow and its exact label/value appears below.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Select data through mouse events executed in native Squeak 6.1
Real Squeak 6.1 capture.

07 · Choose another numeric series

Column one is categorical. Next series cycles from column two through the final numeric column and wraps to column two. Selection resets because the previous readout referred to another series.

The new range is calculated from the selected column. Compare visits and signups: both show the same categories but different magnitudes. The app never combines their units into a misleading shared total.

LSCSVChart >> nextSeries
nextSeries
 series := series = headers size ifTrue: [2] ifFalse: [series+1]. selection := 0. self changed
Where to run this

File in csv-charts-07.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
| app |
app := LSCSVChart new stage: 7; openInWorld.
app lines; nextSeries.
Expected result

The signups column is selected and the y range recalculates.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Choose another numeric series executed in native Squeak 6.1
Real Squeak 6.1 capture.

08 · Handle negative and zero values

A negative-to-positive range places zero inside the plot. Drawing each bar from min(valueY,zeroY) to max(valueY,zeroY) keeps rectangles valid regardless of sign. A zero-height bar is a valid zero, not a missing record.

Load CSV reads only a file you explicitly choose and checks its size before parsing. Cancel leaves the dataset alone. There is no directory scan, background upload or external chart service.

LSCSVChart >> range
range
 | values low high |
 values := rows collect: [:row | row at: series].
 low := values min min: 0. high := values max max: 0.
 low = high ifTrue: [high := low + 1].
 ^ {low. high}
Where to run this

File in csv-charts-08.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
| app |
app := LSCSVChart new stage: 8; openInWorld.
app acceptCSV: 'day,value', String lf, 'A,-5', String lf, 'B,0', String lf, 'C,10'.
app bars.
Expected result

The chart spans −5 through 10 and draws positive and negative bars on opposite sides of zero.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Handle negative and zero values executed in native Squeak 6.1
Real Squeak 6.1 capture.

09 · Use the complete chart tool

The finished tool keeps text acceptance, validation, scaling and selection separate. Use Example to restore the initial fictional data, or load your own small CSV with one label column and numeric columns.

Numbers must consume the entire field. A string such as 1+2 is not treated as an expression. The magnitude cap also prevents enormous values from producing unusable coordinates. The practical exercise below extends the model through Smalltalk messages rather than adding a formula language.

LSCSVChart >> numericField:
numericField: field
 | stream number |
 field isEmpty ifTrue: [self error: 'A number is missing'].
 self validateNumericToken: field.
 (field allSatisfy: [:c | c isDigit or: ['.+-eE' includes: c]]) ifFalse: [self error: 'Invalid numeric field'].
 stream := field readStream. number := Number readFrom: stream.
 (stream atEnd and: [number isNumber and: [number abs <= 1000000000]]) ifFalse: [self error: 'Number is invalid or too large'].
 ^ number
LSCSVChart >> validateNumericToken:
validateNumericToken: token
 | exponentIndex exponent digits |
 token size > 40 ifTrue: [self error: 'Numeric token exceeds 40 characters'].
 exponentIndex := token asLowercase indexOf: $e.
 exponentIndex > 0 ifTrue: [
 exponent := token copyFrom: exponentIndex+1 to: token size.
 (exponent isEmpty or: [exponent size > 4]) ifTrue: [self error: 'Exponent is too long'].
 digits := (#($+ $-) includes: exponent first) ifTrue: [exponent allButFirst] ifFalse: [exponent].
 (digits isEmpty or: [(digits allSatisfy: [:c | c isDigit]) not]) ifTrue: [self error: 'Invalid exponent'].
 (Integer readFrom: exponent) abs > 100 ifTrue: [self error: 'Exponent magnitude exceeds 100']].
 ^ token
Where to run this

File in csv-charts-09.st in a practice image. It includes the complete backing class and opens this stage. To study the construction, select LSCSVChart in the Browser and compare the method below. The standalone opening block can be run with Do it after the source is installed.

Workspace · Do it after installing this checkpoint; close the previous panel first

Workspace · run after installing this checkpoint
LSCSVChart new openInWorld
Expected result

The complete editor supports accepted CSV changes, file loading, series selection, both modes and exact-value inspection.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
Use the complete chart tool executed in native Squeak 6.1
Real Squeak 6.1 capture.

Watch the workflow

These animations are captured frame sequences from genuine native Squeak executions. Actions were scripted for reproducibility. Playback is illustrative and is not a performance measurement. No animation starts until you press Play demo.

NATIVE SQUEAK CAPTURE
Turn CSV data into interactive charts native demonstration
Native mouse-down events select successive categories, then the same model changes from bars to lines. Yellow marks and exact values are drawn by Squeak.
NATIVE SQUEAK CAPTURE
Turn CSV data into interactive charts native demonstration
Switch a series, install signed values, reject invalid CSV without losing the previous chart, restore the example and switch to lines.

Practice with tested solutions

1. Summarize a numeric column

Calculate the total visits in the initial dataset.

Hint

Column two contains visits; inject:into: starts with zero.

Show a tested solution

Workspace · Print it after installing the complete application source

Exercise solution
| chart total |
chart := LSCSVChart new.
total := chart rows inject: 0 into: [:sum :row | sum + row second].
chart delete.
total
Expected

98

Download complete exercise solution

2. Find the largest category

Find the row with the greatest visits without sorting or changing the model.

Hint

Carry the best row through inject:into:.

Show a tested solution

Workspace · Print it after installing the complete application source

Exercise solution
| chart best |
chart := LSCSVChart new.
best := chart rows inject: chart rows first into: [:largest :row |
    row second > largest second ifTrue: [row] ifFalse: [largest]].
chart delete.
best first
Expected

'Thu'

Download complete exercise solution

3. Compute a two-row moving average

Produce one average for each adjacent pair. Explain why the result has one fewer value.

Hint

Average values at i and i+1. Do not label this as a calendar-time average.

Show a tested solution

Workspace · Print it after installing the complete application source

Exercise solution
| chart values averages |
chart := LSCSVChart new.
values := chart rows collect: [:row | row second].
averages := (1 to: values size - 1) collect: [:i | ((values at: i) + (values at: i + 1)) / 2].
chart delete.
averages asArray
Expected

#(16 (35/2) (43/2) (51/2))

Download complete exercise solution

Verification, cleanup and next steps

12 SUnit tests for this lesson pass, alongside all nine independent checkpoint executions and three exact exercise solutions.

The source, visible method bodies, independent stage runs and exercises were executed in stock Squeak 6.1. Additional SUnit checks cover boundaries and actual native events.

  • The four related applications pass 56 tests together in a fresh baseline image.
  • An independent review exercised real editor acceptance, native events, bounded input, request cancellation and persistence behavior; verified defects were fixed before publication.

Delete the tutorial Morph through its halo when finished. The sequencer stops stepping and the JSON browser cancels its owned worker during deletion. Saving an image is separate from saving application data.

  • Squeak 6.1 release notes
  • Installed Squeak 6.1 source — The shipped classes and selectors used by this lesson were inspected and executed in build 23976.

Explore more working examples · Return to the learning path

Scope of this example

  • A categorical label column plus one to three numeric series; at most 40 rows and 16,000 input characters. No date-axis interpolation, statistics or spreadsheet formulas.
  • Only the selected series is drawn. Values are plotted in row order, so sort the input if ordering matters. Bars and lines use the same zero-inclusive scale.
  • The fixed 880×650 native panel is intended for a desktop Squeak image. The tutorial web page itself is responsive.
  • CSV parsing supports quoted fields and escaped quotes. File decoding follows the image’s FileStream behavior; this lesson makes no promise about automatic encoding detection.
  • Before the standard numeric parser runs, numeric tokens are limited to 40 characters and exponent magnitudes to 100. This rejects tiny inputs that would otherwise demand excessive parsing work.