dymokomi/luced-message
Source of release 0.5.0
## The mailbox sidebar: each source's title, then its folders as a tree (indented by
## depth), Inbox first, each with its unread count. Picking a folder shows its
## messages; picking a source's title shows its Inbox.
from luce_ui.ui import ListView, ListItem, IconKind, Font
from sources import Source
## One row of the sidebar.
struct Entry:
let source: int
## Empty for a source's title row.
let folder: str
let role: str
pub class Sidebar:
pub let view: ListView
var entries: list[Entry] = []
## The folder last reported to `on_pick`, by source and path: a row index would go
## stale when the rows are rebuilt.
var shown_source: int = -1
var shown_folder: str = ""
## Called with the source's position and the folder's path when a folder is picked.
pub var on_pick: func(int, str) -> unit!? = none
pub func init(self, font: Font) -> unit!:
self.view = ListView([], font = font)
## Rebuild the rows from every source's folders, keeping the selection.
pub func refresh(self, sources: list[Source]) -> unit!:
let selected = self.selected()
var items: list[ListItem] = []
var entries: list[Entry] = []
for (position, source) in sources.indexed():
items.append(ListItem(text = source.title().upper(), icon = IconKind.folder_open))
entries.append(Entry(source = position, folder = "", role = ""))
let folders = source.folders() catch failure:
_ = failure
recover []
for folder in folders:
let count = f" {folder.unseen}" if folder.unseen > 0 else ""
items.append(ListItem(text = " ".repeat(folder.depth + 1) + folder.name + count, icon = IconKind.folder))
entries.append(Entry(source = position, folder = folder.path, role = folder.role))
self.entries = entries
self.view.set_items(items)
if let previous = selected:
for (at, entry) in entries.indexed():
if entry.source == previous.source and entry.folder == previous.folder:
self.view.select(at)
## The picked row, if any.
func selected(self) -> Entry?:
let at = self.view.selected_index()
if at < 0 or at >= self.entries.length:
return none
return self.entries[at]
## Pick source `source`'s folder `folder` (its Inbox when empty).
pub func pick(self, source: int, folder: str) -> unit!:
for (at, entry) in self.entries.indexed():
if entry.source == source and ((folder != "" and entry.folder == folder) or (folder == "" and entry.role == "inbox")):
self.view.select(at)
return
## Tell `on_pick` when another folder is selected; called every frame. It compares
## folders, not rows, so a refresh between a pick and this poll cannot hide the pick.
pub func poll(self) -> unit!:
let entry = self.selected() else return
if entry.folder == "":
# A title row stands for its Inbox.
self.pick(entry.source, "")
return
if entry.source == self.shown_source and entry.folder == self.shown_folder:
return
self.shown_source = entry.source
self.shown_folder = entry.folder
if let pick = self.on_pick:
pick(entry.source, entry.folder)