garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/notes.rs

raw

//! Notes: write things down. The list of notes, those pinned first and
//! then the newest, each with the day it changed, and a field that finds
//! notes by what they say; beside it, on a wide window, the note being
//! written with the on-screen keyboard (or a physical one). Each note is a
//! file in the app's own folder; it is saved half a second after the last
//! key, and when it is left. A note left empty goes. Which notes are
//! pinned is a small file in the same folder, [`PINS`].

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;

use pinnacle_locale::{Date, t, tf};
use pinnacle_rt::fs;
use pinnacle_rt::locale::{self, Zone};

use pinnacle_ui::layout::notes;
use pinnacle_ui::{App, Event};
use pinnacle_view::{Clipboard, IntoView, Screen, Signal, View, el, signal};

/// Its own folder, wherever the system keeps it (in the data vault once open).
const FOLDER: &str = "app:";
/// How long after the last key a note is saved.
const SAVE_AFTER_MS: u64 = 500;
/// The names of the notes pinned to the top, one a line, in [`FOLDER`]:
/// there only while one is pinned. Its name starts with a dot, which no
/// note's does.
const PINS: &str = "app:/.pinned";

struct Note {
    /// Its file's name in [`FOLDER`].
    name: String,
    text: String,
    /// When it changed, seconds since 1970; 0 when not known, and
    /// `u64::MAX` for a new one not saved yet.
    modified: u64,
    pinned: bool,
}

impl Note {
    fn path(&self) -> String {
        alloc::format!("{FOLDER}/{}", self.name)
    }

    /// Its first line, or what stands in for one.
    fn title(&self) -> &str {
        match self.text.lines().find(|l| !l.trim().is_empty()) {
            Some(line) => line.trim(),
            None => t("New note"),
        }
    }
}

/// Every note in the folder, those pinned first, and among each the one
/// changed last first.
fn load() -> Vec<Note> {
    let pins = fs::read_string(PINS).unwrap_or_default();
    let mut notes: Vec<Note> = fs::list(FOLDER)
        .unwrap_or_default()
        .into_iter()
        .filter(|name| !name.ends_with('/') && !name.starts_with('.'))
        .filter_map(|name| {
            let path = alloc::format!("{FOLDER}/{name}");
            let text = String::from_utf8(fs::read(&path)?).ok()?;
            let modified = fs::stat(&path).map_or(0, |s| s.modified);
            let pinned = pins.lines().any(|l| l == name);
            Some(Note {
                name,
                text,
                modified,
                pinned,
            })
        })
        .collect();
    sort(&mut notes);
    notes
}

/// Pinned first, then the one changed last.
fn sort(notes: &mut [Note]) {
    notes.sort_by(|a, b| {
        b.pinned
            .cmp(&a.pinned)
            .then(b.modified.cmp(&a.modified))
            .then(b.name.cmp(&a.name))
    });
}

/// Writes which notes are pinned; with none, the file goes.
fn save_pins(notes: &[Note]) {
    let names: Vec<&str> = notes
        .iter()
        .filter(|n| n.pinned)
        .map(|n| n.name.as_str())
        .collect();
    if names.is_empty() {
        if fs::exists(PINS) {
            fs::remove(PINS);
        }
    } else if !fs::write(PINS, names.join("\n").as_bytes()) {
        pinnacle_rt::println!("notes: could not keep the pins");
    }
}

/// A name no note has: the next number.
fn new_name(notes: &[Note]) -> String {
    let next = notes
        .iter()
        .filter_map(|n| n.name.parse::<u64>().ok())
        .max()
        .map_or(1, |n| n + 1);
    alloc::format!("{next}")
}

/// Writes the note out; an empty one is removed instead.
fn save(note: &Note) {
    if note.text.trim().is_empty() {
        fs::remove(&note.path());
    } else if !fs::write(&note.path(), note.text.as_bytes()) {
        pinnacle_rt::println!("notes: could not save {}", note.name);
    }
}

