Last active
November 28, 2024 01:45
-
-
Save jmsdnns/0d0b9d07793db0c8d6ef9399a66cc313 to your computer and use it in GitHub Desktop.
Simple demonstration of streaming chunks to a bubbletea TUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"time" | |
"github.com/charmbracelet/bubbles/viewport" | |
tea "github.com/charmbracelet/bubbletea" | |
) | |
const chunkSize = 256 // Read 256 bytes at a time | |
type model struct { | |
readChannel chan tea.Msg | |
file *os.File | |
content string | |
viewport viewport.Model | |
isDone bool | |
} | |
type ( | |
chunkMsg string | |
errorMsg error | |
doneMsg struct{} | |
) | |
func newModel(filename string, channel chan tea.Msg) (model, error) { | |
file, err := os.Open(filename) | |
if err != nil { | |
return model{}, err | |
} | |
return model{ | |
viewport: viewport.New(80, 20), | |
readChannel: channel, | |
file: file, | |
}, nil | |
} | |
func (m model) Init() tea.Cmd { | |
// return m.readNextChunk | |
go m.sendNextChunk() | |
return nil | |
} | |
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { | |
var ( | |
cmd tea.Cmd | |
cmds []tea.Cmd | |
) | |
switch msg := msg.(type) { | |
case tea.KeyMsg: | |
if msg.String() == "q" || msg.String() == "ctrl+c" { | |
return m, tea.Quit | |
} | |
case tea.WindowSizeMsg: | |
m.viewport.Width = msg.Width | |
m.viewport.Height = msg.Height | |
case chunkMsg: | |
m.content += string(msg) | |
m.viewport.SetContent(m.content) | |
if !m.isDone { | |
cmds = append(cmds, m.readNextChunk) | |
} | |
case errorMsg: | |
m.content += "\nError: " + msg.Error() | |
m.viewport.SetContent(m.content) | |
return m, tea.Quit | |
case doneMsg: | |
m.isDone = true | |
m.content += "\n\nDone reading file. Press 'q' to quit." | |
m.viewport.SetContent(m.content) | |
} | |
m.viewport, cmd = m.viewport.Update(msg) | |
cmds = append(cmds, cmd) | |
return m, tea.Batch(cmds...) | |
} | |
func (m model) View() string { | |
return m.viewport.View() | |
} | |
func (m model) readNextChunk() tea.Msg { | |
buffer := make([]byte, chunkSize) | |
n, err := m.file.Read(buffer) | |
if err == io.EOF { | |
m.file.Close() | |
return doneMsg{} | |
} | |
if err != nil { | |
return errorMsg(err) | |
} | |
time.Sleep(200 * time.Millisecond) | |
return chunkMsg(buffer[:n]) | |
} | |
func (m model) sendNextChunk() { | |
defer close(m.readChannel) | |
defer m.file.Close() | |
for { | |
buffer := make([]byte, chunkSize) | |
n, err := m.file.Read(buffer) | |
if err == io.EOF { | |
m.readChannel <- doneMsg{} | |
return | |
} | |
if err != nil { | |
m.readChannel <- errorMsg(err) | |
return | |
} | |
time.Sleep(200 * time.Millisecond) | |
m.readChannel <- chunkMsg(buffer[:n]) | |
} | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Please provide a filename") | |
os.Exit(1) | |
} | |
channel := make(chan tea.Msg) | |
m, err := newModel(os.Args[1], channel) | |
if err != nil { | |
log.Fatal(err) | |
} | |
p := tea.NewProgram(&m, tea.WithAltScreen()) | |
// Handle channel messages in a goroutine | |
go func() { | |
for msg := range channel { | |
p.Send(msg) | |
} | |
}() | |
if _, err := p.Run(); err != nil { | |
log.Fatal(err) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The moonlight filtered through the trees, casting long shadows across the forest floor. A gentle breeze stirred the leaves, making them dance like tiny emerald butterflies. In the distance, a dog howled at the rising moon, its voice echoing through the valley. The old oak tree stood tall and proud, its gnarled branches reaching toward the heavens. She picked up the delicate seashell, listening to the faint whisper of the ocean trapped within. The smell of fresh coffee filled the room, warming the air with its rich aroma. On the edge of the cliff, the waves crashed relentlessly against the rocks below. The clock ticked away in the silence, each second stretching into eternity. He ran his fingers through the pages of the ancient book, as if searching for a forgotten secret. The house was quiet except for the faint hum of the refrigerator in the kitchen. A single cloud drifted lazily across the sky, its shape constantly shifting. The scent of freshly baked bread wafted through the air, making his stomach growl with hunger. She smiled as the first raindrop hit her face, a sign that the storm was near. The cat sat perched on the windowsill, watching the world outside with disinterested eyes. The sound of footsteps echoed through the empty hallway, a reminder that someone had been there before. A small child’s laughter rang out, pure and innocent, as it bounced off the walls of the playground. The sound of the river was soothing, its steady flow a reminder of nature’s unhurried rhythm. He could hear the faint rustling of the wind as it moved through the tall grass, almost like a whisper. The streetlight flickered for a moment before settling into a steady glow, casting its light across the quiet street. The distant hum of traffic was a constant undercurrent, like the pulse of a city that never truly slept. She touched the old, worn leather of the journal, feeling the stories held within its pages. The fog rolled in slowly, swallowing up the landscape in its thick, ghostly embrace. A bird’s song broke the stillness, its melody sharp and clear against the backdrop of silence. The fire crackled softly, its warmth spreading through the room like a comforting embrace. He looked out over the city from the rooftop, the lights twinkling below like stars scattered on the earth. The cold wind cut through his coat, biting at his skin as he trudged through the snow. A soft knock on the door broke the silence, and he hesitated before answering. The leaves were turning shades of gold and amber, signaling the arrival of autumn. The old wooden bridge creaked under his feet as he crossed over the river, its surface slick with moss. Her fingers traced the outline of the painting, each brushstroke a memory frozen in time. The sound of a distant bell could be heard, marking the passage of time in a town that never changed. The sky was a perfect shade of blue, unblemished by clouds or smog, stretching endlessly above. The ground beneath her feet was soft, the scent of damp earth filling the air after the rain. He stepped into the quiet room, the only sound the soft shuffle of his shoes on the hardwood floor. The clock on the wall ticked away the seconds, each one a tiny eternity in the stillness of the night. The garden was alive with color, the flowers blooming in wild abandon despite the late season. A lone wolf stood on the edge of the forest, its eyes glowing in the moonlight as it stared out into the open field. The old man sat by the window, watching the world pass by with a faraway look in his eyes. The stars twinkled above like a million tiny diamonds, scattered across the velvet sky. She closed the door softly behind her, leaving the noise of the city far behind. The kitchen smelled of garlic and onions, the promise of a delicious meal hanging in the air. He leaned against the fence, watching the cows graze lazily in the field as the sun set behind them. The rustling of the leaves was the only sound that accompanied her walk through the forest. A low hum filled the air as the train pulled into the station, its arrival anticipated by all who waited. The snowflakes drifted down gently, each one unique and delicate as it melted on the warm ground. She hummed a tune as she worked, the melody light and carefree as it danced in the air around her. The sound of rain against the roof was soothing, a rhythmic patter that lulled him to sleep. The scent of lavender and rosemary filled the room, a comforting reminder of home. He reached for the old key, its metal cold and worn smooth by years of use. The waves lapped gently at the shore, their rhythm slow and deliberate as they kissed the sand. The orange glow of the sunset bathed everything in a warm, golden light. A sudden gust of wind caught the edge of the umbrella, nearly ripping it from his hands. She closed her eyes and listened, letting the symphony of sounds from the forest fill her senses. The old house creaked and groaned as the wind howled through the cracks in the walls. The path was lined with wildflowers, their bright colors adding a splash of life to the otherwise dull surroundings. He sat at the bar, swirling the glass of whiskey in his hand, lost in thought. The distant sound of children playing echoed through the neighborhood, a sound of life and energy. She ran her hand through her hair, the strands slipping between her fingers like water. The lights of the carnival flickered in the distance, a beacon of color in the dark. He tightened his grip on the rope, his heart pounding as he scaled the cliff face. The leaves crunched beneath his boots as he walked through the autumn forest, a crisp chill in the air. A butterfly flitted past, its delicate wings shimmering in the sunlight like stained glass. The smell of fresh cut grass hung in the air, mingling with the earthy scent of the nearby woods. The distant mountains stood proud and imposing, their peaks shrouded in a veil of mist. She wrapped the scarf tightly around her neck, the cold air biting at her cheeks. The dog lay curled up by the fire, its fur glowing in the warmth of the flames. The river wound its way through the valley, its water clear and sparkling under the afternoon sun. The old radio crackled to life, filling the room with the sound of a soft jazz tune. He took a deep breath, filling his lungs with the crisp mountain air, feeling rejuvenated. The sky was painted in hues of pink and orange as the sun began its descent below the horizon. She ran her fingers along the railing, the cool metal smooth beneath her touch. The scent of fresh paint filled the room, mingling with the faint odor of turpentine. A single star blinked into existence in the twilight sky, a tiny pinprick of light in the vast expanse. He wandered through the forest, the leaves crunching beneath his boots as he went deeper into the trees. The warmth of the coffee mug seeped into his hands, offering a small comfort in the chilly room. The train whistle blew in the distance, a long, mournful sound that carried across the quiet town. A family of deer stood at the edge of the woods, their eyes watching him carefully before they bolted into the trees. The shadows grew longer as the day slipped away, the last rays of sunlight casting a warm glow on everything they touched. She dipped her toes into the cool water, feeling the soft pull of the current as it flowed around her. The scent of pine and cedar hung in the air, earthy and grounding in the quiet wilderness. He pulled his jacket tighter around him as the wind picked up, howling through the empty streets. The soft glow of candlelight illuminated the room, casting flickering shadows on the walls. The distant rumble of thunder signaled the approaching storm, filling the air with a sense of anticipation. She watched the flickering flames in the fireplace, mesmerized by their dance as they crackled and popped. The scent of rain was in the air, the earth waiting to be soaked by the impending storm. He scribbled a note on the back of an envelope, his handwriting hurried but deliberate. The soft hum of the refrigerator was the only sound that filled the quiet apartment. A lone figure stood on the hilltop, silhouetted against the fading light of day. The smell of fresh flowers drifted through the open window, mixing with the cool evening air. The snow fell in heavy, thick flakes, blanketing the world in a soft, silent white. He leaned against the railing, watching the boats drift by on the river, their sails billowing in the wind. The city lights twinkled in the distance, a reflection of the stars above. The air was thick with the scent of jasmine, the flowers blooming in profusion along the path. She ran her fingers along the smooth stones of the riverbed, feeling their cool surface against her skin. The wind rustled the pages of the open book, flipping them over as if eager to read ahead. The waves crashed against the shore with a force that seemed to shake the very earth. He stood at the window, watching the streetlights flicker on one by one as night fell. The distant sound of a train whistle echoed in the air, a lonely sound in the quiet night. The forest was eerily silent, save for the occasional snap of a twig underfoot. She breathed in deeply, the crisp scent of the autumn air filling her lungs. The old lamp flickered to life, casting a soft glow across the room. The birds chirped merrily in the trees, their songs filling the air with cheer. He pulled the blanket up over his shoulders, the warmth of it comforting against the coolness of the evening. The sound of footsteps echoed in the empty hallway, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment