SystemWindow subclass: #LSWindow
 instanceVariableNames: 'fixedExtent' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Search'!

Object subclass: #LSTokenizer
 instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Search'!

Object subclass: #LSIndex
 instanceVariableNames: 'documents postings' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Search'!

Morph subclass: #LSSearchApp
 instanceVariableNames: 'index editor query results mode resultsPane statsLabel statusLabel window' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Search'!

!LSWindow methodsFor: 'tutorial'!
fixedExtent: point
 fixedExtent := point. super extent: point
! !


!LSWindow methodsFor: 'tutorial'!
extent: point
 super extent: (fixedExtent ifNil: [point])
! !


!LSTokenizer methodsFor: 'tutorial'!
isWord: char
 ^ (char >= $a and: [char <= $z]) or: [(char >= $A and: [char <= $Z]) or: [char >= $0 and: [char <= $9]]]
! !


!LSTokenizer methodsFor: 'tutorial'!
tokens: text
 | result cursor start |
 text size > 12000 ifTrue: [self error: 'Limit: 12000 characters per document'].
 result := OrderedCollection new. cursor := 1.
 [cursor <= text size] whileTrue: [
  (self isWord: (text at: cursor)) ifTrue: [
   start := cursor. [cursor <= text size and: [self isWord: (text at: cursor)]] whileTrue: [cursor := cursor + 1].
   cursor - start > 64 ifTrue: [self error: 'Limit: 64 characters per token'].
   result size >= 3000 ifTrue: [self error: 'Limit: 3000 tokens per document'].
   result addLast: {(text copyFrom: start to: cursor - 1) asLowercase. start. cursor - 1}]
  ifFalse: [cursor := cursor + 1]]. ^ result asArray
! !


!LSIndex methodsFor: 'tutorial'!
initialize
 super initialize. documents := Dictionary new. postings := Dictionary new
! !


!LSIndex methodsFor: 'tutorial'!
documents
 ^ documents deepCopy
! !


!LSIndex methodsFor: 'tutorial'!
postings
 ^ postings deepCopy
! !


!LSIndex methodsFor: 'tutorial'!
documentCount
 ^ documents size
! !


!LSIndex methodsFor: 'tutorial'!
termCount
 ^ postings size
! !


!LSIndex methodsFor: 'tutorial'!
validateId: id title: title body: body
 (id isEmpty or: [id size > 40]) ifTrue: [self error: 'ID needs 1 to 40 characters'].
 (title isEmpty or: [title size > 80]) ifTrue: [self error: 'Title needs 1 to 80 characters'].
 body size > 12000 ifTrue: [self error: 'Limit: 12000 characters per document'].
 (documents size >= 30 and: [(documents includesKey: id) not]) ifTrue: [self error: 'Limit: 30 documents']
! !


!LSIndex methodsFor: 'tutorial'!
putId: id title: title body: body
 self validateId: id title: title body: body.
 documents at: id copy put: {title copy. body copy}
! !


!LSIndex methodsFor: 'tutorial'!
loadSamples
 self putId: 'orchard' title: 'Orchard field notes' body: 'A red fox rests near the apple orchard. Blue butterflies visit the quiet garden. The gardener records bright moon flowers.'.
 self putId: 'river' title: 'River trail guide' body: 'Follow the river trail to the old bridge. A quick red fox crossed the path. The quiet garden is two miles away.'.
 self putId: 'space' title: 'Moon observatory' body: 'Tonight the blue moon rises above the observatory. Students compare moon maps and record bright stars.'.
 self putId: 'kitchen' title: 'A fictional kitchen notebook' body: 'Bake an apple tart with cinnamon. Cool the tart near a blue bowl. The orchard supplies crisp apples.'.
 self putId: 'workshop' title: 'Object workshop' body: 'Small objects exchange messages. A search index maps each term to document positions. Clear tests make changes easier.'
! !


!LSIndex methodsFor: 'tutorial'!
indexFor: aDictionary
 | built | built := Dictionary new.
 aDictionary keys asSortedCollection do: [:id | | tokens |
  tokens := LSTokenizer new tokens: (aDictionary at: id) second.
  tokens withIndexDo: [:token :position | | byDocument |
   byDocument := built at: token first ifAbsentPut: [Dictionary new].
   (byDocument at: id ifAbsentPut: [OrderedCollection new]) addLast: position]].
 ^ built
! !


!LSIndex methodsFor: 'tutorial'!
rebuild
 | rebuilt | rebuilt := self indexFor: documents. postings := rebuilt
! !