/// What a tap asked for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tap {
    New,
    Open(usize),
    Back,
    Copy,
    Pin,
    Delete,
}

/// How many lines with something on them, said.
fn lines_said(text: &str) -> String {
    match text.lines().filter(|l| !l.trim().is_empty()).count() {
        0 | 1 => String::from(t("One line")),
        n => tf("{} lines", &[&alloc::format!("{n}")]),
    }
}

/// The open note's title: its first line, or what stands in for one.
fn title_of(text: &str) -> String {
    let note = Note {
        name: String::new(),
        text: text.into(),
        modified: 0,
        pinned: false,
    };
    note.title().into()
}

/// When a note changed, as the language writes it, in the local time:
/// the time for today, the day and month this year, else the whole date.
/// Nothing when it is not known.
fn changed(seconds: u64, zone: &Zone) -> String {
    if seconds == 0 || seconds == u64::MAX {
        return String::new();
    }
    let (then, _) = zone.civil(seconds as i64);
    let day = Date {
        year: then.year,
        month: then.month,
        day: then.day,
    };
    match locale::now_in(zone) {
        Some((now, _)) if (now.year, now.month, now.day) == (then.year, then.month, then.day) => {
            pinnacle_locale::time(then.hour, then.minute)
        }
        Some((now, _)) if now.year == then.year => pinnacle_locale::date_short(day),
        _ => pinnacle_locale::date(day),
    }
}

/// A button that puts `tap` in `tapped`, named for `cargo xtask`.
fn button(
    label: &'static str,
    name: String,
    variant: &'static str,
    tap: Tap,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let tapped = tapped.clone();
    el("button")
        .class("m-button")
        .attr("type", "button")
        .attr("data-variant", variant)
        .attr("data-name", name)
        .on("click", move |_| tapped.set(Some(tap)))
        .child(label)
        .into_view()
}

/// A row of the list as the search reads it: what it is found by, and
/// what it shows.
#[derive(Clone)]
struct Row {
    /// Its title and text, in lower case.
    found_by: String,
    title: String,
    /// Pinned or not, when it changed, and how many lines.
    sub: String,
    pinned: bool,
}

/// Whether `row` is found by what is in the search field.
fn found(row: &Row, query: &str) -> bool {
    let query = query.trim();
    query.is_empty() || row.found_by.contains(&query.to_lowercase())
}

