package session import ( "encoding/json" "errors" "fmt" "os" "git.andreafazzi.eu/andrea/probo/pkg/models" "git.andreafazzi.eu/andrea/probo/pkg/store/file" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/spinner" btTable "github.com/charmbracelet/bubbles/table" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/glamour" "github.com/charmbracelet/huh" "github.com/charmbracelet/lipgloss" "github.com/d5/tengo/v2" "github.com/d5/tengo/v2/stdlib" foam "github.com/remogatto/sugarfoam" "github.com/remogatto/sugarfoam/components/form" "github.com/remogatto/sugarfoam/components/group" "github.com/remogatto/sugarfoam/components/header" "github.com/remogatto/sugarfoam/components/help" "github.com/remogatto/sugarfoam/components/statusbar" "github.com/remogatto/sugarfoam/components/table" "github.com/remogatto/sugarfoam/components/viewport" "github.com/remogatto/sugarfoam/layout" "github.com/remogatto/sugarfoam/layout/tiled" ) var mockSession = ` {"participants":[{"Attributes":{"class":"Math 101A"},"created_at":"2024-04-03T09:22:11.201142494+02:00","firstname":"THOMAS","id":"1024758d-0dba-4bec-aaab-339e87a0649b","lastname":"MANN","token":"427628","updated_at":"2024-05-27T13:48:50.096492274+02:00"},{"Attributes":{"class":"Math 101A"},"created_at":"2024-04-04T10:23:12.203143495+02:00","firstname":"JAMES","id":"f3c5a7bd-6fda-4bce-bbbb-333e88a0650c","lastname":"BROWN","token":"428629","updated_at":"2024-05-27T13:48:50.075089555+02:00"},{"Attributes":{"class":"Math 101A"},"created_at":"2024-04-05T11:24:13.204144496+02:00","firstname":"LUCY","id":"g4d6c8cd-7eda-4cce-cccc-444e89a0661d","lastname":"DOE","token":"429630","updated_at":"2024-05-27T13:48:50.079134348+02:00"}], "quizzes": [{"CorrectPos":0,"answers":[{"created_at":"2024-05-27T13:55:26.448679335+02:00","id":"6771592e-4e2c-45f1-b14f-91f943a5616b","text":"3 + 1 = 1 + 3","updated_at":"2024-05-27T13:55:26.448679428+02:00"},{"created_at":"2024-05-27T13:55:26.448681412+02:00","id":"bad7db2a-f5be-4f22-879a-fd783bb1c0a9","text":"3 - 1 = 1 - 3","updated_at":"2024-05-27T13:55:26.448681456+02:00"},{"created_at":"2024-05-27T13:55:26.448683251+02:00","id":"8ae29e51-65a7-4618-8074-58ee90c4fb83","text":"3 / 2 = 2 / 3","updated_at":"2024-05-27T13:55:26.448683289+02:00"},{"created_at":"2024-05-27T13:55:26.448685048+02:00","id":"7d2a9491-338d-4274-9e62-3d2641788777","text":"-3 + 1 = -1 + 3","updated_at":"2024-05-27T13:55:26.448685085+02:00"}],"correct":{"created_at":"2024-05-27T13:55:26.448679335+02:00","id":"6771592e-4e2c-45f1-b14f-91f943a5616b","text":"3 + 1 = 1 + 3","updated_at":"2024-05-27T13:55:26.448679428+02:00"},"created_at":"2024-05-27T13:49:24.170080837+02:00","hash":"","id":"6a21d3fa-d63c-4acf-9238-551692ed74c4","question":{"created_at":"2024-05-27T13:55:26.448673273+02:00","id":"bf19c1f1-6896-4ca2-b7dc-1657adcce4cd","text":"In #mathematics, for the commutative property of addition, we have\nthat:","updated_at":"2024-05-27T13:55:26.448673633+02:00"},"tags":["#mathematics"],"type":0,"updated_at":"2024-05-27T13:55:26.448701931+02:00"},{"CorrectPos":0,"answers":[{"created_at":"2024-05-27T13:55:26.449222989+02:00","id":"37f741c2-12de-4463-b6c0-42b8b5249e7a","text":"3 * (4 + 5) = 3 * 4 + 3 * 5","updated_at":"2024-05-27T13:55:26.449223079+02:00"},{"created_at":"2024-05-27T13:55:26.44922686+02:00","id":"c60b1b81-5e16-4401-831c-d9fffba1d1eb","text":"6 * (2 - 3) = 6 * 2 + 6 * 3","updated_at":"2024-05-27T13:55:26.449226924+02:00"},{"created_at":"2024-05-27T13:55:26.449230299+02:00","id":"fb0ba30c-1e4e-41a1-9630-7f18aa24a6db","text":"7 * (8 + 2) = 7 * 8 - 7 * 2","updated_at":"2024-05-27T13:55:26.449230351+02:00"},{"created_at":"2024-05-27T13:55:26.449233993+02:00","id":"0cfd6fbb-7aac-4d35-aa17-3e62f5297c68","text":"2 * (1 + 2) = (- 2) * 1 - 4","updated_at":"2024-05-27T13:55:26.449234055+02:00"}],"correct":{"created_at":"2024-05-27T13:55:26.449222989+02:00","id":"37f741c2-12de-4463-b6c0-42b8b5249e7a","text":"3 * (4 + 5) = 3 * 4 + 3 * 5","updated_at":"2024-05-27T13:55:26.449223079+02:00"},"created_at":"2024-05-27T13:49:24.173550821+02:00","hash":"","id":"40aa188a-46c6-4f26-9a1e-4d5a028ba367","question":{"created_at":"2024-05-27T13:55:26.449216807+02:00","id":"723acb0a-5c60-4062-8615-fd3494220b4d","text":"In #mathematics, the distributive property allows us to multiply a sum\nor difference by a single number. Which statement correctly applies\nthis property?","updated_at":"2024-05-27T13:55:26.449216918+02:00"},"tags":["#mathematics"],"type":0,"updated_at":"2024-05-27T13:55:26.449281612+02:00"},{"CorrectPos":0,"answers":[{"created_at":"2024-05-27T13:55:26.449440615+02:00","id":"11be2252-45f0-44c1-a9f0-19dcdcd45b68","text":"1","updated_at":"2024-05-27T13:55:26.449440713+02:00"},{"created_at":"2024-05-27T13:55:26.449452222+02:00","id":"971fbf3b-27b1-4b67-9636-ac681056ce62","text":"0","updated_at":"2024-05-27T13:55:26.449452291+02:00"},{"created_at":"2024-05-27T13:55:26.449455664+02:00","id":"d35104b1-37f9-4312-aa21-a470650cb4dc","text":"2","updated_at":"2024-05-27T13:55:26.44945573+02:00"},{"created_at":"2024-05-27T13:55:26.449459322+02:00","id":"220077d2-1994-40ed-8d28-f39d2ebb8dcf","text":"3","updated_at":"2024-05-27T13:55:26.449459397+02:00"}],"correct":{"created_at":"2024-05-27T13:55:26.449440615+02:00","id":"11be2252-45f0-44c1-a9f0-19dcdcd45b68","text":"1","updated_at":"2024-05-27T13:55:26.449440713+02:00"},"created_at":"2024-05-27T13:49:24.175865713+02:00","hash":"","id":"f9fab318-3373-4729-a80f-b681460824e3","question":{"created_at":"2024-05-27T13:55:26.449432971+02:00","id":"af7d973a-a83c-4a18-ac36-92ab6442ef07","text":"In #mathematics, certain numbers have special properties. Identify the\nidentity element for multiplication among the options given:","updated_at":"2024-05-27T13:55:26.449433136+02:00"},"tags":["#mathematics"],"type":0,"updated_at":"2024-05-27T13:55:26.449476666+02:00"}]}` type SessionModel struct { // UI form *form.Model viewport *viewport.Model table *table.Model group *group.Model help *help.Model statusBar *statusbar.Model spinner spinner.Model // Layout document *layout.Layout // Key bindings bindings *keyBindings // store store *file.SessionFileStore lenStore int result []any // json InputJson string Result string // session session *models.Session // markdown mdRenderer *glamour.TermRenderer // filter file scriptFilePath string state int } func New(path string, stdin string) *SessionModel { form := form.New( form.WithGroups(huh.NewGroup( huh.NewInput(). Key("sessionTitle"). Title("Session title"). Description("Enter the title of the session"). Validate(func(str string) error { if str == "" { return errors.New("You must set a session name!") } return nil }), ))) formBinding := huh.NewDefaultKeyMap() formBinding.Input.Next = key.NewBinding(key.WithKeys("down"), key.WithHelp("down", "next")) formBinding.Input.Prev = key.NewBinding(key.WithKeys("up"), key.WithHelp("up", "prev")) formBinding.Confirm.Next = key.NewBinding(key.WithKeys("down"), key.WithHelp("down", "next")) formBinding.Confirm.Prev = key.NewBinding(key.WithKeys("up"), key.WithHelp("up", "prev")) form.WithShowHelp(false).WithTheme(huh.ThemeDracula()).WithKeyMap(formBinding) viewport := viewport.New() table := table.New(table.WithRelWidths(20, 10, 25, 25, 20)) table.Model.SetColumns([]btTable.Column{ {Title: "UUID", Width: 20}, {Title: "Token", Width: 20}, {Title: "Lastname", Width: 20}, {Title: "Firstname", Width: 20}, {Title: "Class", Width: 20}, }) group := group.New( group.WithItems(form, table, viewport), group.WithLayout( layout.New( layout.WithStyles(&layout.Styles{Container: lipgloss.NewStyle().Padding(1, 1)}), layout.WithItem(form), layout.WithItem(tiled.New(table, viewport)), ), ), ) bindings := newBindings(group) statusBar := statusbar.New(bindings) s := spinner.New( spinner.WithStyle( lipgloss.NewStyle().Foreground(lipgloss.Color("265"))), ) s.Spinner = spinner.Dot header := header.New( header.WithContent( lipgloss.NewStyle(). Bold(true). Border(lipgloss.NormalBorder(), false, false, true, false). Render("✨ Create session ✨"), ), ) help := help.New( bindings, help.WithStyles(&foam.Styles{NoBorder: lipgloss.NewStyle().Padding(1, 1)})) document := layout.New( layout.WithStyles(&layout.Styles{Container: lipgloss.NewStyle().Margin(1)}), layout.WithItem(header), layout.WithItem(group), layout.WithItem(help), layout.WithItem(statusBar), ) renderer, err := glamour.NewTermRenderer( glamour.WithStandardStyle("dracula"), glamour.WithWordWrap(80), ) if err != nil { panic(err) } return &SessionModel{ form: form, table: table, viewport: viewport, group: group, statusBar: statusBar, spinner: s, document: document, mdRenderer: renderer, bindings: bindings, help: help, scriptFilePath: path, InputJson: stdin, } } func (m *SessionModel) Init() tea.Cmd { var cmds []tea.Cmd cmds = append(cmds, m.group.Init(), m.loadStore(), m.spinner.Tick) m.group.Focus() return tea.Batch(cmds...) } func (m *SessionModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { var cmds []tea.Cmd switch msg := msg.(type) { case tea.WindowSizeMsg: m.handleWindowSize(msg) case tea.KeyMsg: switch { case key.Matches(msg, m.bindings.quit): cmds = append(cmds, tea.Quit) } case storeLoadedMsg: cmds = append(cmds, m.handleStoreLoaded(msg)) case scriptExecutedMsg: m.handleScriptExecuted(msg) case errorMsg: m.handleError(msg) m.state = ErrorState } cmds = m.handleState(msg, cmds) return m, tea.Batch(cmds...) } func (m *SessionModel) View() string { return m.document.View() } func (m *SessionModel) marshalJSON() (string, error) { session, err := m.createSession() if err != nil { return "", err } resultJson, err := json.Marshal(session) if err != nil { return "", err } return string(resultJson), nil } func (m *SessionModel) executeScript() tea.Cmd { return func() tea.Msg { if m.scriptFilePath == "" { return nil } sessionJson, err := json.Marshal(models.Session{Exams: map[string]*models.Exam{}}) if err != nil { panic(err) } script, err := os.ReadFile(m.scriptFilePath) if err != nil { panic(err) } s := tengo.NewScript(script) s.SetImports(stdlib.GetModuleMap("fmt", "json", "rand", "times")) _ = s.Add("input", m.InputJson) _ = s.Add("output", string(sessionJson)) c, err := s.Compile() if err != nil { panic(err) } if err := c.Run(); err != nil { panic(err) } return scriptExecutedMsg{fmt.Sprintf("%s", c.Get("output"))} } } func (m *SessionModel) createSession() (*models.Session, error) { m.session.Title = m.form.GetString("sessionTitle") session, err := m.store.Storer.Create(m.session) if err != nil { return nil, err } return session, err } func (m *SessionModel) showErrorOnStatusBar(err error) { m.statusBar.SetContent( stateFormats[ErrorState][0], fmt.Sprintf(stateFormats[ErrorState][1], err), stateFormats[ErrorState][2], ) } func (m *SessionModel) updateTableContent(session *models.Session) { rows := make([]btTable.Row, 0) for _, exam := range session.Exams { rows = append(rows, btTable.Row{ exam.Participant.ID, exam.Participant.Token, exam.Participant.Lastname, exam.Participant.Firstname, exam.Participant.Attributes.Get("class"), }) } m.table.SetRows(rows) } func (m *SessionModel) updateViewportContent(session *models.Session) { if len(m.table.Rows()) == 0 { panic(errors.New("Session have not exams")) } currentUUID := m.table.SelectedRow()[0] currentExam := session.Exams[currentUUID] if currentExam == nil { panic("Current token is not associate to any exam!") } // md, err := currentExam.ToMarkdown() // if err != nil { // m.showErrorOnStatusBar(err) // } // data, err := currentExam.Marshal() // if err != nil { // panic(err) // } // result, err := m.mdRenderer.Render(md) // if err != nil { // m.showErrorOnStatusBar(err) // } // m.viewport.SetContent(result) // m.viewport.SetContent(string(data)) m.viewport.SetContent(mockSession) } func (m *SessionModel) createMDRenderer() *glamour.TermRenderer { renderer, err := glamour.NewTermRenderer( glamour.WithStandardStyle("dracula"), glamour.WithWordWrap(m.viewport.GetWidth()), ) if err != nil { panic(err) } return renderer } func (m *SessionModel) handleWindowSize(msg tea.WindowSizeMsg) { m.group.SetSize(msg.Width, msg.Height) m.document.SetSize(msg.Width, msg.Height) m.mdRenderer = m.createMDRenderer() } func (m *SessionModel) handleError(msg tea.Msg) { err := msg.(errorMsg) m.statusBar.SetContent( stateFormats[ErrorState][0], fmt.Sprintf(stateFormats[ErrorState][1], err.error), stateFormats[ErrorState][2], ) } func (m *SessionModel) handleScriptExecuted(msg tea.Msg) { session := new(models.Session) jsonData := []byte(msg.(scriptExecutedMsg).result) err := json.Unmarshal(jsonData, &session) if err != nil { panic(err) } m.session = session m.updateTableContent(session) m.updateViewportContent(session) m.state = BrowseState } func (m *SessionModel) handleStoreLoaded(msg tea.Msg) tea.Cmd { storeMsg := msg.(storeLoadedMsg) m.store = storeMsg.store m.lenStore = len(m.store.ReadAll()) return m.executeScript() } func (m *SessionModel) handleState(msg tea.Msg, cmds []tea.Cmd) []tea.Cmd { _, cmd := m.group.Update(msg) if m.state == LoadingStoreState { return m.updateSpinner(msg, cmd, cmds) } if m.form.State == huh.StateCompleted { var err error m.Result, err = m.marshalJSON() if err != nil { panic(err) } cmds = append(cmds, tea.Quit) } if len(m.form.Errors()) > 0 { m.state = ErrorState for _, err := range m.form.Errors() { m.showErrorOnStatusBar(err) } } else { m.state = BrowseState } if m.state == BrowseState { m.updateViewportContent(m.session) } if m.state != ErrorState { m.statusBar.SetContent( stateFormats[BrowseState][0], fmt.Sprintf(stateFormats[BrowseState][1], m.lenStore, len(m.session.Exams)), stateFormats[BrowseState][2], ) } cmds = append(cmds, cmd) return cmds } func (m *SessionModel) updateSpinner(msg tea.Msg, cmd tea.Cmd, cmds []tea.Cmd) []tea.Cmd { m.spinner, cmd = m.spinner.Update(msg) m.statusBar.SetContent(fmt.Sprintf(stateFormats[m.state][0], m.spinner.View()), stateFormats[m.state][1], stateFormats[m.state][2]) cmds = append(cmds, cmd) return cmds } func (m *SessionModel) loadStore() tea.Cmd { return func() tea.Msg { sStore, err := file.NewDefaultSessionFileStore() if err != nil { panic(err) } return storeLoadedMsg{sStore} } }