!LSIndex methodsFor: 'tutorial'!
positionsFor: term in: id
 ^ ((postings at: term ifAbsent: [Dictionary new]) at: id ifAbsent: [#()]) copy
! !


!LSSearchApp methodsFor: 'tutorial'!
initialize
 super initialize. self color: (Color fromString: '#EDF4EF'); extent: 830@600.
 index := LSIndex new. index loadSamples. self prepareIndex. query := 'red fox'. results := #(). mode := #terms.
 self label: 'Local Search Studio' at: 24@13 size: 27.
 self label: ('Checkpoint ', self stage printString, ' / 9: ', self stageTitle) at: 25@53 size: 14.
 self label: 'A tiny, explicit corpus of five fictional documents' at: 25@88 size: 13.
 editor := PluggableTextMorph on: self text: #query accept: #acceptQuery:.
 editor acceptOnCR: false; plainTextOnly: true; extent: 778@49; position: self position + (25@113). self addMorph: editor.
 self buildToolbar.
 statsLabel := self label: '' at: 25@220 size: 14.
 resultsPane := ScrollPane new color: Color white; extent: 778@286; position: self position + (25@250). self addMorph: resultsPane.
 statusLabel := self label: 'Search only this supplied corpus. No folders are scanned.' at: 25@561 size: 13.
 self showCorpus; refresh
! !


!LSSearchApp methodsFor: 'tutorial'!
prepareIndex
 index rebuild
! !


!LSSearchApp methodsFor: 'tutorial'!
label: text at: point size: size
 | label | label := StringMorph contents: text font: (TextStyle default fontOfSize: size).
 label color: (Color fromString: '#204C39'); position: self position + point. self addMorph: label. ^ label
! !


!LSSearchApp methodsFor: 'tutorial'!
button: text at: x action: selector
 | button | button := SimpleButtonMorph new label: text; target: self; actionSelector: selector; color: Color white; position: self position + (x@183). self addMorph: button
! !


!LSSearchApp methodsFor: 'tutorial'!
buttonNamed: text
 ^ self submorphs detect: [:morph | (morph isKindOf: SimpleButtonMorph) and: [morph label = text]]
! !


!LSSearchApp methodsFor: 'tutorial'!
query
 ^ query
! !


!LSSearchApp methodsFor: 'tutorial'!
query: text
 query := text asString. editor setText: query asText
! !


!LSSearchApp methodsFor: 'tutorial'!
acceptQuery: text
 query := text asString. ^ true
! !


!LSSearchApp methodsFor: 'tutorial'!
editor
 ^ editor
! !


!LSSearchApp methodsFor: 'tutorial'!
index
 ^ index
! !


!LSSearchApp methodsFor: 'tutorial'!
results
 ^ results copy
! !


!LSSearchApp methodsFor: 'tutorial'!
mode
 ^ mode
! !


!LSSearchApp methodsFor: 'tutorial'!
status
 ^ statusLabel contents
! !


!LSSearchApp methodsFor: 'tutorial'!
refresh
 statsLabel contents: (index documentCount printString, ' documents   |   ', index termCount printString, ' indexed terms   |   ', results size printString, ' results'). ^ self
! !


!LSSearchApp methodsFor: 'tutorial'!
clearResults
 resultsPane scroller submorphs do: [:each | each delete]
! !


!LSSearchApp methodsFor: 'tutorial'!
rowTitle: text at: y
 | title | title := StringMorph contents: text font: (TextStyle default fontOfSize: 17). title color: (Color fromString: '#204C39'); position: 14@y. resultsPane scroller addMorph: title
! !


!LSSearchApp methodsFor: 'tutorial'!
rowBody: text at: y
 | body | body := TextMorph new. body contents: text asText; wrapFlag: true; width: 721; position: 14@y. resultsPane scroller addMorph: body
! !


!LSSearchApp methodsFor: 'tutorial'!
showCorpus
 self clearResults.
 index documents keys asSortedCollection withIndexDo: [:id :n | | document | document := index documents at: id.
  self rowTitle: document first, '  [', id, ']' at: 12 + ((n - 1) * 112).
  self rowBody: document second at: 42 + ((n - 1) * 112)].
 statusLabel contents: 'Five bundled samples. Scroll to inspect the complete fictional corpus.'
! !


!LSSearchApp methodsFor: 'tutorial'!
showTokens
 | tokens | self clearResults. query := editor text asString.
 [tokens := LSTokenizer new tokens: query. self rowTitle: 'Lowercase tokens with original spans' at: 12.
 self rowBody: (String streamContents: [:out | tokens do: [:token | out nextPutAll: token first; nextPutAll: '  ['; nextPutAll: token second printString; nextPutAll: '..'; nextPutAll: token third printString; nextPutAll: ']'; cr]]) at: 45.
 statusLabel contents: 'Punctuation separates words. Spans still point to the original text.']
 on: Error do: [:error | statusLabel contents: error messageText]
! !


!LSSearchApp methodsFor: 'tutorial'!
showPostings
 | terms term byDocument | self clearResults. query := editor text asString.
 [terms := LSTokenizer new tokens: query. terms isEmpty ifTrue: [statusLabel contents: 'Type one word to inspect its postings.'. ^ self].
 term := terms first first. byDocument := index postings at: term ifAbsent: [Dictionary new].
 self rowTitle: 'Inverted index for: ', term at: 12.
 self rowBody: (String streamContents: [:out | byDocument keys asSortedCollection do: [:id | out nextPutAll: id; nextPutAll: ' -> token positions '; nextPutAll: (byDocument at: id) asArray printString; cr]]) at: 48.
 statusLabel contents: 'Positions are token ordinals within each document body.']
 on: Error do: [:error | statusLabel contents: error messageText]. self refresh
! !


!LSSearchApp methodsFor: 'tutorial'!
open
 window := LSWindow new model: self; setLabel: 'Local Search Studio | Squeak 6.1'.
 window addMorph: self fullFrame: (LayoutFrame fractions: (0@0 corner: 1@1)). window fixedExtent: 840@633. window openInWorld. ^ self
! !


!LSSearchApp methodsFor: 'tutorial'!
window
 ^ window
! !


!LSSearchApp class methodsFor: 'tutorial'!
open
 ^ self new open
! !


!LSSearchApp methodsFor: 'tutorial'!
stage
 ^ 3
! !


!LSSearchApp methodsFor: 'tutorial'!
stageTitle
 ^ 'Build positional postings'
! !


!LSSearchApp methodsFor: 'tutorial'!
buildToolbar
 self button: 'Corpus' at: 25 action: #showCorpus.
 self button: 'Tokens' at: 98 action: #showTokens.
 self button: 'Postings' at: 167 action: #showPostings.
! !