/// The list of notes, those pinned first and then the newest: a title, a
/// count, a button for a new one, the search field, and a row for each
/// note it finds, the open one marked (and always there).
fn list_pane(
    notes: &[Note],
    open: Option<usize>,
    both: bool,
    zone: &Zone,
    text: &Signal<String>,
    query: &Signal<String>,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let count = match notes.len() {
        1 => String::from(t("1 note")),
        n => tf("{} notes", &[&alloc::format!("{n}")]),
    };
    let rows: Vec<Row> = notes
        .iter()
        .map(|note| {
            let mut sub = Vec::new();
            if note.pinned {
                sub.push(String::from(t("Pinned")));
            }
            let when = changed(note.modified, zone);
            if !when.is_empty() {
                sub.push(when);
            }
            sub.push(lines_said(&note.text));
            Row {
                found_by: note.text.to_lowercase(),
                title: note.title().into(),
                sub: sub.join(" · "),
                pinned: note.pinned,
            }
        })
        .collect();
    let (text, q, tapped_rows) = (text.clone(), query.clone(), tapped.clone());
    // Built again as the search changes, and only the list.
    let list = move || {
        let query = q.get();
        let mut out = Vec::new();
        for (i, row) in rows.iter().enumerate() {
            if open != Some(i) && !found(row, &query) {
                continue;
            }
            let tapped = tapped_rows.clone();
            // The open note's row follows what is typed in it.
            let (title, sub): (View, View) = if open == Some(i) {
                let (typed, lines) = (text.clone(), text.clone());
                let pinned = row.pinned;
                (
                    (move || title_of(&typed.get())).into_view(),
                    (move || {
                        let lines = lines_said(&lines.get());
                        if pinned {
                            alloc::format!("{} · {lines}", t("Pinned"))
                        } else {
                            lines
                        }
                    })
                    .into_view(),
                )
            } else {
                (row.title.clone().into_view(), row.sub.clone().into_view())
            };
            out.push(
                el("button")
                    .class("m-list-item")
                    .attr("type", "button")
                    .attr("role", "listitem")
                    .attr("data-name", alloc::format!("note-{i}"))
                    .attr("aria-current", (open == Some(i)).then_some("true"))
                    // The open one stands out, as the hand-drawn list had it.
                    .attr(
                        "style",
                        (open == Some(i)).then_some("background: var(--m-pressed)"),
                    )
                    .on("click", move |_| tapped.set(Some(Tap::Open(i))))
                    .child(
                        el("span")
                            .class("m-list-item__body")
                            .child(el("span").class("m-list-item__title").child(title))
                            .child(el("span").class("m-list-item__sub").child(sub)),
                    )
                    .into_view(),
            );
        }
        if out.is_empty() && !query.trim().is_empty() {
            out.push(
                el("p")
                    .attr(
                        "style",
                        "margin: 24px 0; text-align: center; color: var(--m-text-dim)",
                    )
                    .child(t("No note says that"))
                    .into_view(),
            );
        }
        out
    };
    let width = if both {
        "width: 360px; flex: none"
    } else {
        "flex: 1"
    };
    let mut pane = el("section")
        .attr(
            "style",
            alloc::format!("{width}; overflow-y: auto; padding: 24px 16px; display: flex; flex-direction: column; gap: 12px"),
        )
        .child(el("h1").attr("style", "font-size: 30px; margin: 16px 0 0").child(t("Notes")))
        .child(el("p").attr("style", "margin: 0; color: var(--m-text-dim)").child(count))
        .child(button(t("+  New note"), "new".into(), "primary", Tap::New, tapped));
    if !notes.is_empty() {
        let q = query.clone();
        let typed = query.clone();
        pane = pane.child(
            el("div").class("m-input").child(
                el("input")
                    .class("m-input__native")
                    .attr("type", "search")
                    .attr("placeholder", t("Search"))
                    .attr("data-name", "search")
                    .prop("value", move || q.get_untracked())
                    .on("input", move |e| typed.set(e.value.clone().unwrap_or_default())),
            ),
        );
    }
    pane.child(el("div").class("m-list").attr("role", "list").child(list))
        .into_view()
}

/// The open note: its title with Pin, Copy and Delete (and back, alone on
/// a narrow window), and the text being written, filling the rest.
fn note_pane(
    note: &Note,
    both: bool,
    text: &Signal<String>,
    edited: &Signal<Option<String>>,
    tapped: &Signal<Option<Tap>>,
) -> View {
    let mut header = el("div").attr("style", "display: flex; align-items: center; gap: 8px");
    if !both {
        header = header.child(button("←", "back".into(), "ghost", Tap::Back, tapped));
    }
    let typed = text.clone();
    let pin = if note.pinned { t("Unpin") } else { t("Pin") };
    header = header
        .child(
            el("h2")
                .attr(
                    "style",
                    "flex: 1; min-width: 0; margin: 0; font-size: 21px; white-space: nowrap; overflow: hidden",
                )
                .child(move || title_of(&typed.get())),
        )
        .child(button(pin, "pin".into(), "ghost", Tap::Pin, tapped))
        .child(button(t("Copy"), "copy".into(), "ghost", Tap::Copy, tapped))
        .child(button(t("Delete"), "delete".into(), "ghost", Tap::Delete, tapped));
    let edited = edited.clone();
    el("section")
        .attr(
            "style",
            "flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 12px; \
             padding: 24px 16px; background: var(--m-surface)",
        )
        .child(header)
        .child(
            el("textarea")
                .class("m-input")
                .attr("data-name", "text")
                .attr("placeholder", t("Write something"))
                .attr("style", "flex: 1; width: 100%; min-height: 120px")
                .prop("value", note.text.clone())
                .prop_bool("@focus", true)
                .on("input", move |e| edited.set(e.value.clone())),
        )
        .into_view()
}

/// What the page is drawn from, besides the notes.
struct Signals {
    text: Signal<String>,
    edited: Signal<Option<String>>,
    query: Signal<String>,
    tapped: Signal<Option<Tap>>,
}

/// The page: the list and the open note side by side on a wide window,
/// one of them on a narrow one.
fn page(notes: &[Note], open: Option<usize>, both: bool, zone: &Zone, s: &Signals) -> View {
    let mut root = el("div").attr("style", "display: flex; height: 100vh");
    if both || open.is_none() {
        root = root.child(list_pane(notes, open, both, zone, &s.text, &s.query, &s.tapped));
    }
    match open {
        Some(i) => root = root.child(note_pane(&notes[i], both, &s.text, &s.edited, &s.tapped)),
        None if both => {
            root = root.child(
                el("section")
                    .attr(
                        "style",
                        "flex: 1; display: flex; align-items: center; justify-content: center; \
                         background: var(--m-surface); color: var(--m-text-dim)",
                    )
                    .child(t("Choose a note, or start a new one")),
            )
        }
        None => {}
    }
    root.into_view()
}

/// What is selected in the note to the clipboard, or, with nothing
/// selected, the whole note.
fn copy(app: &App, screen: &Screen, note: &Note) {
    match screen.selected_text() {
        Some(part) => {
            app.copy(&part);
            pinnacle_rt::println!("notes: copied {} bytes of {}", part.len(), note.name);
        }
        None => {
            app.copy(&note.text);
            pinnacle_rt::println!("notes: copied {}", note.name);
        }
    }
}

/// Takes what a signal holds, leaving it empty.
fn take<T: Clone + 'static>(s: &Signal<Option<T>>) -> Option<T> {
    let v = s.get_untracked();
    if v.is_some() {
        s.set(None);
    }
    v
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let mut app = App::new("Notes");
    let mut notes = load();
    let mut open: Option<usize> = None;
    // When the open note is to be saved: some time after its last change.
    let mut save_at: Option<u64> = None;
    let mut redraw = true;
    let mut screen = Screen::new(app.width, app.height);
    // The local time zone, for the days notes changed: read again when
    // the app comes to the front.
    let mut zone = locale::zone();
    let s = Signals {
        text: signal(String::new()),
        edited: signal(None),
        query: signal(String::new()),
        tapped: signal(None),
    };
    pinnacle_rt::println!("notes: {} notes", notes.len());
    loop {
        if redraw {
            let both = notes::two_panes(app.width as i32);
            s.text
                .set(open.map(|i| notes[i].text.clone()).unwrap_or_default());
            screen.resize(app.width, app.height);
            screen.clear();
            screen.mount(page(&notes, open, both, &zone, &s));
            screen.draw(&mut app.canvas(), true);
            app.present_all();
            screen.announce("notes: button ");
            redraw = false;
        }
        match app.next_event(save_at) {
            Event::Timeout => {
                if let Some(i) = open {
                    save(&notes[i]);
                    pinnacle_rt::println!("notes: saved {}", notes[i].name);
                }
                save_at = None;
            }
            Event::Shown(false) => {
                // Leaving the app saves the note, as leaving the note does.
                if let Some(i) = open.filter(|_| save_at.take().is_some()) {
                    save(&notes[i]);
                }
            }
            Event::Shown(true) => {
                zone = locale::zone();
                redraw = true;
            }
            Event::Resized => redraw = true,
            // The language changed: everything is said again in it.
            Event::Preferences => {
                screen.restyle();
                redraw = true;
            }
            Event::Input(e) => {
                screen.input(&e);
                match screen.clipboard() {
                    Some(Clipboard::Paste) => app.paste(),
                    Some(Clipboard::Copy) => {
                        if let Some(i) = open {
                            copy(&app, &screen, &notes[i]);
                        }
                    }
                    None => {}
                }
                match take(&s.tapped) {
                    Some(Tap::New) => {
                        leave(&mut notes, &mut open, &mut save_at, usize::MAX);
                        let note = Note {
                            name: new_name(&notes),
                            text: String::new(),
                            modified: u64::MAX,
                            pinned: false,
                        };
                        pinnacle_rt::println!("notes: new {}", note.name);
                        // Under those pinned, above the rest.
                        let at = notes.iter().take_while(|n| n.pinned).count();
                        notes.insert(at, note);
                        open = Some(at);
                        redraw = true;
                    }
                    Some(Tap::Open(i)) => {
                        // The one left is saved, and goes if it is empty.
                        let i = leave(&mut notes, &mut open, &mut save_at, i);
                        open = Some(i);
                        pinnacle_rt::println!("notes: opened {}", notes[i].name);
                        redraw = true;
                    }
                    Some(Tap::Back) => {
                        leave(&mut notes, &mut open, &mut save_at, usize::MAX);
                        redraw = true;
                    }
                    Some(Tap::Copy) => {
                        if let Some(i) = open {
                            copy(&app, &screen, &notes[i]);
                        }
                    }
                    Some(Tap::Pin) => {
                        if let Some(i) = open {
                            notes[i].pinned = !notes[i].pinned;
                            let name = notes[i].name.clone();
                            // Kept in its place in the list: the open one
                            // is found again by its name.
                            sort(&mut notes);
                            open = notes.iter().position(|n| n.name == name);
                            save_pins(&notes);
                            let said = if open.is_some_and(|i| notes[i].pinned) {
                                "pinned"
                            } else {
                                "unpinned"
                            };
                            pinnacle_rt::println!("notes: {said} {name}");
                            redraw = true;
                        }
                    }
                    Some(Tap::Delete) => {
                        if let Some(i) = open.take() {
                            let note = notes.remove(i);
                            fs::remove(&note.path());
                            if note.pinned {
                                save_pins(&notes);
                            }
                            pinnacle_rt::println!("notes: deleted {}", note.name);
                            save_at = None;
                            redraw = true;
                        }
                    }
                    None => {}
                }
            }
            Event::Clipboard(pasted) => {
                if screen.paste(&pasted) {
                    pinnacle_rt::println!("notes: pasted {} bytes", pasted.len());
                }
            }
            Event::Closed => {
                if let Some(i) = open {
                    save(&notes[i]);
                }
                return 0;
            }
            _ => {}
        }
        // What was typed or pasted into the open note.
        if let (Some(value), Some(i)) = (take(&s.edited), open) {
            notes[i].text = value.clone();
            // Now, for the list's day; a new one keeps its place at the top.
            if notes[i].modified != u64::MAX {
                notes[i].modified = pinnacle_rt::clock();
            }
            s.text.set(value);
            save_at = Some(pinnacle_rt::time() + SAVE_AFTER_MS);
        }
        if !redraw && let Some(area) = screen.draw(&mut app.canvas(), false) {
            app.present(area);
        }
    }
}

/// Leaves the open note, if any, for note `next` (`usize::MAX`: none): saves
/// it if it changed, drops it if it is empty. Returns where `next` is now.
fn leave(notes: &mut Vec<Note>, open: &mut Option<usize>, save_at: &mut Option<u64>, next: usize) -> usize {
    let Some(i) = open.take() else { return next };
    if i == next {
        return next;
    }
    if save_at.take().is_some() || notes[i].text.trim().is_empty() {
        save(&notes[i]);
    }
    if notes[i].text.trim().is_empty() {
        let gone = notes.remove(i);
        if gone.pinned {
            save_pins(notes);
        }
        if next != usize::MAX && next > i {
            return next - 1;
        }
    }
    next
}