Let habits ask questions when a day is done, with their statistics

A habit's editor now has "Ask when done": add questions, each with its
words and how it is answered, as text, a whole number, a time or yes or
no. A habit without questions works as before. With them, tapping an
open day shows the questions, and Done records the answers and marks the
day. Tapping a day that is done shows its answers to change, like a
practice's session data, with Not done to open the day again. Counting
habits show their questions under the count steps.

Each answer keeps its question's words, so earlier days read the same
after a question is reworded or removed. Questions travel with the habit
and answers with the day to every device, only inside the encrypted
records; older versions of the app keep them.

The habit's statistics add up each question over the last 30 days: the
average and earliest to latest of times, with a dot per day, bedtimes
around midnight averaging correctly; the average and total of numbers
with a bar per day; how often the answer was yes; and the latest written
answers.
This commit is contained in:
waozi committed 2026-10-13 13:56:21 -03:00
1 parent 347fc198c2
commit 7b65ddaf5e
42 files changed
+2452 -30

No files matched your search

+4
View File
@@ -39,6 +39,10 @@ HabitsApply :: (message: HabitsMessage) -> HabitsMessage {
message.day_action = ifx message.decrement then HABITS_DAY_DECREMENT else HABITS_DAY_COUNT
} else if message.linked_count > 0 {
message.day_action = HABITS_DAY_LINKED
} else if message.question_count > 0 {
// The day opens its questions, or the answers of a done day,
// instead of being marked or cleared.
message.day_action = HABITS_DAY_QUESTIONS
} else {
message.day_action = HABITS_DAY_TOGGLE
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+17
View File
@@ -97,6 +97,23 @@ earlier days keep the schedule they had, and nothing recorded is removed. Days
off the schedule have no circle but still open, and what was recorded on them
shows faded. The context lists each habit's schedule and notification hour.
A habit can ask questions when a day is done, set under "Ask when done" in its
editor: each has its words and an answer type, text, a whole number, a time
or yes or no. Without questions a tap marks the day as before. With them the
Habits package answers a day tap with `HABITS_DAY_QUESTIONS`: an open day shows
the questions and Done records the answers with the day; a done day shows its
answers to change, or Not done to open it again without them. Counting habits
show the questions under the count steps. Questions are stored as a JSON
array on the habit (`habits.questions`) and answers on the day
(`habit_days.answers`), each with a stable question id and the question's
words, so a day reads the same after a question changes or goes. Both sync in
the encrypted habit and day records; a record from an app before them keeps
what the device has. The habit's statistics add up each question's last 30
days: average and total of numbers, average and earliest to latest of times
(cut at the day's longest unanswered stretch, so bedtimes around midnight
average correctly), how often the answer was yes, and the latest written
answers.
`/donate` and `show_donation_links` show the existing Bitcoin and Monero addresses
with copy, wallet and Trocador actions. Only a user click opens a destination.
The host chooses every address and URL from Inbe's donation configuration. Old
+48
View File
@@ -1818,6 +1818,54 @@ Denní cíl
[habit_link_practices]
Propojit cvičení
---
[habit_questions_label]
Zeptat se po splnění
---
[habit_question_placeholder]
Otázka, např. Kdy jsem začal jíst?
---
[habit_question_add]
Přidat otázku
---
[habit_answer_as]
Odpověď jako
---
[habit_answer_text]
Text
---
[habit_answer_number]
Číslo
---
[habit_answer_time]
Čas
---
[habit_answer_yes_no]
Ano, nebo ne
---
[habit_answer_yes]
Ano
---
[habit_answer_no]
Ne
---
[habit_day_not_done]
Nesplněno
---
[habit_stats_answers_title]
Odpovědi za posledních 30 dní
---
[habit_stats_average]
Průměr
---
[habit_stats_total]
Celkem
---
[habit_stats_time_range]
Nejdříve - nejpozději
---
[habit_stats_answered]
Zodpovězeno
---
[habit_link_practices_hint]
Vyberte dokončená cvičení, která se započítají do tohoto návyku.
---
+48
View File
@@ -1818,6 +1818,54 @@ Tagesziel
[habit_link_practices]
Übungen verknüpfen
---
[habit_questions_label]
Beim Erledigen fragen
---
[habit_question_placeholder]
Eine Frage, z. B. Wann habe ich angefangen zu essen?
---
[habit_question_add]
Frage hinzufügen
---
[habit_answer_as]
Antwort als
---
[habit_answer_text]
Text
---
[habit_answer_number]
Zahl
---
[habit_answer_time]
Uhrzeit
---
[habit_answer_yes_no]
Ja oder nein
---
[habit_answer_yes]
Ja
---
[habit_answer_no]
Nein
---
[habit_day_not_done]
Nicht erledigt
---
[habit_stats_answers_title]
Antworten, letzte 30 Tage
---
[habit_stats_average]
Durchschnitt
---
[habit_stats_total]
Summe
---
[habit_stats_time_range]
Früheste - späteste
---
[habit_stats_answered]
Beantwortet
---
[habit_link_practices_hint]
Wähle abgeschlossene Übungen, die für diese Gewohnheit zählen.
---
+48
View File
@@ -1847,6 +1847,54 @@ Daily target
[habit_link_practices]
Link practices
---
[habit_questions_label]
Ask when done
---
[habit_question_placeholder]
A question, e.g. When did I start eating?
---
[habit_question_add]
Add question
---
[habit_answer_as]
Answer as
---
[habit_answer_text]
Text
---
[habit_answer_number]
Number
---
[habit_answer_time]
Time
---
[habit_answer_yes_no]
Yes or no
---
[habit_answer_yes]
Yes
---
[habit_answer_no]
No
---
[habit_day_not_done]
Not done
---
[habit_stats_answers_title]
Answers, last 30 days
---
[habit_stats_average]
Average
---
[habit_stats_total]
Total
---
[habit_stats_time_range]
Earliest - latest
---
[habit_stats_answered]
Answered
---
[habit_link_practices_hint]
Choose which completed practices count toward this habit.
---
+48
View File
@@ -1827,6 +1827,54 @@ Meta diaria
[habit_link_practices]
Vincular prácticas
---
[habit_questions_label]
Preguntar al completar
---
[habit_question_placeholder]
Una pregunta, p. ej. ¿Cuándo empecé a comer?
---
[habit_question_add]
Añadir pregunta
---
[habit_answer_as]
Responder con
---
[habit_answer_text]
Texto
---
[habit_answer_number]
Número
---
[habit_answer_time]
Hora
---
[habit_answer_yes_no]
Sí o no
---
[habit_answer_yes]
Sí
---
[habit_answer_no]
No
---
[habit_day_not_done]
No hecho
---
[habit_stats_answers_title]
Respuestas, últimos 30 días
---
[habit_stats_average]
Promedio
---
[habit_stats_total]
Suma
---
[habit_stats_time_range]
Más temprano - más tarde
---
[habit_stats_answered]
Respondidas
---
[habit_link_practices_hint]
Elige qué prácticas completadas cuentan para este hábito.
---
+48
View File
@@ -1818,6 +1818,54 @@ Objectif quotidien
[habit_link_practices]
Lier des pratiques
---
[habit_questions_label]
Demander une fois fait
---
[habit_question_placeholder]
Une question, p. ex. Quand ai-je commencé à manger ?
---
[habit_question_add]
Ajouter une question
---
[habit_answer_as]
Répondre par
---
[habit_answer_text]
Texte
---
[habit_answer_number]
Nombre
---
[habit_answer_time]
Heure
---
[habit_answer_yes_no]
Oui ou non
---
[habit_answer_yes]
Oui
---
[habit_answer_no]
Non
---
[habit_day_not_done]
Pas fait
---
[habit_stats_answers_title]
Réponses, 30 derniers jours
---
[habit_stats_average]
Moyenne
---
[habit_stats_total]
Somme
---
[habit_stats_time_range]
Plus tôt - plus tard
---
[habit_stats_answered]
Répondu
---
[habit_link_practices_hint]
Choisissez les pratiques terminées qui comptent pour cette habitude.
---
+48
View File
@@ -1827,6 +1827,54 @@ Target harian
[habit_link_practices]
Tautkan latihan
---
[habit_questions_label]
Tanyakan saat selesai
---
[habit_question_placeholder]
Pertanyaan, mis. Kapan saya mulai makan?
---
[habit_question_add]
Tambah pertanyaan
---
[habit_answer_as]
Jawab dengan
---
[habit_answer_text]
Teks
---
[habit_answer_number]
Angka
---
[habit_answer_time]
Waktu
---
[habit_answer_yes_no]
Ya atau tidak
---
[habit_answer_yes]
Ya
---
[habit_answer_no]
Tidak
---
[habit_day_not_done]
Belum selesai
---
[habit_stats_answers_title]
Jawaban, 30 hari terakhir
---
[habit_stats_average]
Rata-rata
---
[habit_stats_total]
Jumlah
---
[habit_stats_time_range]
Paling awal - paling akhir
---
[habit_stats_answered]
Dijawab
---
[habit_link_practices_hint]
Pilih latihan selesai yang dihitung untuk kebiasaan ini.
---
+48
View File
@@ -1818,6 +1818,54 @@ Obiettivo giornaliero
[habit_link_practices]
Collega pratiche
---
[habit_questions_label]
Chiedi al completamento
---
[habit_question_placeholder]
Una domanda, ad es. Quando ho iniziato a mangiare?
---
[habit_question_add]
Aggiungi domanda
---
[habit_answer_as]
Rispondi con
---
[habit_answer_text]
Testo
---
[habit_answer_number]
Numero
---
[habit_answer_time]
Ora
---
[habit_answer_yes_no]
Sì o no
---
[habit_answer_yes]
Sì
---
[habit_answer_no]
No
---
[habit_day_not_done]
Non fatto
---
[habit_stats_answers_title]
Risposte, ultimi 30 giorni
---
[habit_stats_average]
Media
---
[habit_stats_total]
Totale
---
[habit_stats_time_range]
Più presto - più tardi
---
[habit_stats_answered]
Risposte date
---
[habit_link_practices_hint]
Scegli quali pratiche completate contano per questa abitudine.
---
+48
View File
@@ -1820,6 +1820,54 @@ Inner Breezeは無料のオープンソースです。役に立ったら、少
[habit_link_practices]
練習を連携
---
[habit_questions_label]
完了時に質問
---
[habit_question_placeholder]
質問 (例: 何時に食べ始めた?)
---
[habit_question_add]
質問を追加
---
[habit_answer_as]
回答の形式
---
[habit_answer_text]
テキスト
---
[habit_answer_number]
数値
---
[habit_answer_time]
時刻
---
[habit_answer_yes_no]
はい/いいえ
---
[habit_answer_yes]
はい
---
[habit_answer_no]
いいえ
---
[habit_day_not_done]
未完了に戻す
---
[habit_stats_answers_title]
回答 (過去30日)
---
[habit_stats_average]
平均
---
[habit_stats_total]
合計
---
[habit_stats_time_range]
最早 - 最遅
---
[habit_stats_answered]
回答日数
---
[habit_link_practices_hint]
この習慣に反映する完了済みの練習を選択します。
---
+48
View File
@@ -1818,6 +1818,54 @@ Inner Breeze는 무료 오픈 소스입니다. 도움이 되셨다면 작은 후
[habit_link_practices]
연습 연결
---
[habit_questions_label]
완료할 때 질문
---
[habit_question_placeholder]
질문 (예: 언제 먹기 시작했나요?)
---
[habit_question_add]
질문 추가
---
[habit_answer_as]
답변 형식
---
[habit_answer_text]
텍스트
---
[habit_answer_number]
숫자
---
[habit_answer_time]
시간
---
[habit_answer_yes_no]
예/아니요
---
[habit_answer_yes]
예
---
[habit_answer_no]
아니요
---
[habit_day_not_done]
완료 취소
---
[habit_stats_answers_title]
답변 (최근 30일)
---
[habit_stats_average]
평균
---
[habit_stats_total]
합계
---
[habit_stats_time_range]
가장 이른 - 가장 늦은
---
[habit_stats_answered]
답변한 날
---
[habit_link_practices_hint]
이 습관에 반영할 완료된 연습을 선택하세요.
---
+48
View File
@@ -1827,6 +1827,54 @@ Meta diária
[habit_link_practices]
Vincular práticas
---
[habit_questions_label]
Perguntar ao concluir
---
[habit_question_placeholder]
Uma pergunta, p. ex. Quando comecei a comer?
---
[habit_question_add]
Adicionar pergunta
---
[habit_answer_as]
Responder com
---
[habit_answer_text]
Texto
---
[habit_answer_number]
Número
---
[habit_answer_time]
Hora
---
[habit_answer_yes_no]
Sim ou não
---
[habit_answer_yes]
Sim
---
[habit_answer_no]
Não
---
[habit_day_not_done]
Não feito
---
[habit_stats_answers_title]
Respostas, últimos 30 dias
---
[habit_stats_average]
Média
---
[habit_stats_total]
Soma
---
[habit_stats_time_range]
Mais cedo - mais tarde
---
[habit_stats_answered]
Respondidas
---
[habit_link_practices_hint]
Escolha quais práticas concluídas contam para este hábito.
---
+48
View File
@@ -1818,6 +1818,54 @@ Inner Breeze бесплатное приложение с открытым ис
[habit_link_practices]
Связать практики
---
[habit_questions_label]
Спрашивать при выполнении
---
[habit_question_placeholder]
Вопрос, например: Когда я начал есть?
---
[habit_question_add]
Добавить вопрос
---
[habit_answer_as]
Ответ в виде
---
[habit_answer_text]
Текст
---
[habit_answer_number]
Число
---
[habit_answer_time]
Время
---
[habit_answer_yes_no]
Да или нет
---
[habit_answer_yes]
Да
---
[habit_answer_no]
Нет
---
[habit_day_not_done]
Не выполнено
---
[habit_stats_answers_title]
Ответы за 30 дней
---
[habit_stats_average]
Среднее
---
[habit_stats_total]
Всего
---
[habit_stats_time_range]
Самое раннее - позднее
---
[habit_stats_answered]
Отвечено
---
[habit_link_practices_hint]
Выберите завершённые практики, которые учитываются в этой привычке.
---
+48
View File
@@ -1818,6 +1818,54 @@ Inner Breeze 免费且开源。如果它对您有帮助,一点小额捐赠将
[habit_link_practices]
关联练习
---
[habit_questions_label]
完成时提问
---
[habit_question_placeholder]
问题,例如:我几点开始吃饭?
---
[habit_question_add]
添加问题
---
[habit_answer_as]
回答方式
---
[habit_answer_text]
文本
---
[habit_answer_number]
数字
---
[habit_answer_time]
时间
---
[habit_answer_yes_no]
是或否
---
[habit_answer_yes]
是
---
[habit_answer_no]
否
---
[habit_day_not_done]
未完成
---
[habit_stats_answers_title]
回答(最近30天)
---
[habit_stats_average]
平均
---
[habit_stats_total]
总计
---
[habit_stats_time_range]
最早 - 最晚
---
[habit_stats_answered]
已回答
---
[habit_link_practices_hint]
选择要计入此习惯的已完成练习。
---
+9
View File
@@ -312,6 +312,15 @@ HabitEditState :: struct {
formula_anchor: s32
formula_scroll_x: s32
formula_focused: s32
// The questions the habit asks when a day is done, as edited.
questions: [HABIT_QUESTION_MAX]HabitQuestion
question_count: s32
// 1 + the index of the question being typed in, or 0, and its field's
// cursor; the other questions' fields show from their start.
question_focused: s32
question_cursor: s32
question_anchor: s32
question_scroll_x: s32
}
SessionResult :: struct {
+86
View File
@@ -35,6 +35,9 @@
#import, file "../storage/sync_result.zi";
#import, file "../screens/elist_types.zi";
#import, file "../screens/habits/edit.zi";
#import, file "../screens/habits_screen.zi";
#import, file "../habits/habit_questions.zi";
#import, file "../habits/habit_actions.zi";
#import, file "../screens/lumi_screen.zi";
#import, file "text_buffers.zi";
#import, file "../app/exercise_types.zi";
@@ -159,6 +162,50 @@ screenshot_seed_habit_counts :: (app: *InnerBreeze) {
habit_set_day_count(*app.habits, 2, screenshot_day_index_offset(4), 2)
}
// The habit_question scenes: the first habit asks four questions, and most
// of the last two weeks have answers.
screenshot_question_times: [14]string = .["", "07:10", "07:45", "08:05", "",
"06:55", "07:30", "07:20", "08:15", "", "07:05", "07:40", "07:25", "07:50"];
screenshot_question_meals: [3]string = .["Oatmeal", "Eggs", "Fruit"];
screenshot_seed_habit_questions :: (app: *InnerBreeze, index: s32) {
if app == null || index < 0 || index >= app.habits.count { return }
habit := *app.habits.items[index]
texts: [4]string = .["When did I start eating?", "Plates", "Ate fruit?",
"What did I eat first?"]
types: [4]s32 = .[HABIT_ANSWER_TIME, HABIT_ANSWER_NUMBER,
HABIT_ANSWER_YES_NO, HABIT_ANSWER_TEXT]
habit.question_count = 0
question: s32 = 0
while question < 4 && HabitQuestionAdd(habit.questions[:],
*habit.question_count, 1782200000) {
unused AppCopyText(texts[question], habit.questions[question].text[:])
habit.questions[question].answer_type = types[question]
question += 1
}
habits_save(*app.habits)
none: [1]HabitAnswer
offset: s32 = 1
while offset < 14 {
time := screenshot_question_times[offset]
if time.count > 0 {
answers: [HABIT_DAY_ANSWER_MAX]HabitAnswer
count := HabitAnswersForDay(habit, none[:], 0, answers[:])
unused AppCopyText(time, answers[0].value[:])
plates: [4]u8
unused AppFormatS32(1 + offset % 3, plates[:])
unused AppCopyText(AppTextFromCString(*plates[0], 4), answers[1].value[:])
unused AppCopyText(ifx offset % 2 == 0 then "yes" else "no",
answers[2].value[:])
unused AppCopyText(screenshot_question_meals[offset % 3],
answers[3].value[:])
unused habit_answer_day(app, index, screenshot_day_index_offset(offset),
answers[:], count)
}
offset += 1
}
}
// The sun_salutation_pose scene: Upward salute, the second step, with the
// fourth painted character, held four seconds in so the move has finished.
screenshot_pose_character :: 3
@@ -543,6 +590,45 @@ setup_screenshot_scene :: (app: *InnerBreeze, request: *ScreenshotRequest) {
app.habits.count_dialog_day = screenshot_day_index_offset(0)
app_open_modal(app, cast(ModalType)ModalHabitCount)
}
} else if scene_text == "habit_count_questions" {
app.main_tab = APP_MAIN_TAB_HABITS
app.habits.screen_mode = HABITS_SCREEN_OVERVIEW
app.habits.selected = 2
app.habits.tab = HABIT_TAB_WEEKLY
app.habits.view_mode = HABIT_VIEW_WEEKLY
app.breathing.screen = ScreenHabits
screenshot_seed_habit_counts(app)
screenshot_seed_habit_questions(app, 2)
HabitScreenOpenCount(app, 2, screenshot_day_index_offset(0))
} else if scene_text == "habit_questions_dialog" {
app.main_tab = APP_MAIN_TAB_HABITS
app.habits.screen_mode = HABITS_SCREEN_OVERVIEW
app.habits.selected = -1
app.habits.tab = HABIT_TAB_WEEKLY
app.habits.view_mode = HABIT_VIEW_WEEKLY
app.breathing.screen = ScreenHabits
screenshot_seed_habit_questions(app, 0)
HabitScreenLoadAnswers(app, 0, screenshot_day_index_offset(0))
dialog := *app.habits.answer_dialog
unused AppCopyText("07", dialog.hours[0][:])
unused AppCopyText("40", dialog.minutes[0][:])
unused AppCopyText("2", dialog.answers[1].value[:])
unused AppCopyText("yes", dialog.answers[2].value[:])
unused AppCopyText("Oatmeal with berries", dialog.answers[3].value[:])
app_open_modal(app, cast(ModalType)ModalHabitQuestions)
} else if scene_text == "habit_edit_questions" {
app.main_tab = APP_MAIN_TAB_HABITS
screenshot_seed_habit_questions(app, 0)
habit_edit_begin(app, 0)
app.habits.scroll = 100000
} else if scene_text == "habit_question_stats" {
app.main_tab = APP_MAIN_TAB_HABITS
screenshot_seed_habit_questions(app, 0)
app.habits.screen_mode = HABITS_SCREEN_STATISTICS
app.habits.selected = 0
app.habits.tab = HABIT_TAB_STATISTICS
app.breathing.screen = ScreenHabits
app.habits.scroll = 100000
} else if scene_text == "habit_count_calendar" {
app.main_tab = APP_MAIN_TAB_HABITS
app.habits.screen_mode = HABITS_SCREEN_HISTORY
+4
View File
@@ -14,6 +14,7 @@ HABITS_DAY_DECREMENT :: 1
HABITS_DAY_COUNT :: 2
HABITS_DAY_LINKED :: 3
HABITS_DAY_TOGGLE :: 4
HABITS_DAY_QUESTIONS :: 5
HabitsMessage :: struct {
abi: s32
@@ -48,4 +49,7 @@ HabitsMessage :: struct {
day_action: s32
block_click: bool
screen: s32
// The questions the habit asks when a day is done; a host from before
// them leaves this 0.
question_count: s32
}
+4 -2
View File
@@ -69,12 +69,14 @@ SaveHabit :: (message: HabitsMessage) -> bool {
previous_weekdays := habit.weekdays
habit.weekdays = message.weekdays
habit.reminder_hour = message.reminder_hour
// The icon and schedule stay with the host's editor, so a Habits
// package from before them saves them too. A changed schedule plans
// The icon, schedule and questions stay with the host's editor, so a
// Habits package from before them saves them too. A changed schedule plans
// the days from today on; earlier days keep theirs.
if shared_app.habit_edit.active != 0 &&
(message.is_new || shared_app.habit_edit.index == index) {
habit.icon = shared_app.habit_edit.icon
habit.questions = shared_app.habit_edit.questions
habit.question_count = shared_app.habit_edit.question_count
habit.weekdays = previous_weekdays
unused HabitScheduleSet(habit, shared_app.habit_edit.schedule,
habits_today_index(), message.is_new)
+18 -2
View File
@@ -950,7 +950,7 @@ DecodeColor :: (value: HostValue) -> Color {
}
HabitsMessageCodec :: struct {
fields: [32]HostField
fields: [33]HostField
color: ColorCodec
}
@@ -959,7 +959,7 @@ EncodeHabitsMessage :: (data: HabitsMessage, codec: *HabitsMessageCodec) -> Host
value.kind = cast(s32)HostRecord
value.type_name = HostTextData("HabitsMessage")
value.fields = *codec.fields[0]
value.field_count = 32
value.field_count = 33
codec.fields[0].name = HostTextData("abi")
codec.fields[0].value = HostScalar("s32", cast(s64)data.abi)
codec.fields[1].name = HostTextData("action")
@@ -1030,6 +1030,8 @@ EncodeHabitsMessage :: (data: HabitsMessage, codec: *HabitsMessageCodec) -> Host
codec.fields[30].value = HostScalar("bool", ifx data.block_click then 1 else 0)
codec.fields[31].name = HostTextData("screen")
codec.fields[31].value = HostScalar("s32", cast(s64)data.screen)
codec.fields[32].name = HostTextData("question_count")
codec.fields[32].value = HostScalar("s32", cast(s64)data.question_count)
return value
}
@@ -1227,6 +1229,12 @@ DecodeHabitsMessage :: (value: HostValue) -> HabitsMessage {
data.screen = cast(s32)value.fields[field_at].value.integer
}
}
{
field_at := HostFieldAt(value, 32, "question_count")
if field_at >= 0 {
data.question_count = cast(s32)value.fields[field_at].value.integer
}
}
return data
}
@@ -3009,6 +3017,14 @@ ValidHabitsMessage :: (value: HostValue) -> bool {
}
}
}
{
field_at := HostFieldAt(value, 32, "question_count")
if field_at >= 0 {
if !HostScalarValid(value.fields[field_at].value, "s32", cast(s32)HostInteger) {
return false
}
}
}
return true
}
+37
View File
@@ -4,6 +4,7 @@
#import, file "habit_types.zi";
#import, file "habit_calendar.zi";
#import, file "habit_schedule.zi";
#import, file "habit_questions.zi";
#import, file "../app/app_types.zi";
#import, file "../app/text_buffers.zi";
#import, file "../storage/storage_habits.zi";
@@ -30,6 +31,42 @@ habit_complete_day :: (app: *InnerBreeze, index: s32, day: s32) -> bool {
return habit_completed_day(habit, day) != 0
}
// Records a day's answers to its habit's questions. Unless the habit counts,
// the day is done with them; a counting habit keeps the day's count.
habit_answer_day :: (app: *InnerBreeze, index: s32, day: s32,
answers: []HabitAnswer, count: s32) -> bool {
if app == null || index < 0 || index >= app.habits.count || day <= 0 {
return false
}
habit := *app.habits.items[index]
if habit_counting_enabled(habit) == 0 && habit_completed_day(habit, day) == 0 &&
!habit_complete_day(app, index, day) {
return false
}
if storage_habit_day_answers_save(AppTextFromCString(*habit.id[0],
HABIT_ID_SIZE), day, answers, count) == 0 {
return false
}
unused app_auto_sync(app)
return true
}
// A done day back to open, without its answers.
habit_reopen_day :: (app: *InnerBreeze, index: s32, day: s32) -> bool {
if app == null || index < 0 || index >= app.habits.count || day <= 0 {
return false
}
habit := *app.habits.items[index]
none: [1]HabitAnswer
if storage_habit_day_answers_save(AppTextFromCString(*habit.id[0],
HABIT_ID_SIZE), day, none[:], 0) == 0 {
return false
}
habit_set_day(*app.habits, index, day, 0)
unused app_auto_sync(app)
return true
}
// Gives a habit a schedule from today on and its notification hour, or -1
// for none, then saves and syncs it. Earlier days keep their schedules.
habit_set_schedule :: (app: *InnerBreeze, index: s32, rule: HabitSchedule,
+229
View File
@@ -0,0 +1,229 @@
// What a habit's answers to one question add up to over its last days.
#import, file "habit_types.zi";
#import, file "habit_questions.zi";
#import, file "../app/text_buffers.zi";
HABIT_ANSWER_STATS_DAYS :: 30
HABIT_ANSWER_RECENT :: 3
HABIT_MINUTES_PER_DAY :: 1440
HabitAnswerStats :: struct {
id: s64
answer_type: s32
// Days with an answer, and for numbers and times their sum, lowest and
// highest. Times are minutes after midnight; see HabitAnswerStatsFinish.
answered: s32
sum: s64
lowest: s32
highest: s32
yes: s32
no: s32
// Each day, oldest first: the day's number or time, or -1 without one.
values: [HABIT_ANSWER_STATS_DAYS]s32
// The latest text answers, newest first, and their days.
recent: [HABIT_ANSWER_RECENT][HABIT_ANSWER_SIZE]u8
recent_days: [HABIT_ANSWER_RECENT]s32
recent_count: s32
}
HabitAnswerStatsBegin :: (stats: *HabitAnswerStats, question: *HabitQuestion) {
stats.* = HabitAnswerStats.{}
stats.id = question.id
stats.answer_type = question.answer_type
day: s32 = 0
while day < HABIT_ANSWER_STATS_DAYS {
stats.values[day] = -1
day += 1
}
}
// A whole number of up to nine digits, or -1.
HabitAnswerNumber :: (value: string) -> s32 {
if value.count == 0 || value.count > 9 {
return -1
}
number: s32 = 0
index: s64 = 0
while index < value.count {
if !HabitTimeDigit(value[index]) {
return -1
}
number = number * 10 + cast(s32)value[index] - 48
index += 1
}
return number
}
// Counts the answer of the day at slot, 0 the oldest; a later answer of the
// same day is the one shown.
HabitAnswerStatsAdd :: (stats: *HabitAnswerStats, slot: s32, local_date: s32,
value: string) {
if slot < 0 || slot >= HABIT_ANSWER_STATS_DAYS || value.count == 0 {
return
}
if stats.answer_type == HABIT_ANSWER_YES_NO {
if value == "yes" {
stats.yes += 1
stats.answered += 1
} else if value == "no" {
stats.no += 1
stats.answered += 1
}
return
}
if stats.answer_type == HABIT_ANSWER_TEXT {
stats.answered += 1
// Days come oldest first: each newer answer goes in front.
last := stats.recent_count
if last >= HABIT_ANSWER_RECENT {
last = HABIT_ANSWER_RECENT - 1
}
while last > 0 {
stats.recent[last] = stats.recent[last - 1]
stats.recent_days[last] = stats.recent_days[last - 1]
last -= 1
}
unused AppCopyText(value, stats.recent[0][:])
stats.recent_days[0] = local_date
if stats.recent_count < HABIT_ANSWER_RECENT {
stats.recent_count += 1
}
return
}
number: s32 = -1
if stats.answer_type == HABIT_ANSWER_TIME {
hours: s32 = 0
minutes: s32 = 0
if HabitTimeParts(value, *hours, *minutes) {
number = hours * 60 + minutes
}
} else {
number = HabitAnswerNumber(value)
}
if number < 0 || stats.values[slot] >= 0 {
return
}
stats.values[slot] = number
stats.answered += 1
}
// Where the day's clock is cut for times: at the end of the longest
// stretch of the day without an answer. Times before the cut count as the
// next day's, so bedtimes such as 23:30 and 00:30 average to midnight,
// while times through the day, such as 07:00 to 09:00, keep midnight as
// the cut (-1).
HabitAnswerTimeCut :: (values: []s32) -> s32 {
sorted: [HABIT_ANSWER_STATS_DAYS]s32
count: s32 = 0
index: s32 = 0
while index < cast(s32)values.count && count < HABIT_ANSWER_STATS_DAYS {
value := values[index]
if value >= 0 {
place := count
while place > 0 && sorted[place - 1] > value {
sorted[place] = sorted[place - 1]
place -= 1
}
sorted[place] = value
count += 1
}
index += 1
}
if count < 2 {
return -1
}
// The stretch over midnight, from the latest time to the earliest.
longest := sorted[0] + HABIT_MINUTES_PER_DAY - sorted[count - 1]
cut: s32 = -1
index = 1
while index < count {
gap := sorted[index] - sorted[index - 1]
if gap > longest {
longest = gap
cut = sorted[index]
}
index += 1
}
return cut
}
// Sums the days' numbers and times, with their lowest and highest. Times
// before the cut (HabitAnswerTimeCut) count a day later; they are shown
// modulo a day.
HabitAnswerStatsFinish :: (stats: *HabitAnswerStats) {
if stats.answer_type != HABIT_ANSWER_TIME &&
stats.answer_type != HABIT_ANSWER_NUMBER {
return
}
if stats.answer_type == HABIT_ANSWER_TIME {
cut := HabitAnswerTimeCut(stats.values[:])
if cut >= 0 {
day: s32 = 0
while day < HABIT_ANSWER_STATS_DAYS {
if stats.values[day] >= 0 && stats.values[day] < cut {
stats.values[day] += HABIT_MINUTES_PER_DAY
}
day += 1
}
}
}
stats.sum = 0
stats.lowest = -1
stats.highest = -1
day: s32 = 0
while day < HABIT_ANSWER_STATS_DAYS {
value := stats.values[day]
if value >= 0 {
stats.sum += cast(s64)value
if stats.lowest < 0 || value < stats.lowest {
stats.lowest = value
}
if value > stats.highest {
stats.highest = value
}
}
day += 1
}
}
// The average in hundredths, or -1 without answers.
HabitAnswerStatsAverage100 :: (stats: *HabitAnswerStats) -> s64 {
if stats.answered <= 0 {
return -1
}
return (stats.sum * 100 + cast(s64)stats.answered / 2) /
cast(s64)stats.answered
}
// Minutes after midnight, of this or the next day, as "HH:MM".
HabitAnswerTimeText :: (minutes: s32, output: []u8) -> string {
if output.count > 0 {
output[0] = cast(u8)0
}
if minutes < 0 {
return ""
}
minutes = minutes % HABIT_MINUTES_PER_DAY
cursor: s32 = 0
unused TextBufferAppendPaddedNumber(output, *cursor, minutes / 60, 2)
unused TextBufferAppendByte(output, *cursor, cast(u8)58)
unused TextBufferAppendPaddedNumber(output, *cursor, minutes % 60, 2)
return AppTextFromCString(*output[0], cast(s32)output.count)
}
// A number in hundredths with up to one decimal: 1250 is "12.5".
HabitAnswerDecimalText :: (value_x100: s64, output: []u8) -> string {
if output.count > 0 {
output[0] = cast(u8)0
}
tenths := (value_x100 + 5) / 10
unused AppFormatS64(tenths / 10, output)
if tenths % 10 != 0 {
cursor := cast(s32)AppTextFromCString(*output[0],
cast(s32)output.count).count
unused TextBufferAppendByte(output, *cursor, cast(u8)46)
unused TextBufferAppendByte(output, *cursor,
cast(u8)(48 + tenths % 10))
}
return AppTextFromCString(*output[0], cast(s32)output.count)
}
+227
View File
@@ -0,0 +1,227 @@
// The questions a habit asks when a day is done, and the day's answers.
#import, file "habit_types.zi";
#import, file "../app/text_buffers.zi";
// The name an answer type is stored and synced under.
HabitAnswerTypeName :: (answer_type: s32) -> string {
if answer_type == HABIT_ANSWER_NUMBER {
return "number"
}
if answer_type == HABIT_ANSWER_TIME {
return "time"
}
if answer_type == HABIT_ANSWER_YES_NO {
return "yes_no"
}
return "text"
}
// A type this version does not know, as from a newer app, reads as text.
HabitAnswerTypeFromName :: (name: string) -> s32 {
if name == "number" {
return HABIT_ANSWER_NUMBER
}
if name == "time" {
return HABIT_ANSWER_TIME
}
if name == "yes_no" {
return HABIT_ANSWER_YES_NO
}
return HABIT_ANSWER_TEXT
}
HabitQuestionText :: (question: *HabitQuestion) -> string {
return AppTextFromCString(*question.text[0], HABIT_QUESTION_TEXT_SIZE)
}
HabitAnswerValue :: (answer: *HabitAnswer) -> string {
return AppTextFromCString(*answer.value[0], HABIT_ANSWER_SIZE)
}
HabitAnswerQuestion :: (answer: *HabitAnswer) -> string {
return AppTextFromCString(*answer.question[0], HABIT_QUESTION_TEXT_SIZE)
}
// An id above every id the questions have, and above every id given before
// now, so a removed question's answers never belong to a new one.
HabitQuestionNewId :: (questions: []HabitQuestion, count: s32,
now: s64) -> s64 {
id := now * 100
index: s32 = 0
while index < count && index < cast(s32)questions.count {
if questions[index].id >= id {
id = questions[index].id + 1
}
index += 1
}
return id
}
// Adds a question without words, answered as text, or returns false when
// the habit asks all it can.
HabitQuestionAdd :: (questions: []HabitQuestion, count: *s32,
now: s64) -> bool {
if count.* < 0 || count.* >= HABIT_QUESTION_MAX ||
count.* >= cast(s32)questions.count {
return false
}
question := *questions[count.*]
question.* = HabitQuestion.{}
question.id = HabitQuestionNewId(questions, count.*, now)
question.answer_type = HABIT_ANSWER_TEXT
count.* += 1
return true
}
HabitQuestionRemove :: (questions: []HabitQuestion, count: *s32,
index: s32) {
if index < 0 || index >= count.* {
return
}
while index + 1 < count.* {
questions[index] = questions[index + 1]
index += 1
}
count.* -= 1
questions[count.*] = HabitQuestion.{}
}
// Keeps the questions that have words, trimmed, in their order.
HabitQuestionsKeepWorded :: (questions: []HabitQuestion, count: *s32) {
index: s32 = 0
while index < count.* {
text := HabitQuestionText(*questions[index])
start: s64 = 0
end := text.count
while start < end && (text[start] == cast(u8)32 || text[start] == cast(u8)9) {
start += 1
}
while end > start && (text[end - 1] == cast(u8)32 || text[end - 1] == cast(u8)9) {
end -= 1
}
if start == end {
HabitQuestionRemove(questions, count, index)
} else {
trimmed: [HABIT_QUESTION_TEXT_SIZE]u8
unused AppCopyText(text[start:end], trimmed[:])
unused AppCopyText(AppTextFromCString(*trimmed[0],
HABIT_QUESTION_TEXT_SIZE), questions[index].text[:])
index += 1
}
}
}
HabitTimeDigit :: (byte: u8) -> bool {
return byte >= cast(u8)48 && byte <= cast(u8)57
}
// Reads "H:MM" or "HH:MM" from 0:00 to 23:59.
HabitTimeParts :: (value: string, hours: *s32, minutes: *s32) -> bool {
colon: s64 = -1
index: s64 = 0
while index < value.count {
if value[index] == cast(u8)58 {
colon = index
} else if !HabitTimeDigit(value[index]) {
return false
}
index += 1
}
if colon < 1 || colon > 2 || value.count - colon != 3 {
return false
}
hour: s32 = 0
index = 0
while index < colon {
hour = hour * 10 + cast(s32)value[index] - 48
index += 1
}
minute := (cast(s32)value[colon + 1] - 48) * 10 +
cast(s32)value[colon + 2] - 48
if hour > 23 || minute > 59 {
return false
}
hours.* = hour
minutes.* = minute
return true
}
HabitTimeTypedNumber :: (typed: string) -> s32 {
if typed.count == 0 {
return -1
}
value: s32 = 0
index: s64 = 0
while index < typed.count {
if !HabitTimeDigit(typed[index]) {
return -1
}
value = value * 10 + cast(s32)typed[index] - 48
index += 1
}
return value
}
// The time typed as hours and minutes, as "HH:MM"; empty while the hours
// are, and minutes left empty are 00.
HabitTimeFromTyped :: (hours_typed: string, minutes_typed: string,
output: []u8) -> bool {
if output.count > 0 {
output[0] = cast(u8)0
}
hours := HabitTimeTypedNumber(hours_typed)
if hours < 0 {
return hours_typed.count == 0
}
minutes: s32 = 0
if minutes_typed.count > 0 {
minutes = HabitTimeTypedNumber(minutes_typed)
}
if hours > 23 || minutes < 0 || minutes > 59 {
return false
}
cursor: s32 = 0
return TextBufferAppendPaddedNumber(output, *cursor, hours, 2) &&
TextBufferAppendByte(output, *cursor, cast(u8)58) &&
TextBufferAppendPaddedNumber(output, *cursor, minutes, 2)
}
// The answers a day's dialog shows: one for each question the habit asks
// now, in its order, with what the day recorded for it, then what the day
// recorded for questions since removed.
HabitAnswersForDay :: (habit: *Habit, stored: []HabitAnswer,
stored_count: s32, output: []HabitAnswer) -> s32 {
count: s32 = 0
used: [HABIT_DAY_ANSWER_MAX]bool
index: s32 = 0
while index < habit.question_count && count < cast(s32)output.count {
question := *habit.questions[index]
answer := *output[count]
answer.* = HabitAnswer.{}
answer.id = question.id
answer.answer_type = question.answer_type
unused AppCopyText(HabitQuestionText(question), answer.question[:])
match: s32 = 0
while match < stored_count && match < cast(s32)stored.count {
if !used[match] && stored[match].id == question.id {
used[match] = true
unused AppCopyText(HabitAnswerValue(*stored[match]),
answer.value[:])
break
}
match += 1
}
count += 1
index += 1
}
index = 0
while index < stored_count && index < cast(s32)stored.count &&
count < cast(s32)output.count {
if !used[index] && HabitAnswerValue(*stored[index]).count > 0 {
output[count] = stored[index]
count += 1
}
index += 1
}
return count
}
+53
View File
@@ -82,6 +82,35 @@ HabitSchedule :: struct {
formula: [HABIT_FORMULA_SIZE]u8
}
// Questions a habit asks when a day is done, and how each is answered.
HABIT_QUESTION_MAX :: 8
HABIT_QUESTION_TEXT_SIZE :: 96
HABIT_ANSWER_SIZE :: 256
HABIT_ANSWER_TEXT :: 1
HABIT_ANSWER_NUMBER :: 2
HABIT_ANSWER_TIME :: 3
HABIT_ANSWER_YES_NO :: 4
HABIT_ANSWER_TYPE_COUNT :: 4
// A day's answers also keep those to questions since removed.
HABIT_DAY_ANSWER_MAX :: 16
HabitQuestion :: struct {
// Stays with the question while its words or answer change, so each
// day's answer still finds it; never given to another question.
id: s64
answer_type: s32
text: [HABIT_QUESTION_TEXT_SIZE]u8
}
// One answer of a day. It keeps the question's words and answer type as
// they were, so it reads the same after the question changes or goes.
HabitAnswer :: struct {
id: s64
answer_type: s32
question: [HABIT_QUESTION_TEXT_SIZE]u8
value: [HABIT_ANSWER_SIZE]u8
}
HabitDay :: struct {
day_index: s32
completed: s32
@@ -112,6 +141,9 @@ Habit :: struct {
// had. Without schedules, weekdays plans the habit.
schedules: [HABIT_SCHEDULE_MAX]HabitSchedule
schedule_count: s32
// Asked when a day is done; without them a tap marks the day.
questions: [HABIT_QUESTION_MAX]HabitQuestion
question_count: s32
days: *HabitDay
day_count: s32
day_capacity: s32
@@ -124,6 +156,25 @@ HabitDaySave :: struct {
count: s32
}
// The day dialog that asks a habit's questions, or shows the answers of a
// day that is done.
HabitAnswerDialog :: struct {
habit: s32
day: s32
answers: [HABIT_DAY_ANSWER_MAX]HabitAnswer
count: s32
// A time answer's hours and minutes as typed.
hours: [HABIT_DAY_ANSWER_MAX][4]u8
minutes: [HABIT_DAY_ANSWER_MAX][4]u8
// The field typed in: twice the answer's index, plus one for a time's
// minutes; -1 while none is.
focus: s32
cursor: s32
anchor: s32
scroll_x: s32
scroll: s32
}
HabitLinkedEntry :: struct {
path: [HABIT_LINKED_PATH_SIZE]u8
year: s32
@@ -178,6 +229,8 @@ Habits :: struct {
// The habit and day the count dialog edits while it is open.
count_dialog_habit: s32
count_dialog_day: s32
// The answers the questions or count dialog edits while it is open.
answer_dialog: HabitAnswerDialog
// Whether the inactive habits' rows are shown in the table, and the habit
// being dragged: a row to another place or a deactivated habit back
// into the rows. A row on a touch screen is lifted only once held.
+149 -1
View File
@@ -22,6 +22,8 @@ c :: #system_library "c";
#import, file "../../app/exercise_types.zi";
#import, file "../../habits/habit_icons.zi";
#import, file "../../habits/habit_schedule.zi";
#import, file "../../habits/habit_questions.zi";
#import "date_time"
#import, file "../../app/text_buffers.zi";
#import, file "../../app/locale.zi";
#import, file "../../app/app_modal_state.zi";
@@ -121,6 +123,8 @@ habit_edit_begin :: (app: *InnerBreeze, index: s32) {
app.habit_edit.schedule = HabitScheduleCurrent(*app.habits.items[index])
app.habit_edit.reminder_hour = app.habits.items[index].reminder_hour
app.habit_edit.icon = app.habits.items[index].icon
app.habit_edit.questions = app.habits.items[index].questions
app.habit_edit.question_count = app.habits.items[index].question_count
AppCopyText(AppTextFromCString(*app.habits.items[index].name[0],
HABIT_NAME_SIZE), app.habit_edit.text[:])
AppCopyText(AppTextFromCString(*app.habits.items[index].description[0],
@@ -232,6 +236,8 @@ habit_edit_commit :: (app: *InnerBreeze) {
!habit_edit_formula_valid(app) {
return
}
HabitQuestionsKeepWorded(app.habit_edit.questions[:],
*app.habit_edit.question_count)
message := HabitsMessageFor(app, HABITS_COMMIT)
message.active = app.habit_edit.active != 0
message.is_new = app.habit_edit.is_new != 0
@@ -433,7 +439,144 @@ habit_edit_section_body :: (app: *InnerBreeze, section: s32,
return habit_edit_schedule_height(app, width)
}
return AppScale(ifx (app.habit_edit.counter_enabled != 0)
then (148) else (96))
then (148) else (96)) + habit_edit_questions_height(app)
}
// The questions below the tracking options: a heading, each question with
// its answer type under it, and the button that adds one.
habit_edit_questions_height :: (app: *InnerBreeze) -> s32 {
return AppScale(48) + app.habit_edit.question_count * AppScale(104) +
AppScale(44)
}
habit_edit_answer_label :: (answer_type: s32) -> string {
if answer_type == HABIT_ANSWER_NUMBER {
return LocaleText("habit_answer_number")
}
if answer_type == HABIT_ANSWER_TIME {
return LocaleText("habit_answer_time")
}
if answer_type == HABIT_ANSWER_YES_NO {
return LocaleText("habit_answer_yes_no")
}
return LocaleText("habit_answer_text")
}
habit_edit_question_field :: (app: *InnerBreeze, index: s32,
bounds: Rectangle) -> bool {
question := *app.habit_edit.questions[index]
focused := app.habit_edit.question_focused == index + 1
typed: [64]u8
field: TextFieldProps
field.key = KeyHash("habit/edit/question") + cast(u64)index
field.bounds = bounds
field.value = FrameTextHold(*app.ui.frame_text, HabitQuestionText(question))
field.placeholder = LocaleText("habit_question_placeholder")
if focused {
field.cursor = app.habit_edit.question_cursor
field.anchor = app.habit_edit.question_anchor
field.scroll_x = app.habit_edit.question_scroll_x
}
field.focused = focused
field.focus_id = 7720 + index
field.max_bytes = HABIT_QUESTION_TEXT_SIZE - 1
field.max_codepoints = HABIT_QUESTION_TEXT_SIZE - 1
field.input = SampleTextFieldInput(focused, typed[:])
result := TextField(app.ui.session, field)
if result.edit.changed {
unused AppReplaceText(question.text[:], result.edit.start,
result.edit.end, result.edit.replacement)
}
if result.focused {
app.habit_edit.question_focused = index + 1
app.habit_edit.question_cursor = result.cursor
app.habit_edit.question_anchor = result.anchor
app.habit_edit.question_scroll_x = result.scroll_x
habit_edit_focus_only(app, 5)
} else if focused {
app.habit_edit.question_focused = 0
}
if result.clipboard_write {
unused TextInputWriteClipboard(result.clipboard_text)
}
return result.focused
}
// "Ask when done": each question's words with a button that removes it,
// "Answer as" its type under them, and a button that adds a question.
habit_edit_questions :: (app: *InnerBreeze, x: s32, y: s32, width: s32,
viewport_y: s32, viewport_h: s32, content_h: s32) {
edit := *app.habit_edit
habit_edit_text(app, LocaleText("habit_questions_label"),
x, y + AppScale(12), width, AppScale(28))
y += AppScale(48)
remove_w := AppScale(44)
type_w := AppScale(160)
types: [HABIT_ANSWER_TYPE_COUNT]DropdownOption
answer_type: s32 = 0
while answer_type < HABIT_ANSWER_TYPE_COUNT {
types[answer_type].label = habit_edit_answer_label(answer_type + 1)
answer_type += 1
}
index: s32 = 0
while index < edit.question_count {
text_bounds := Rectangle.{cast(float32)x, cast(float32)y,
cast(float32)(width - remove_w - AppScale(8)),
cast(float32)AppScale(44)}
was_focused := edit.question_focused == index + 1
if habit_edit_question_field(app, index, text_bounds) && !was_focused {
habit_edit_ensure_visible(app, viewport_y, viewport_h,
content_h, text_bounds)
}
removed := Button(app.ui.session, ButtonProps.{
.id = 7740 + index,
.bounds = Rectangle.{cast(float32)(x + width - remove_w),
cast(float32)y, cast(float32)remove_w,
cast(float32)AppScale(44)},
.label = "-",
.tone = cast(ButtonTone)ButtonToneNeutral,
.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0
habit_edit_row_label(app, LocaleText("habit_answer_as"), x,
y + AppScale(48), width - type_w - AppScale(8))
menu: DropdownProps
menu.id = 7750 + index
menu.bounds = Rectangle.{cast(float32)(x + width - type_w),
cast(float32)(y + AppScale(52)), cast(float32)type_w,
cast(float32)AppScale(44)}
menu.selected_index = edit.questions[index].answer_type - 1
chosen := Dropdown(app.ui.session, menu, types[:])
if chosen.changed {
edit.questions[index].answer_type = chosen.selected_index + 1
}
if removed {
HabitQuestionRemove(edit.questions[:], *edit.question_count, index)
edit.question_focused = 0
return
}
y += AppScale(104)
index += 1
}
add_label: [96]u8
args: [1]FormatArg
args[0].text = LocaleText("habit_question_add")
args[0].is_text = true
unused FormatTemplate("+ %s", args[:], add_label[:])
if Button(app.ui.session, ButtonProps.{
.id = 7760,
.bounds = Rectangle.{cast(float32)x, cast(float32)y,
cast(float32)width, cast(float32)AppScale(44)},
.label = FrameTextHold(*app.ui.frame_text,
AppTextFromCString(*add_label[0], 96)),
.disabled = edit.question_count >= HABIT_QUESTION_MAX,
.tone = cast(ButtonTone)ButtonToneNeutral,
.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 &&
HabitQuestionAdd(edit.questions[:], *edit.question_count, UnixNow()) {
edit.question_focused = edit.question_count
edit.question_cursor = 0
edit.question_anchor = 0
edit.question_scroll_x = 0
habit_edit_focus_only(app, 5)
}
}
// A section is a heading above a framed card holding its body.
@@ -745,6 +888,9 @@ habit_edit_focus_only :: (app: *InnerBreeze, field: s32) {
app.habit_edit.description_focused = ifx field == 2 then 1 else 0
app.habit_edit.counter_focused = ifx field == 3 then 1 else 0
app.habit_edit.formula_focused = ifx field == 4 then 1 else 0
if field != 5 {
app.habit_edit.question_focused = 0
}
}
habit_edit_formula_field :: (app: *InnerBreeze, bounds: Rectangle) -> bool {
@@ -1206,6 +1352,8 @@ habit_edit_tracking :: (app: *InnerBreeze, x: s32, y: s32,
.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 {
app_open_modal(app, cast(ModalType)ModalHabitPracticePicker)
}
habit_edit_questions(app, x, y + AppScale(44), width, viewport_y,
viewport_h, content_h)
}
habit_edit_modal :: (app: *InnerBreeze) -> bool {
+329 -1
View File
@@ -28,6 +28,9 @@ GetTime :: () -> float64 #foreign raylib_input;
#import, file "../habits/habit_sessions.zi";
#import, file "../habits/habit_linked_rules.zi";
#import, file "../habits/habit_date.zi";
#import, file "../habits/habit_questions.zi";
#import, file "../habits/habit_actions.zi";
#import, file "../storage/storage_habits.zi";
#import, file "../storage/storage_core.zi";
#import, file "../platform/web_storage.zi";
#import, file "habits/edit.zi";
@@ -67,6 +70,9 @@ GetTime :: () -> float64 #foreign raylib_input;
#import "svg_icon"
#import "tree_input"
#import "widget_kind"
#import "text_field_widget"
#import "text_input_props"
#import, file "../platform/raylib_text_input.zi";
using ModalType;
using ButtonTone;
@@ -449,6 +455,7 @@ HabitScreenAdjustCount :: (app: *InnerBreeze, index: s32,
HabitScreenOpenCount :: (app: *InnerBreeze, index: s32, day_index: s32) {
app.habits.count_dialog_habit = index
app.habits.count_dialog_day = day_index
HabitScreenLoadAnswers(app, index, day_index)
app_open_modal(app, cast(ModalType)ModalHabitCount)
}
@@ -465,6 +472,7 @@ HabitScreenDayAction :: (app: *InnerBreeze, index: s32,
message.completed = HabitScreenCompletion(app, index, day_index)
message.counter_enabled = habit_counting_enabled(habit)
message.linked_count = HabitScreenLinkedCount(app, index, day_index)
message.question_count = habit.question_count
message.decrement = decrement
message = HabitsRun(message)
if !message.succeeded {
@@ -476,6 +484,8 @@ HabitScreenDayAction :: (app: *InnerBreeze, index: s32,
HabitScreenOpenCount(app, index, day_index)
} else if message.day_action == HABITS_DAY_LINKED {
habit_open_linked_edit_page(app, index, day_index)
} else if message.day_action == HABITS_DAY_QUESTIONS {
HabitScreenOpenQuestions(app, index, day_index)
} else if message.day_action == HABITS_DAY_TOGGLE {
habit_toggle_day(*app.habits, index, day_index)
unused app_auto_sync(app)
@@ -1834,6 +1844,300 @@ HabitScreenCountText :: (app: *InnerBreeze, bounds: Rectangle,
Text(app.ui.session, props)
}
// ---- A day's questions and answers ---------------------------------------
HABIT_ANSWER_ROW_HEIGHT :: 82
// Fills the day dialog with the habit's questions and what the day answered.
HabitScreenLoadAnswers :: (app: *InnerBreeze, index: s32, day_index: s32) {
dialog := *app.habits.answer_dialog
dialog.* = HabitAnswerDialog.{}
dialog.habit = index
dialog.day = day_index
dialog.focus = -1
habit := *app.habits.items[index]
stored: [HABIT_DAY_ANSWER_MAX]HabitAnswer
stored_count := storage_habit_day_answers_load(
AppTextFromCString(*habit.id[0], HABIT_ID_SIZE), day_index, stored[:])
dialog.count = HabitAnswersForDay(habit, stored[:], stored_count,
dialog.answers[:])
answer: s32 = 0
while answer < dialog.count {
hours: s32 = 0
minutes: s32 = 0
if dialog.answers[answer].answer_type == HABIT_ANSWER_TIME &&
HabitTimeParts(HabitAnswerValue(*dialog.answers[answer]), *hours, *minutes) {
cursor: s32 = 0
unused TextBufferAppendPaddedNumber(dialog.hours[answer][:],
*cursor, hours, 2)
cursor = 0
unused TextBufferAppendPaddedNumber(dialog.minutes[answer][:],
*cursor, minutes, 2)
}
answer += 1
}
}
// Saves the dialog's answers: a day with questions is done with them.
HabitScreenSaveAnswers :: (app: *InnerBreeze) -> bool {
dialog := *app.habits.answer_dialog
answer: s32 = 0
while answer < dialog.count {
if dialog.answers[answer].answer_type == HABIT_ANSWER_TIME {
unused HabitTimeFromTyped(
AppTextFromCString(*dialog.hours[answer][0], 4),
AppTextFromCString(*dialog.minutes[answer][0], 4),
dialog.answers[answer].value[:])
}
answer += 1
}
return habit_answer_day(app, dialog.habit, dialog.day,
dialog.answers[:], dialog.count)
}
// One typed answer. Fields share one cursor: only the focused one has it.
HabitScreenAnswerTextField :: (app: *InnerBreeze, field: s32,
bounds: Rectangle, buffer: []u8, numeric: bool, max_bytes: s32) {
dialog := *app.habits.answer_dialog
focused := dialog.focus == field
typed: [64]u8
props: TextFieldProps
props.key = KeyHash("habits/answers/field") + cast(u64)field
props.bounds = bounds
props.value = FrameTextHold(*app.ui.frame_text,
AppTextFromCString(*buffer[0], cast(s32)buffer.count))
if focused {
props.cursor = dialog.cursor
props.anchor = dialog.anchor
props.scroll_x = dialog.scroll_x
}
props.focused = focused
props.focus_id = 7800 + field
props.numeric = numeric
props.max_bytes = max_bytes
props.max_codepoints = max_bytes
props.input = SampleTextFieldInput(focused, typed[:])
result := TextField(app.ui.session, props)
if result.edit.changed {
unused AppReplaceText(buffer, result.edit.start, result.edit.end,
result.edit.replacement)
}
if result.focused {
dialog.focus = field
dialog.cursor = result.cursor
dialog.anchor = result.anchor
dialog.scroll_x = result.scroll_x
} else if dialog.focus == field {
dialog.focus = -1
}
if result.clipboard_write {
unused TextInputWriteClipboard(result.clipboard_text)
}
}
// Hours and minutes stop at their largest: 23 and 59.
HabitScreenClampTyped :: (buffer: []u8, largest: s32) {
typed := HabitTimeTypedNumber(AppTextFromCString(*buffer[0],
cast(s32)buffer.count))
if typed > largest {
cursor: s32 = 0
unused TextBufferAppendPaddedNumber(buffer, *cursor, largest, 2)
}
}
// A yes or no answer: tapping the chosen one again leaves it unanswered.
HabitScreenYesNo :: (app: *InnerBreeze, answer: *HabitAnswer, id: s32,
x: s32, y: s32, width: s32) {
gap := AppScale(8)
half := (width - gap) / 2
values: [2]string = .["yes", "no"]
labels: [2]string = .[LocaleText("habit_answer_yes"),
LocaleText("habit_answer_no")]
option: s32 = 0
while option < 2 {
chosen := HabitAnswerValue(answer) == values[option]
props: ButtonProps
props.id = id + option
props.bounds = HabitScreenRect(x + option * (half + gap), y, half,
AppScale(44))
props.label = labels[option]
props.tone = cast(ButtonTone)(ifx chosen then ButtonToneAccent
else ButtonToneNeutral)
props.emphasis = cast(ButtonEmphasis)(ifx chosen then
ButtonEmphasisFilled else ButtonEmphasisSoft)
if Button(app.ui.session, props) != 0 {
unused AppCopyText(ifx chosen then "" else values[option],
answer.value[:])
}
option += 1
}
}
HabitScreenAnswersHeight :: (app: *InnerBreeze) -> s32 {
return app.habits.answer_dialog.count * AppScale(HABIT_ANSWER_ROW_HEIGHT)
}
// Each question above its answer, in the input its answer type takes.
HabitScreenAnswerFields :: (app: *InnerBreeze, x: s32, y: s32,
width: s32) {
dialog := *app.habits.answer_dialog
index: s32 = 0
while index < dialog.count {
answer := *dialog.answers[index]
label: TextProps
label.bounds = HabitScreenRect(x, y, width, AppScale(22))
label.text = FrameTextHold(*app.ui.frame_text,
HabitAnswerQuestion(answer))
label.font = AppSmallFontSize()
label.wrap = cast(TextWrap)TextWrapNone
Text(app.ui.session, label)
input_y := y + AppScale(26)
if answer.answer_type == HABIT_ANSWER_TIME {
part_w := AppScale(64)
colon_w := AppScale(20)
HabitScreenAnswerTextField(app, index * 2,
HabitScreenRect(x, input_y, part_w, AppScale(44)),
dialog.hours[index][:], true, 2)
HabitScreenClampTyped(dialog.hours[index][:], 23)
HabitScreenCountText(app, HabitScreenRect(x + part_w, input_y,
colon_w, AppScale(44)), ":", AppFontSize())
HabitScreenAnswerTextField(app, index * 2 + 1,
HabitScreenRect(x + part_w + colon_w, input_y, part_w,
AppScale(44)), dialog.minutes[index][:], true, 2)
HabitScreenClampTyped(dialog.minutes[index][:], 59)
} else if answer.answer_type == HABIT_ANSWER_YES_NO {
HabitScreenYesNo(app, answer, 7900 + index * 2, x, input_y, width)
} else if answer.answer_type == HABIT_ANSWER_NUMBER {
HabitScreenAnswerTextField(app, index * 2,
HabitScreenRect(x, input_y, AppScale(160), AppScale(44)),
answer.value[:], true, 9)
} else {
HabitScreenAnswerTextField(app, index * 2,
HabitScreenRect(x, input_y, width, AppScale(44)),
answer.value[:], false, HABIT_ANSWER_SIZE - 1)
}
y += AppScale(HABIT_ANSWER_ROW_HEIGHT)
index += 1
}
}
// The answers in a scrolling area, for questions that do not all fit.
HabitScreenAnswerArea :: (app: *InnerBreeze, bounds: Rectangle) {
dialog := *app.habits.answer_dialog
scroll := Scroll(app.ui.session, ScrollProps.{
.key = KeyHash("habits/answers/scroll"),
.bounds = bounds,
.content_height = HabitScreenAnswersHeight(app),
.scroll_offset = dialog.scroll,
.scale = MetricsScale()})
dialog.scroll = scroll.scroll_offset
if scroll.opened {
HabitScreenAnswerFields(app, cast(s32)scroll.content.x,
cast(s32)scroll.content.y, cast(s32)scroll.content.width)
unused End(app.ui.session)
}
}
// The answer area's height in a dialog: all answers, or what fits.
HabitScreenAnswerAreaHeight :: (app: *InnerBreeze, other: s32) -> s32 {
room := app.ui.view_height - AppScale(32) - AppScale(74) - other
height := HabitScreenAnswersHeight(app)
if height > room {
height = room
}
if height < AppScale(HABIT_ANSWER_ROW_HEIGHT) {
height = AppScale(HABIT_ANSWER_ROW_HEIGHT)
}
return height
}
HabitScreenOpenQuestions :: (app: *InnerBreeze, index: s32, day_index: s32) {
HabitScreenLoadAnswers(app, index, day_index)
app_open_modal(app, cast(ModalType)ModalHabitQuestions)
}
// A habit's questions for a day. Done records the answers and the day; a
// day that is done shows its answers to change, or opens again.
HabitScreenQuestionsDialog :: (app: *InnerBreeze) {
if app.modal.active == 0 ||
app.modal.type != cast(ModalType)ModalHabitQuestions { return }
dialog := *app.habits.answer_dialog
index := dialog.habit
day_index := dialog.day
if index < 0 || index >= app.habits.count || day_index <= 0 {
app_close_modal(app)
return
}
habit := *app.habits.items[index]
done := HabitScreenCompletion(app, index, day_index)
gap := AppScale(12)
date_h := AppScale(24)
button_h := AppScale(44)
area_h := HabitScreenAnswerAreaHeight(app, date_h + gap * 2 + button_h)
content_h := date_h + gap + area_h + gap + button_h
frame := ModalFrame(app.ui.session, ModalFrameProps.{
.key = KeyHash("habits/questions-dialog"),
.title = AppTextFromCString(*habit.name[0], HABIT_NAME_SIZE),
.width = AppScale(380), .height = content_h + AppScale(74),
.scale = MetricsScale(),
.has_right_action = true,
.right_label = LocaleText("cancel_button")})
if frame.dismissed || frame.right_clicked {
app_close_modal(app)
return
}
if !frame.opened {
return
}
content := frame.layout.content
x := cast(s32)content.x
y := cast(s32)content.y
width := cast(s32)content.width
day_text := HabitScreenDate(app, day_index)
if day_index == habits_today_index() {
day_text = LocaleText("habits_today")
}
HabitScreenCountText(app, HabitScreenRect(x, y, width, date_h),
day_text, AppSmallFontSize())
y += date_h + gap
HabitScreenAnswerArea(app, HabitScreenRect(x, y, width, area_h))
y += area_h + gap
if done {
half := (width - gap) / 2
reopen: ButtonProps
reopen.id = 5730001
reopen.bounds = HabitScreenRect(x, y, half, button_h)
reopen.label = LocaleText("habit_day_not_done")
reopen.tone = cast(ButtonTone)ButtonToneNeutral
reopen.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft
if Button(app.ui.session, reopen) != 0 &&
habit_reopen_day(app, index, day_index) {
app_close_modal(app)
}
save: ButtonProps
save.id = 5730002
save.bounds = HabitScreenRect(x + half + gap, y, width - half - gap,
button_h)
save.label = LocaleText("save_button")
save.tone = cast(ButtonTone)ButtonToneAccent
save.emphasis = cast(ButtonEmphasis)ButtonEmphasisFilled
if Button(app.ui.session, save) != 0 && HabitScreenSaveAnswers(app) {
app_close_modal(app)
}
} else {
complete: ButtonProps
complete.id = 5730003
complete.bounds = HabitScreenRect(x, y, width, button_h)
complete.label = LocaleText("done_button")
complete.tone = cast(ButtonTone)ButtonToneAccent
complete.emphasis = cast(ButtonEmphasis)ButtonEmphasisFilled
if Button(app.ui.session, complete) != 0 && HabitScreenSaveAnswers(app) {
app_close_modal(app)
}
}
unused End(app.ui.session)
}
// The count dialog: the day's count with large steps down and up. Linked
// practice sessions are the floor, and their sessions open from here.
HabitScreenCountDialog :: (app: *InnerBreeze) {
@@ -1855,14 +2159,27 @@ HabitScreenCountDialog :: (app: *InnerBreeze) {
content_h := AppScale(24) + AppScale(64) + AppScale(24) + gap +
step_h + gap + button_h
if linked_count > 0 { content_h += button_h + gap }
// A counting habit's questions sit under the steps; their answers are
// kept however the dialog closes.
asks := habit.question_count > 0 &&
app.habits.answer_dialog.habit == index &&
app.habits.answer_dialog.day == day_index
area_h: s32 = 0
if asks {
area_h = HabitScreenAnswerAreaHeight(app, content_h + gap)
content_h += area_h + gap
}
frame := ModalFrame(app.ui.session, ModalFrameProps.{
.key = KeyHash("habits/count-dialog"),
.title = AppTextFromCString(*habit.name[0], HABIT_NAME_SIZE),
.width = AppScale(340), .height = content_h + AppScale(74),
.width = AppScale(ifx asks then 380 else 340), .height = content_h + AppScale(74),
.scale = MetricsScale(),
.has_right_action = true,
.right_label = LocaleText("close_button")})
if frame.dismissed || frame.right_clicked {
if asks {
unused HabitScreenSaveAnswers(app)
}
app_close_modal(app)
return
}
@@ -1906,6 +2223,10 @@ HabitScreenCountDialog :: (app: *InnerBreeze) {
HabitScreenAdjustCount(app, index, day_index, 1)
}
y += step_h + gap
if asks {
HabitScreenAnswerArea(app, HabitScreenRect(x, y, width, area_h))
y += area_h + gap
}
if linked_count > 0 {
sessions_text: [96]u8
@@ -1924,6 +2245,9 @@ HabitScreenCountDialog :: (app: *InnerBreeze) {
sessions.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft
if Button(app.ui.session, sessions) != 0 {
unused End(app.ui.session)
if asks {
unused HabitScreenSaveAnswers(app)
}
habit_open_linked_edit_page(app, index, day_index)
return
}
@@ -1936,6 +2260,9 @@ HabitScreenCountDialog :: (app: *InnerBreeze) {
done.tone = cast(ButtonTone)ButtonToneNeutral
done.emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft
if Button(app.ui.session, done) != 0 {
if asks {
unused HabitScreenSaveAnswers(app)
}
app_close_modal(app)
}
unused End(app.ui.session)
@@ -1946,6 +2273,7 @@ draw_habits_screen :: (app: *InnerBreeze) {
if app == null { return }
HabitScreenDrawPage(app)
HabitScreenCountDialog(app)
HabitScreenQuestionsDialog(app)
}
HabitScreenDrawPage :: (app: *InnerBreeze) {
+287 -1
View File
@@ -7,6 +7,10 @@ habit_cached_linked_entries :: (app: *InnerBreeze,
#import, file "statistics_date_rules.zi";
#import "date_time"
#import, file "../habits/habit_types.zi";
#import, file "../habits/habit_questions.zi";
#import, file "../habits/habit_answer_stats.zi";
#import, file "../storage/storage_habits.zi";
#import, file "../storage/db.zi";
#import, file "../core/types.zi";
#import, file "../app/app_types.zi";
#import, file "../storage/storage_core.zi";
@@ -518,6 +522,286 @@ statistics_draw_hold_graph :: (app: *InnerBreeze, linked_ctx: *HabitLinkedContex
}
}
// ---- What a habit's answers add up to ------------------------------------
statistics_answers: [HABIT_QUESTION_MAX]HabitAnswerStats;
statistics_answers_count: s32;
statistics_answers_revision: s64 = -1;
statistics_answers_today: s32;
statistics_answers_habit: [HABIT_ID_SIZE]u8;
// The last days up to today, oldest first.
statistics_last_days :: (today_index: s32, days: []s32) {
year := today_index / 10000
month := (today_index / 100) % 100
day := today_index % 100
slot := cast(s32)days.count - 1
while slot >= 0 {
days[slot] = year * 10000 + month * 100 + day
day -= 1
if day == 0 {
month -= 1
if month == 0 {
year -= 1
month = 12
}
day = habit_days_in_month(year, month)
}
slot -= 1
}
}
statistics_today_index :: () -> s32 {
local := LocalNow()
if !local.valid { return 0 }
return local.year * 10000 + local.month * 100 + local.day
}
// The habit's answer statistics, read again when its data or the day changes.
statistics_answer_stats :: (active: *Habit) -> s32 {
today := statistics_today_index()
habit_id := AppTextFromCString(*active.id[0], HABIT_ID_SIZE)
revision := storage_data_revision()
if revision == statistics_answers_revision &&
today == statistics_answers_today &&
AppTextFromCString(*statistics_answers_habit[0], HABIT_ID_SIZE) == habit_id &&
statistics_answers_count == active.question_count {
return statistics_answers_count
}
statistics_answers_revision = revision
statistics_answers_today = today
unused AppCopyText(habit_id, statistics_answers_habit[:])
days: [HABIT_ANSWER_STATS_DAYS]s32
statistics_last_days(today, days[:])
statistics_answers_count = 0
while statistics_answers_count < active.question_count {
unused storage_habit_answer_stats(habit_id,
*active.questions[statistics_answers_count], days[:],
*statistics_answers[statistics_answers_count])
statistics_answers_count += 1
}
return statistics_answers_count
}
statistics_answer_title_height :: (title: string, width: s32) -> s32 {
return AppParagraphHeight(title, width, Text16, AppScale(3))
}
// One question's statistics below its title: two figures, then the days'
// numbers or times as a chart, or the latest written answers.
statistics_answer_height :: (stats: *HabitAnswerStats, title: string,
width: s32) -> s32 {
height := statistics_answer_title_height(title, width) + AppScale(10) +
AppScale(66) + AppScale(22)
if stats.answer_type == HABIT_ANSWER_TIME ||
stats.answer_type == HABIT_ANSWER_NUMBER {
height += AppScale(128) + AppScale(24)
} else if stats.answer_type == HABIT_ANSWER_TEXT {
height += stats.recent_count * AppScale(26) + AppScale(14)
}
return height
}
statistics_answers_height :: (active: *Habit, width: s32) -> s32 {
if active == null || active.question_count <= 0 {
return 0
}
count := statistics_answer_stats(active)
// The answers start a little below the page's fixed height.
height := AppScale(48) + statistics_answer_title_height(
LocaleText("habit_stats_answers_title"), width) + AppScale(10)
index: s32 = 0
while index < count {
height += statistics_answer_height(*statistics_answers[index],
HabitQuestionText(*active.questions[index]), width)
index += 1
}
return height
}
statistics_answer_value_text :: (stats: *HabitAnswerStats, value: s32,
output: []u8) -> string {
if stats.answer_type == HABIT_ANSWER_TIME {
return HabitAnswerTimeText(value, output)
}
unused AppFormatS32(value, output)
return AppTextFromCString(*output[0], cast(s32)output.count)
}
// The days oldest to newest: bars from zero for numbers, dots between the
// earliest and latest time for times.
statistics_draw_answer_chart :: (stats: *HabitAnswerStats, x: s32, y: s32,
width: s32, accent: Color) {
chart_h := AppScale(128)
axis_w := AppScale(52)
plot_x := x + axis_w
plot_y := y + AppScale(12)
plot_w := width - axis_w - AppScale(10)
plot_h := chart_h - AppScale(24)
DrawRectangle(x, y, width, chart_h, DarkenColor(StyleTokenColor("canvas"), 7))
if stats.answered <= 0 || plot_w <= 0 {
return
}
is_time := stats.answer_type == HABIT_ANSWER_TIME
low: s32 = 0
high := stats.highest
if is_time {
low = stats.lowest
if high - low < 60 {
low -= 30
high += 30
}
}
if high <= low {
high = low + 1
}
label: [16]u8
Text(CurrentApp().ui.session, TextProps.{
.bounds = Rectangle.{cast(float32)(x + AppScale(6)),
cast(float32)(plot_y - AppScale(6)), 0, 0},
.text = FrameTextHold(*CurrentApp().ui.frame_text,
statistics_answer_value_text(stats, high, label[:])),
.font = Text12, .wrap = cast(TextWrap)TextWrapNone})
Text(CurrentApp().ui.session, TextProps.{
.bounds = Rectangle.{cast(float32)(x + AppScale(6)),
cast(float32)(plot_y + plot_h - AppScale(10)), 0, 0},
.text = FrameTextHold(*CurrentApp().ui.frame_text,
statistics_answer_value_text(stats, low, label[:])),
.font = Text12, .wrap = cast(TextWrap)TextWrapNone})
slot_w := plot_w / HABIT_ANSWER_STATS_DAYS
if slot_w < 1 { slot_w = 1 }
day: s32 = 0
while day < HABIT_ANSWER_STATS_DAYS {
value := stats.values[day]
if value >= 0 {
slot_x := plot_x + day * slot_w
if is_time {
dot := AppScale(8)
dot_y := plot_y + (high - value) * (plot_h - dot) / (high - low)
DrawRectangle(slot_x + (slot_w - dot) / 2, dot_y, dot, dot, accent)
} else {
bar_h := value * plot_h / high
if bar_h < AppScale(3) { bar_h = AppScale(3) }
bar_w := slot_w - AppScale(2)
if bar_w < 1 { bar_w = 1 }
DrawRectangle(slot_x + 1, plot_y + plot_h - bar_h, bar_w,
bar_h, LightenColor(accent, 12))
}
}
day += 1
}
}
statistics_draw_answer :: (stats: *HabitAnswerStats, title: string, x: s32,
y: s32, width: s32, accent: Color) {
y += statistics_draw_section_title(title, x, y, width) + AppScale(10)
metric_h := AppScale(66)
gap := AppScale(8)
half := (width - gap) / 2
first: [48]u8
second: [48]u8
first_label := LocaleText("habit_stats_average")
second_label := LocaleText("habit_stats_total")
first_text := "-"
second_text := "-"
if stats.answer_type == HABIT_ANSWER_YES_NO {
first_label = LocaleText("habit_answer_yes")
second_label = LocaleText("habit_stats_answered")
if stats.answered > 0 {
args: [1]FormatArg
args[0].number = (stats.yes * 100 + stats.answered / 2) / stats.answered
unused FormatTemplate("%d%%", args[:], first[:])
first_text = AppTextFromCString(*first[0], 48)
}
} else if stats.answer_type == HABIT_ANSWER_TEXT {
first_label = LocaleText("habit_stats_answered")
} else if stats.answered > 0 {
average := HabitAnswerStatsAverage100(stats)
if stats.answer_type == HABIT_ANSWER_TIME {
first_text = HabitAnswerTimeText(cast(s32)((average + 50) / 100), first[:])
low: [16]u8
high: [16]u8
args: [2]FormatArg
args[0].text = HabitAnswerTimeText(stats.lowest, low[:])
args[0].is_text = true
args[1].text = HabitAnswerTimeText(stats.highest, high[:])
args[1].is_text = true
unused FormatTemplate("%s - %s", args[:], second[:])
second_text = AppTextFromCString(*second[0], 48)
second_label = LocaleText("habit_stats_time_range")
} else {
first_text = HabitAnswerDecimalText(average, first[:])
unused AppFormatS64(stats.sum, second[:])
second_text = AppTextFromCString(*second[0], 48)
}
}
answered: [24]u8
answered_args: [2]FormatArg
answered_args[0].number = stats.answered
answered_args[1].number = HABIT_ANSWER_STATS_DAYS
unused FormatTemplate("%d/%d", answered_args[:], answered[:])
if stats.answer_type == HABIT_ANSWER_TEXT {
statistics_draw_metric(x, y, width, metric_h, first_label,
FrameTextHold(*CurrentApp().ui.frame_text,
AppTextFromCString(*answered[0], 24)), accent)
} else {
if stats.answer_type == HABIT_ANSWER_YES_NO {
second_text = AppTextFromCString(*answered[0], 24)
}
statistics_draw_metric(x, y, half, metric_h, first_label,
FrameTextHold(*CurrentApp().ui.frame_text, first_text), accent)
statistics_draw_metric(x + half + gap, y, width - half - gap, metric_h,
second_label, FrameTextHold(*CurrentApp().ui.frame_text,
second_text), LightenColor(accent, 20))
}
y += metric_h + AppScale(22)
if stats.answer_type == HABIT_ANSWER_TIME ||
stats.answer_type == HABIT_ANSWER_NUMBER {
statistics_draw_answer_chart(stats, x, y, width, accent)
} else if stats.answer_type == HABIT_ANSWER_TEXT {
index: s32 = 0
while index < stats.recent_count {
day := stats.recent_days[index]
line: [HABIT_ANSWER_SIZE + 32]u8
args: [4]FormatArg
args[0].number = day / 10000
args[1].number = (day / 100) % 100
args[2].number = day % 100
args[3].text = AppTextFromCString(*stats.recent[index][0],
HABIT_ANSWER_SIZE)
args[3].is_text = true
unused FormatTemplate("%04d-%02d-%02d %s", args[:], line[:])
Text(CurrentApp().ui.session, TextProps.{
.bounds = Rectangle.{cast(float32)x, cast(float32)y,
cast(float32)width, cast(float32)AppScale(24)},
.text = FrameTextHold(*CurrentApp().ui.frame_text,
AppTextFromCString(*line[0], cast(s32)line.count)),
.wrap = cast(TextWrap)TextWrapNone})
y += AppScale(26)
index += 1
}
}
}
// Every question of the habit with what its answers add up to.
statistics_draw_answers :: (active: *Habit, x: s32, y: s32, width: s32) {
if active == null || active.question_count <= 0 {
return
}
count := statistics_answer_stats(active)
y += statistics_draw_section_title(LocaleText("habit_stats_answers_title"),
x, y, width) + AppScale(10)
index: s32 = 0
while index < count {
title := HabitQuestionText(*active.questions[index])
statistics_draw_answer(*statistics_answers[index],
FrameTextHold(*CurrentApp().ui.frame_text, title), x, y, width,
active.color)
y += statistics_answer_height(*statistics_answers[index], title, width)
index += 1
}
}
statistics_draw_view :: (app: *InnerBreeze, active: *Habit, linked_ctx: *HabitLinkedContext, content_x: s32, content_w: s32, y: s32) {
local := LocalNow()
current_streak: s32 = 0
@@ -684,6 +968,8 @@ statistics_draw_view :: (app: *InnerBreeze, active: *Habit, linked_ctx: *HabitLi
LocaleText("habit_stats_best_streak"),
AppTextFromCString(*value[0], 64), active.color)
}
y += metric_h + AppScale(32)
statistics_draw_answers(active, content_x, y, content_w)
}
draw_statistics_content :: (app: *InnerBreeze, content_top: s32) {
@@ -727,7 +1013,7 @@ draw_statistics_content :: (app: *InnerBreeze, content_top: s32) {
page_ctx.mood_count = page_mood_count
GetCenteredColumn(max_w, GetPageSidePadding(), *content_x, *content_w)
content_h = statistics_content_height(page_ctx.linked_count,
page_ctx.mood_count)
page_ctx.mood_count) + statistics_answers_height(active, content_w)
{
scroll_1_bounds: Rectangle = Rectangle.{cast(float32)0,
cast(float32)scroll_y, cast(float32)app.ui.view_width,
+21 -8
View File
@@ -36,7 +36,13 @@ SET completed = MAX(completed, COALESCE((
JOIN sync_remote_habit_map m ON m.old_id = d.habit_id
WHERE m.new_id = habit_days.habit_id
AND d.local_date = habit_days.local_date
), 0))
), 0)),
answers = CASE WHEN answers <> '' THEN answers ELSE COALESCE((
SELECT d.answers FROM habit_days d
JOIN sync_remote_habit_map m ON m.old_id = d.habit_id
WHERE m.new_id = habit_days.habit_id
AND d.local_date = habit_days.local_date
), '') END
WHERE EXISTS (
SELECT 1 FROM sync_remote_habit_map m
WHERE m.new_id = habit_days.habit_id
@@ -45,10 +51,10 @@ SQL
InsertRemoteHabitDaysSQL :: #string SQL
INSERT INTO habit_days(
habit_id, local_date, completed, count, session_count, updated_at
habit_id, local_date, completed, count, session_count, updated_at, answers
)
SELECT m.new_id, d.local_date, d.completed, d.count,
d.session_count, d.updated_at
d.session_count, d.updated_at, d.answers
FROM habit_days d
JOIN sync_remote_habit_map m ON m.old_id = d.habit_id
WHERE NOT EXISTS (
@@ -88,7 +94,7 @@ SQL
SyncHabitsSQL :: #string SQL
INSERT INTO
habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule)
habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions)
SELECT COALESCE(json_extract(value,'$.id'),''),?2,
COALESCE(json_extract(value,'$.name'),''),
CAST(COALESCE(json_extract(value,'$.color_r'),0) AS INTEGER),
@@ -112,6 +118,8 @@ FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER),
CAST(COALESCE(json_extract(value,'$.icon'), (SELECT icon
FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),0) AS INTEGER),
CAST(COALESCE(json_extract(value,'$.schedule'), (SELECT schedule
FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),'') AS TEXT),
CAST(COALESCE(json_extract(value,'$.questions'), (SELECT questions
FROM habits WHERE id=COALESCE(json_extract(value,'$.id'),'')),'') AS TEXT) FROM (SELECT value
FROM json_each(?1,'$.changes.habits') UNION ALL SELECT value FROM
json_each(?1,'$.data.habits')) WHERE COALESCE(json_extract(value,'$.id'),'')<>'' ON CONFLICT(id)
@@ -120,25 +128,30 @@ user_id=excluded.user_id,name=excluded.name,color_r=excluded.color_r,color_g=exc
color_b=excluded.color_b,sync_mode=excluded.sync_mode,sync_activity=excluded.sync_activity,
counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target,sort_order=excluded.sort_order,deleted_at=excluded.deleted_at,
updated_at=excluded.updated_at, weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour,
deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule
deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule,
questions=excluded.questions
WHERE excluded.updated_at > habits.updated_at OR (excluded.updated_at = habits.updated_at AND
NOT EXISTS ( SELECT 1 FROM sync_outbox WHERE entity_type='habit' AND entity_id=habits.id AND
local_date=0))
SQL
SyncHabitDaysSQL :: #string SQL
INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at) SELECT
INSERT INTO habit_days(habit_id,local_date,completed,count,updated_at,answers) SELECT
COALESCE(json_extract(value,'$.habit_id'),''),
CAST(COALESCE(json_extract(value,'$.local_date'),0) AS INTEGER), CASE WHEN
json_extract(value,'$.completed') THEN 1 ELSE 0 END,
CAST(COALESCE(json_extract(value,'$.count'),CASE WHEN json_extract(value,'$.completed') THEN 1
ELSE 0 END) AS INTEGER),
CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INTEGER) FROM (SELECT
CAST(COALESCE(strftime('%s',json_extract(value,'$.updated_at')),'0') AS INTEGER),
CAST(COALESCE(json_extract(value,'$.answers'),(SELECT answers FROM habit_days WHERE
habit_id=COALESCE(json_extract(value,'$.habit_id'),'') AND
local_date=CAST(COALESCE(json_extract(value,'$.local_date'),0) AS INTEGER)),'') AS TEXT) FROM (SELECT
value FROM json_each(?1,'$.changes.habit_days') UNION ALL SELECT value FROM
json_each(?1,'$.data.habit_days')) WHERE COALESCE(json_extract(value,'$.habit_id'),'')<>'' AND
CAST(COALESCE(json_extract(value,'$.local_date'),0) AS INTEGER)>0 ON
CONFLICT(habit_id,local_date) DO UPDATE SET
completed=excluded.completed,count=excluded.count,updated_at=excluded.updated_at WHERE
completed=excluded.completed,count=excluded.count,updated_at=excluded.updated_at,
answers=excluded.answers WHERE
excluded.updated_at > habit_days.updated_at OR (excluded.updated_at = habit_days.updated_at AND
NOT EXISTS ( SELECT 1 FROM sync_outbox WHERE entity_type='habit_day' AND
entity_id=habit_days.habit_id AND local_date=habit_days.local_date ))
+6
View File
@@ -184,6 +184,12 @@ migrate_schema :: () -> s32 {
if !SchemaHasColumn("habits", "schedule") && !SchemaExec(SchemaHabitSchedule) {
return SchemaUpgradeFailed()
}
if !SchemaHasColumn("habits", "questions") && !SchemaExec(SchemaHabitQuestions) {
return SchemaUpgradeFailed()
}
if !SchemaHasColumn("habit_days", "answers") && !SchemaExec(SchemaDayAnswers) {
return SchemaUpgradeFailed()
}
if !SchemaHasColumn("habits", "updated_at") && !SchemaAddEpochColumn("habits", epoch) {
return SchemaUpgradeFailed()
}
+11
View File
@@ -97,6 +97,7 @@ CREATE TABLE IF NOT EXISTS habit_days( habit_id TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
session_count INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
answers TEXT NOT NULL DEFAULT '',
PRIMARY KEY(habit_id,
local_date));
CREATE TABLE IF NOT EXISTS sync_remote_habit_map( old_id TEXT PRIMARY KEY,
@@ -226,6 +227,16 @@ SchemaHabitSchedule :: #string SQL
ALTER TABLE habits ADD COLUMN schedule TEXT NOT NULL DEFAULT ''
SQL
// The questions a habit asks when a day is done, as a JSON array.
SchemaHabitQuestions :: #string SQL
ALTER TABLE habits ADD COLUMN questions TEXT NOT NULL DEFAULT ''
SQL
// A day's answers to its habit's questions, as a JSON array.
SchemaDayAnswers :: #string SQL
ALTER TABLE habit_days ADD COLUMN answers TEXT NOT NULL DEFAULT ''
SQL
SchemaSessionMoodBefore :: #string SQL
ALTER TABLE sessions ADD COLUMN mood_before INTEGER NOT NULL DEFAULT 0
SQL
+7 -3
View File
@@ -901,6 +901,8 @@ storage_append_habit_row_json :: (json_handle: s64, stmt_handle: s64) {
storage_json_append_int_field(json, "icon", cast(s64)sqlite3_column_int(stmt, 15))
storage_json_builder_append_text(json, ",")
storage_json_builder_key_value_text(json, "schedule", AppTextFromCString(SqliteColumnText(stmt, 16), 8192))
storage_json_builder_append_text(json, ",")
storage_json_builder_key_value_text(json, "questions", AppTextFromCString(SqliteColumnText(stmt, 17), 65536))
storage_json_builder_append_text(json, "}")
}
@@ -914,6 +916,8 @@ storage_append_habit_day_row_json :: (json_handle: s64, stmt_handle: s64) {
storage_json_append_int_field(json, "count", cast(s64)sqlite3_column_int(stmt, 3))
storage_json_builder_append_text(json, ",\"updated_at\":")
storage_json_builder_append_epoch(json, SqliteColumnInt64(stmt, 4))
storage_json_builder_append_text(json, ",")
storage_json_builder_key_value_text(json, "answers", AppTextFromCString(SqliteColumnText(stmt, 5), 65536))
storage_json_builder_append_text(json, "}")
}
@@ -1073,14 +1077,14 @@ storage_append_dated_payload_json :: (json: *StorageJsonBuilder, sql: string, id
storage_append_habit_payload_json :: (json: *StorageJsonBuilder, habit_id: string) -> s32 {
return storage_append_id_payload_json(
json,
"SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule FROM habits WHERE user_id=?1 AND id=?2",
"SELECT id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions FROM habits WHERE user_id=?1 AND id=?2",
habit_id, storage_append_habit_row_json)
}
storage_append_habit_day_payload_json :: (json: *StorageJsonBuilder, habit_id: string, local_date: s32) -> s32 {
return storage_append_dated_payload_json(
json,
"SELECT hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at FROM habit_days hd JOIN habits h ON h.id=hd.habit_id WHERE h.user_id=?1 AND hd.habit_id=?2 AND hd.local_date=?3",
"SELECT hd.habit_id,hd.local_date,hd.completed,hd.count,hd.updated_at,hd.answers FROM habit_days hd JOIN habits h ON h.id=hd.habit_id WHERE h.user_id=?1 AND hd.habit_id=?2 AND hd.local_date=?3",
habit_id, local_date, storage_append_habit_day_row_json)
}
@@ -2555,7 +2559,7 @@ storage_sync_status :: (status: *StorageSyncStatus) -> s32 {
storage_purge_synced_deleted_data_sqls: [4] string = .[
"DELETE FROM session_rounds WHERE session_id IN (SELECT id FROM sessions WHERE deleted_at>0 AND id NOT IN (SELECT entity_id FROM sync_outbox WHERE entity_type='session'))",
"DELETE FROM sessions WHERE deleted_at>0 AND id NOT IN (SELECT entity_id FROM sync_outbox WHERE entity_type='session')",
"DELETE FROM habit_days WHERE completed=0 AND count=0 AND session_count=0 AND NOT EXISTS (SELECT 1 FROM sync_outbox o WHERE o.entity_type='habit_day' AND o.entity_id=habit_days.habit_id AND o.local_date=habit_days.local_date)",
"DELETE FROM habit_days WHERE completed=0 AND count=0 AND session_count=0 AND answers='' AND NOT EXISTS (SELECT 1 FROM sync_outbox o WHERE o.entity_type='habit_day' AND o.entity_id=habit_days.habit_id AND o.local_date=habit_days.local_date)",
"DELETE FROM habits WHERE deleted_at>0 AND id NOT IN (SELECT entity_id FROM sync_outbox WHERE entity_type='habit')"
];
+1 -1
View File
@@ -83,7 +83,7 @@ storage_same_habit_id :: (a: string, b: string) -> bool {
return true
}
storage_merge_habit_into_sqls: [4] string = .["UPDATE habit_days SET completed=MAX(completed,COALESCE((SELECT d.completed FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), count=MAX(count,COALESCE((SELECT d.count FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), session_count=MAX(session_count,COALESCE((SELECT d.session_count FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), updated_at=MAX(updated_at,COALESCE((SELECT d.updated_at FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)) WHERE habit_id=?1 AND EXISTS (SELECT 1 FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date)", "INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) SELECT ?1,d.local_date,d.completed,d.count,d.session_count,d.updated_at FROM habit_days d WHERE d.habit_id=?2 AND NOT EXISTS (SELECT 1 FROM habit_days k WHERE k.habit_id=?1 AND k.local_date=d.local_date)", "DELETE FROM habit_days WHERE habit_id=?2", "DELETE FROM habits WHERE id=?2"];
storage_merge_habit_into_sqls: [4] string = .["UPDATE habit_days SET completed=MAX(completed,COALESCE((SELECT d.completed FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), count=MAX(count,COALESCE((SELECT d.count FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), session_count=MAX(session_count,COALESCE((SELECT d.session_count FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), updated_at=MAX(updated_at,COALESCE((SELECT d.updated_at FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),0)), answers=CASE WHEN answers<>'' THEN answers ELSE COALESCE((SELECT d.answers FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date),'') END WHERE habit_id=?1 AND EXISTS (SELECT 1 FROM habit_days d WHERE d.habit_id=?2 AND d.local_date=habit_days.local_date)", "INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at,answers) SELECT ?1,d.local_date,d.completed,d.count,d.session_count,d.updated_at,d.answers FROM habit_days d WHERE d.habit_id=?2 AND NOT EXISTS (SELECT 1 FROM habit_days k WHERE k.habit_id=?1 AND k.local_date=d.local_date)", "DELETE FROM habit_days WHERE habit_id=?2", "DELETE FROM habits WHERE id=?2"];
storage_merge_habit_into :: (keeper_id: string, duplicate_id: string) -> s32 {
stmt: *void = null
+194 -4
View File
@@ -6,11 +6,14 @@ c :: #system_library "c";
#import, file "../habits/habit_memory.zi";
#import, file "../habits/habit_days.zi";
#import, file "../habits/habit_schedule.zi";
#import, file "../habits/habit_questions.zi";
#import, file "../habits/habit_answer_stats.zi";
#import, file "../app/text_buffers.zi";
#import, file "state.zi";
#import, file "sqlite.zi";
#import, file "sql_query.zi";
#import, file "meta.zi";
#import, file "json.zi";
STORAGE_ID_SIZE :: 64
storage_next_change_time :: () -> s64 #foreign c "storage_next_change_time";
sqlite3_column_int :: (statement: *void, column: s32) -> s32 #foreign c "sqlite3_column_int";
@@ -54,6 +57,182 @@ meta_equals_buf :: (key: string, value: string) -> s32 {
// A habit's questions as the JSON array stored and synced with it.
storage_habit_questions_json :: (habit: *Habit, json: *StorageJsonBuilder) {
storage_json_builder_append_text(json, "[")
index: s32 = 0
while index < habit.question_count && index < HABIT_QUESTION_MAX {
question := *habit.questions[index]
id_text: [24]u8
unused AppFormatS64(question.id, id_text[:])
if index > 0 {
storage_json_builder_append_text(json, ",")
}
storage_json_builder_append_text(json, "{\"id\":")
storage_json_builder_append_text(json, AppTextFromCString(*id_text[0], 24))
storage_json_builder_append_text(json, ",")
storage_json_builder_key_value_text(json, "type",
HabitAnswerTypeName(question.answer_type))
storage_json_builder_append_text(json, ",")
storage_json_builder_key_value_text(json, "text", HabitQuestionText(question))
storage_json_builder_append_text(json, "}")
index += 1
}
storage_json_builder_append_text(json, "]")
}
// Reads a habit's questions from their JSON; text that is not a JSON array
// leaves the habit without questions.
storage_habit_questions_read :: (habit: *Habit, questions_json: string) {
habit.question_count = 0
if storage_db_handle() == null || questions_json.count == 0 {
return
}
stmt: *void = null
sql := "SELECT CAST(COALESCE(json_extract(value,'$.id'),0) AS INTEGER),COALESCE(json_extract(value,'$.type'),''),COALESCE(json_extract(value,'$.text'),'') FROM json_each(CASE WHEN json_valid(?1) AND json_type(?1)='array' THEN ?1 ELSE '[]' END) WHERE json_type(value)='object'"
if SqlitePrepareText(storage_db_handle(), sql, -1, *stmt, null) != SQLITE_OK {
return
}
bind_text(stmt, 1, questions_json)
while habit.question_count < HABIT_QUESTION_MAX && SqliteStep(stmt) == SQLITE_ROW {
question := *habit.questions[habit.question_count]
question.* = HabitQuestion.{}
question.id = SqliteColumnInt64(stmt, 0)
question.answer_type = HabitAnswerTypeFromName(
AppTextFromCString(SqliteColumnText(stmt, 1), 32))
copy_sqlite_text(*question.text[0], HABIT_QUESTION_TEXT_SIZE,
SqliteColumnText(stmt, 2))
habit.question_count += 1
}
SqliteFinalize(stmt)
}
// The answers a day recorded for its habit's questions.
storage_habit_day_answers_load :: (habit_id: string, local_date: s32,
output: []HabitAnswer) -> s32 {
if storage_db_handle() == null || habit_id.count == 0 || local_date <= 0 {
return 0
}
stmt: *void = null
sql := "SELECT CAST(COALESCE(json_extract(a.value,'$.id'),0) AS INTEGER),COALESCE(json_extract(a.value,'$.type'),''),COALESCE(json_extract(a.value,'$.question'),''),CAST(COALESCE(json_extract(a.value,'$.value'),'') AS TEXT) FROM habit_days hd,json_each(CASE WHEN json_valid(hd.answers) AND json_type(hd.answers)='array' THEN hd.answers ELSE '[]' END) a WHERE hd.habit_id=?1 AND hd.local_date=?2 AND json_type(a.value)='object'"
if SqlitePrepareText(storage_db_handle(), sql, -1, *stmt, null) != SQLITE_OK {
return 0
}
bind_text(stmt, 1, habit_id)
sqlite3_bind_int(stmt, 2, local_date)
count: s32 = 0
while count < cast(s32)output.count && SqliteStep(stmt) == SQLITE_ROW {
answer := *output[count]
answer.* = HabitAnswer.{}
answer.id = SqliteColumnInt64(stmt, 0)
answer.answer_type = HabitAnswerTypeFromName(
AppTextFromCString(SqliteColumnText(stmt, 1), 32))
copy_sqlite_text(*answer.question[0], HABIT_QUESTION_TEXT_SIZE,
SqliteColumnText(stmt, 2))
copy_sqlite_text(*answer.value[0], HABIT_ANSWER_SIZE,
SqliteColumnText(stmt, 3))
count += 1
}
SqliteFinalize(stmt)
return count
}
// Records a day's answers, leaving out those left empty, and syncs the day.
// The day's completion and count stay as they are.
storage_habit_day_answers_save :: (habit_id: string, local_date: s32,
answers: []HabitAnswer, count: s32) -> s32 {
if storage_db_handle() == null || habit_id.count == 0 || local_date <= 0 {
return 0
}
json: StorageJsonBuilder
json.ok = 1
storage_json_builder_append_text(*json, "[")
written: s32 = 0
index: s32 = 0
while index < count && index < cast(s32)answers.count {
answer := *answers[index]
if HabitAnswerValue(answer).count > 0 {
id_text: [24]u8
unused AppFormatS64(answer.id, id_text[:])
if written > 0 {
storage_json_builder_append_text(*json, ",")
}
storage_json_builder_append_text(*json, "{\"id\":")
storage_json_builder_append_text(*json, AppTextFromCString(*id_text[0], 24))
storage_json_builder_append_text(*json, ",")
storage_json_builder_key_value_text(*json, "type",
HabitAnswerTypeName(answer.answer_type))
storage_json_builder_append_text(*json, ",")
storage_json_builder_key_value_text(*json, "question",
HabitAnswerQuestion(answer))
storage_json_builder_append_text(*json, ",")
storage_json_builder_key_value_text(*json, "value",
HabitAnswerValue(answer))
storage_json_builder_append_text(*json, "}")
written += 1
}
index += 1
}
storage_json_builder_append_text(*json, "]")
if json.ok == 0 || json.data == null {
storage_json_builder_free(*json)
return 0
}
answers_text := ifx written > 0 then AppTextFromCString(json.data,
cast(s32)json.len) else ""
stmt: *void = null
sql := "INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at,answers) VALUES(?1,?2,0,0,0,?3,?4) ON CONFLICT(habit_id,local_date) DO UPDATE SET answers=excluded.answers,updated_at=excluded.updated_at WHERE habit_days.answers<>excluded.answers"
ok: s32 = 0
if SqlitePrepareText(storage_db_handle(), sql, -1, *stmt, null) == SQLITE_OK {
bind_text(stmt, 1, habit_id)
sqlite3_bind_int(stmt, 2, local_date)
SqliteBindInt64(stmt, 3, storage_next_change_time())
bind_text(stmt, 4, answers_text)
if SqliteStep(stmt) == SQLITE_DONE {
ok = 1
if sqlite3_changes(storage_db_handle()) > 0 {
storage_enqueue_sync_habit_day(habit_id, local_date)
}
}
SqliteFinalize(stmt)
}
storage_json_builder_free(*json)
if ok != 0 {
storage_schedule_persist()
}
return ok
}
// Adds up a question's answers on the given days, oldest first.
storage_habit_answer_stats :: (habit_id: string, question: *HabitQuestion,
days: []s32, stats: *HabitAnswerStats) -> s32 {
HabitAnswerStatsBegin(stats, question)
if storage_db_handle() == null || habit_id.count == 0 || days.count == 0 {
return 0
}
stmt: *void = null
sql := "SELECT hd.local_date,CAST(COALESCE(json_extract(a.value,'$.value'),'') AS TEXT) FROM habit_days hd,json_each(CASE WHEN json_valid(hd.answers) AND json_type(hd.answers)='array' THEN hd.answers ELSE '[]' END) a WHERE hd.habit_id=?1 AND hd.local_date BETWEEN ?2 AND ?3 AND json_type(a.value)='object' AND CAST(COALESCE(json_extract(a.value,'$.id'),0) AS INTEGER)=?4 ORDER BY hd.local_date"
if SqlitePrepareText(storage_db_handle(), sql, -1, *stmt, null) != SQLITE_OK {
return 0
}
bind_text(stmt, 1, habit_id)
sqlite3_bind_int(stmt, 2, days[0])
sqlite3_bind_int(stmt, 3, days[days.count - 1])
SqliteBindInt64(stmt, 4, question.id)
while SqliteStep(stmt) == SQLITE_ROW {
local_date := sqlite3_column_int(stmt, 0)
slot: s32 = 0
while slot < cast(s32)days.count && days[slot] != local_date {
slot += 1
}
HabitAnswerStatsAdd(stats, slot, local_date,
AppTextFromCString(SqliteColumnText(stmt, 1), HABIT_ANSWER_SIZE))
}
SqliteFinalize(stmt)
HabitAnswerStatsFinish(stats)
return 1
}
#program_export
storage_habits_empty :: () -> s32 {
if storage_habit_count() == 0 { return 1 }
@@ -84,8 +263,8 @@ storage_habits_load :: (habits_ptr: *void) -> s32 {
}
habits_free(habits)
habits.* = Habits.{}
sql_hb1: [248] u8
AppCopyText("SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule FROM habits WHERE deleted_at=0 ORDER BY sort_order,id LIMIT 32", sql_hb1[:])
sql_hb1: [264] u8
AppCopyText("SELECT id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,weekdays,reminder_hour,deactivated,icon,schedule,questions FROM habits WHERE deleted_at=0 ORDER BY sort_order,id LIMIT 32", sql_hb1[:])
if SqlitePrepare(storage_db_handle(), *sql_hb1[0], -1, *stmt, null) != SQLITE_OK {
return 0
}
@@ -122,6 +301,8 @@ storage_habits_load :: (habits_ptr: *void) -> s32 {
habit.icon = sqlite3_column_int(stmt, 13)
HabitScheduleRead(habit, AppTextFromCString(SqliteColumnText(stmt, 14),
HABIT_SCHEDULE_TEXT_SIZE))
storage_habit_questions_read(habit,
AppTextFromCString(SqliteColumnText(stmt, 15), 2147483647))
index += 1
}
SqliteFinalize(stmt)
@@ -203,8 +384,8 @@ storage_habits_save :: (habits_ptr: *void) {
sql_hbp1: [64] u8
AppCopyText("INSERT OR IGNORE INTO sync_loaded_habits(id) VALUES(?1)", sql_hbp1[:])
SqlitePrepare(storage_db_handle(), *sql_hbp1[0], -1, *loaded_stmt, null)
sql_hbq1: [1500] u8
AppCopyText("INSERT INTO habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,0,?13,?14,?15,?16,?17,?18) ON CONFLICT(id) DO UPDATE SET user_id=excluded.user_id,name=excluded.name,description=excluded.description,color_r=excluded.color_r,color_g=excluded.color_g,color_b=excluded.color_b,sync_mode=excluded.sync_mode,sync_activity=excluded.sync_activity,counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target,sort_order=excluded.sort_order,deleted_at=0,updated_at=excluded.updated_at,weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour,deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule WHERE habits.user_id<>excluded.user_id OR habits.name<>excluded.name OR habits.color_r<>excluded.color_r OR habits.color_g<>excluded.color_g OR habits.color_b<>excluded.color_b OR habits.sync_mode<>excluded.sync_mode OR habits.sync_activity<>excluded.sync_activity OR habits.counter_enabled<>excluded.counter_enabled OR habits.counter_target<>excluded.counter_target OR habits.sort_order<>excluded.sort_order OR habits.deleted_at<>0 OR habits.weekdays<>excluded.weekdays OR habits.reminder_hour<>excluded.reminder_hour OR habits.deactivated<>excluded.deactivated OR habits.icon<>excluded.icon OR habits.schedule<>excluded.schedule", sql_hbq1[:])
sql_hbq1: [1600] u8
AppCopyText("INSERT INTO habits(id,user_id,name,description,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,counter_target,sort_order,deleted_at,updated_at,weekdays,reminder_hour,deactivated,icon,schedule,questions) VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,0,?13,?14,?15,?16,?17,?18,?19) ON CONFLICT(id) DO UPDATE SET user_id=excluded.user_id,name=excluded.name,description=excluded.description,color_r=excluded.color_r,color_g=excluded.color_g,color_b=excluded.color_b,sync_mode=excluded.sync_mode,sync_activity=excluded.sync_activity,counter_enabled=excluded.counter_enabled,counter_target=excluded.counter_target,sort_order=excluded.sort_order,deleted_at=0,updated_at=excluded.updated_at,weekdays=excluded.weekdays,reminder_hour=excluded.reminder_hour,deactivated=excluded.deactivated,icon=excluded.icon,schedule=excluded.schedule,questions=excluded.questions WHERE habits.user_id<>excluded.user_id OR habits.name<>excluded.name OR habits.color_r<>excluded.color_r OR habits.color_g<>excluded.color_g OR habits.color_b<>excluded.color_b OR habits.sync_mode<>excluded.sync_mode OR habits.sync_activity<>excluded.sync_activity OR habits.counter_enabled<>excluded.counter_enabled OR habits.counter_target<>excluded.counter_target OR habits.sort_order<>excluded.sort_order OR habits.deleted_at<>0 OR habits.weekdays<>excluded.weekdays OR habits.reminder_hour<>excluded.reminder_hour OR habits.deactivated<>excluded.deactivated OR habits.icon<>excluded.icon OR habits.schedule<>excluded.schedule OR habits.questions<>excluded.questions", sql_hbq1[:])
SqlitePrepare(storage_db_handle(), *sql_hbq1[0], -1, *habit_stmt, null)
sql_hbq2: [72] u8
AppCopyText("UPDATE habits SET description=?2 WHERE id=?1 AND description<>?2", sql_hbq2[:])
@@ -260,9 +441,18 @@ storage_habits_save :: (habits_ptr: *void) {
schedule_text: [HABIT_SCHEDULE_TEXT_SIZE]u8
bind_text(habit_stmt, 18, HabitScheduleWrite(habit,
schedule_text[:]))
questions_json: StorageJsonBuilder
questions_json.ok = 1
if habit.question_count > 0 {
storage_habit_questions_json(habit, *questions_json)
}
bind_text(habit_stmt, 19, ifx questions_json.ok != 0 &&
questions_json.data != null then AppTextFromCString(
questions_json.data, cast(s32)questions_json.len) else "")
if SqliteStep(habit_stmt) == SQLITE_DONE && sqlite3_changes(storage_db_handle()) > 0 {
storage_enqueue_sync_habit(AppTextFromCString(*habit.id[0], 40))
}
storage_json_builder_free(*questions_json)
if desc_stmt != null {
sqlite3_reset(desc_stmt)
sqlite3_clear_bindings(desc_stmt)
+7
View File
@@ -459,8 +459,15 @@ CheckModules :: () -> s32 {
habit.scheduled = true
habit.counter_enabled = 0
habit.linked_count = 1
habit.question_count = 2
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_LINKED && habit.block_click, 22)
habit.linked_count = 0
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_QUESTIONS && habit.block_click, 48)
habit.question_count = 0
habit = HabitsRun(habit)
Expect(habit.day_action == HABITS_DAY_TOGGLE, 49)
habit.action = HABITS_HISTORY
habit.selected = 0
habit = HabitsRun(habit)
+2 -1
View File
@@ -61,7 +61,8 @@ def load(database, habit, sequence):
for day, value in enumerate(sequence):
if value:
database.execute(
"INSERT INTO habit_days VALUES (?,?,?,?,?,?)",
"INSERT INTO habit_days(habit_id,local_date,completed,count,"
"session_count,updated_at) VALUES (?,?,?,?,?,?)",
(habit, day, value, value, value, value))
+2
View File
@@ -150,3 +150,5 @@ ru trocador_button
zh theme_app
zh trocador_button
de launcher_title
cs habit_answer_text
de habit_answer_text
+138
View File
@@ -13,6 +13,8 @@
#import, file "../src/habits/habit_memory.zi";
#import, file "../src/storage/storage_habits.zi";
#import, file "../src/habits/habit_model.zi";
#import, file "../src/habits/habit_questions.zi";
#import, file "../src/habits/habit_answer_stats.zi";
c :: #system_library "c";
#import, file "../src/storage/import_types.zi";
@@ -536,6 +538,140 @@ test_uuid_habit_ids_load_days :: () {
storage_close()
}
// Questions travel with the habit; a day keeps its answers with the
// question's words, so they read the same after the question goes.
test_habit_questions_and_answers :: () {
root := make_root("habit-questions")
check_true("init db", storage_init(root) != 0)
storage_close()
raw_exec(root, "INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,sort_order,deleted_at,updated_at) VALUES('meal',(SELECT id FROM users LIMIT 1),'First meal',1,2,3,0,0,0,0,0,1782200000);")
check_true("reopen db", storage_init(root) != 0)
habits_b = Habits.{}
check_true("load habit", storage_habits_load(cast(*void)*habits_b) != 0)
habit := *habits_b.items[0]
check_int("no questions at first", habit.question_count, 0)
check_true("add a time question",
HabitQuestionAdd(habit.questions[:], *habit.question_count, 1782200000))
unused AppCopyText("When did I start \"eating\"?", habit.questions[0].text[:])
habit.questions[0].answer_type = HABIT_ANSWER_TIME
check_true("add a number question",
HabitQuestionAdd(habit.questions[:], *habit.question_count, 1782200000))
unused AppCopyText("Plates", habit.questions[1].text[:])
habit.questions[1].answer_type = HABIT_ANSWER_NUMBER
check_true("add a question without words",
HabitQuestionAdd(habit.questions[:], *habit.question_count, 1782200000))
HabitQuestionsKeepWorded(habit.questions[:], *habit.question_count)
check_int("a question without words is dropped", habit.question_count, 2)
check_true("each question has its own id",
habit.questions[0].id != habit.questions[1].id)
time_id := habit.questions[0].id
storage_habits_save(cast(*void)*habits_b)
check_int("the habit is queued to sync",
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='habit' AND entity_id='meal'"), 1)
habits_free(*habits_b)
habits_b = Habits.{}
check_true("reload habit", storage_habits_load(cast(*void)*habits_b) != 0)
habit = *habits_b.items[0]
check_int("questions kept", habit.question_count, 2)
check_true("words kept, quotes too",
HabitQuestionText(*habit.questions[0]) == "When did I start \"eating\"?")
check_int("answer type kept", habit.questions[0].answer_type, HABIT_ANSWER_TIME)
check_true("id kept", habit.questions[0].id == time_id)
none: [1]HabitAnswer
answers: [HABIT_DAY_ANSWER_MAX]HabitAnswer
count := HabitAnswersForDay(habit, none[:], 0, answers[:])
check_int("a day asks every question", count, 2)
unused AppCopyText("07:30", answers[0].value[:])
unused AppCopyText("2", answers[1].value[:])
check_true("save answers",
storage_habit_day_answers_save("meal", 20260701, answers[:], count) != 0)
check_int("the day is queued to sync",
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='habit_day' AND entity_id='meal' AND local_date=20260701"), 1)
loaded: [HABIT_DAY_ANSWER_MAX]HabitAnswer
loaded_count := storage_habit_day_answers_load("meal", 20260701, loaded[:])
check_int("answers loaded", loaded_count, 2)
check_true("time answer loaded", HabitAnswerValue(*loaded[0]) == "07:30" &&
loaded[0].id == time_id && loaded[0].answer_type == HABIT_ANSWER_TIME)
check_true("question words kept with the answer",
HabitAnswerQuestion(*loaded[0]) == "When did I start \"eating\"?")
HabitQuestionRemove(habit.questions[:], *habit.question_count, 0)
shown := HabitAnswersForDay(habit, loaded[:], loaded_count, answers[:])
check_int("a removed question's answer still shows", shown, 2)
check_true("current questions come first",
HabitAnswerQuestion(*answers[0]) == "Plates" &&
HabitAnswerValue(*answers[0]) == "2")
check_true("the removed question keeps its words",
HabitAnswerValue(*answers[1]) == "07:30" && answers[1].id == time_id)
cleared := storage_habit_day_answers_save("meal", 20260701, none[:], 0)
check_true("clear answers", cleared != 0 &&
storage_habit_day_answers_load("meal", 20260701, loaded[:]) == 0)
habits_free(*habits_b)
storage_close()
}
test_answer_statistics :: () {
root := make_root("habit-answer-stats")
check_true("init db", storage_init(root) != 0)
storage_close()
raw_exec(root, "INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,sort_order,deleted_at,updated_at,questions) VALUES('sleep',(SELECT id FROM users LIMIT 1),'Sleep',1,2,3,0,0,0,0,0,1782200000,'[{\"id\":1,\"type\":\"time\",\"text\":\"Bedtime\"},{\"id\":2,\"type\":\"number\",\"text\":\"Pages\"},{\"id\":3,\"type\":\"yes_no\",\"text\":\"Tea\"},{\"id\":4,\"type\":\"text\",\"text\":\"Dream\"}]');INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at,answers) VALUES('sleep',20260701,1,1,0,1782200000,'[{\"id\":1,\"type\":\"time\",\"question\":\"Bedtime\",\"value\":\"23:30\"},{\"id\":2,\"type\":\"number\",\"question\":\"Pages\",\"value\":\"2\"},{\"id\":3,\"type\":\"yes_no\",\"question\":\"Tea\",\"value\":\"yes\"},{\"id\":4,\"type\":\"text\",\"question\":\"Dream\",\"value\":\"Flying\"}]'),('sleep',20260702,1,1,0,1782200000,'[{\"id\":1,\"type\":\"time\",\"question\":\"Bedtime\",\"value\":\"00:30\"},{\"id\":2,\"type\":\"number\",\"question\":\"Pages\",\"value\":\"3\"},{\"id\":3,\"type\":\"yes_no\",\"question\":\"Tea\",\"value\":\"no\"},{\"id\":4,\"type\":\"text\",\"question\":\"Dream\",\"value\":\"Sea\"}]');")
check_true("reopen db", storage_init(root) != 0)
habits_b = Habits.{}
check_true("load habit", storage_habits_load(cast(*void)*habits_b) != 0)
habit := *habits_b.items[0]
check_int("questions read from JSON", habit.question_count, 4)
check_int("yes or no read", habit.questions[2].answer_type, HABIT_ANSWER_YES_NO)
days: [HABIT_ANSWER_STATS_DAYS]s32
slot: s32 = 0
while slot < HABIT_ANSWER_STATS_DAYS {
days[slot] = 20260701 + slot
slot += 1
}
stats: HabitAnswerStats
text: [16]u8
unused storage_habit_answer_stats("sleep", *habit.questions[0], days[:], *stats)
check_int("bedtimes answered", stats.answered, 2)
check_true("bedtimes around midnight average to midnight",
HabitAnswerTimeText(cast(s32)((HabitAnswerStatsAverage100(*stats) + 50) / 100),
text[:]) == "00:00")
check_true("earliest bedtime is 23:30",
HabitAnswerTimeText(stats.lowest, text[:]) == "23:30")
check_true("latest bedtime is 00:30",
HabitAnswerTimeText(stats.highest, text[:]) == "00:30")
unused storage_habit_answer_stats("sleep", *habit.questions[1], days[:], *stats)
check_true("pages sum", stats.sum == 5)
check_true("pages average 2.5",
HabitAnswerDecimalText(HabitAnswerStatsAverage100(*stats), text[:]) == "2.5")
check_int("first day's pages in its slot", stats.values[0], 2)
check_int("an unanswered day has no value", stats.values[2], -1)
unused storage_habit_answer_stats("sleep", *habit.questions[2], days[:], *stats)
check_true("one yes and one no", stats.yes == 1 && stats.no == 1)
unused storage_habit_answer_stats("sleep", *habit.questions[3], days[:], *stats)
check_true("newest text answer first", stats.recent_count == 2 &&
AppTextFromCString(*stats.recent[0][0], HABIT_ANSWER_SIZE) == "Sea" &&
stats.recent_days[0] == 20260702)
habits_free(*habits_b)
storage_close()
day_times: [3]s32 = .[420, 480, 540]
check_int("times through the day keep midnight", HabitAnswerTimeCut(day_times[:]), -1)
typed: [8]u8
check_true("typed 7 and 5 read 07:05",
HabitTimeFromTyped("7", "5", typed[:]) &&
AppTextFromCString(*typed[0], 8) == "07:05")
check_true("no hours, no time",
HabitTimeFromTyped("", "30", typed[:]) &&
AppTextFromCString(*typed[0], 8) == "")
check_true("24 hours is not a time", !HabitTimeFromTyped("24", "00", typed[:]))
hours: s32 = 0
minutes: s32 = 0
check_true("9:05 reads", HabitTimeParts("9:05", *hours, *minutes) &&
hours == 9 && minutes == 5)
check_true("9:5 does not", !HabitTimeParts("9:5", *hours, *minutes))
}
#program_export
Check :: () -> s32 {
guard := support_begin("/tmp/inbe-storage-habits-zi-test/")
@@ -553,5 +689,7 @@ Check :: () -> s32 {
test_existing_sessions_materialize()
test_meditation_logs_feed_profile_stats()
test_uuid_habit_ids_load_days()
test_habit_questions_and_answers()
test_answer_statistics()
return failures
}
+4 -2
View File
@@ -55,10 +55,12 @@ db.executescript(
updated_at INTEGER, weekdays INTEGER, reminder_hour INTEGER,
deactivated INTEGER NOT NULL DEFAULT 0,
icon INTEGER NOT NULL DEFAULT 0,
schedule TEXT NOT NULL DEFAULT '');
schedule TEXT NOT NULL DEFAULT '',
questions TEXT NOT NULL DEFAULT '');
CREATE TABLE habit_days(
habit_id TEXT, local_date INTEGER, completed INTEGER,
count INTEGER, session_count INTEGER, updated_at INTEGER,
answers TEXT NOT NULL DEFAULT '',
PRIMARY KEY(habit_id, local_date));
CREATE TABLE sync_remote_habit_map(
old_id TEXT PRIMARY KEY, new_id TEXT);
@@ -140,7 +142,7 @@ db.execute(
"INSERT INTO habits(id,user_id,name,deleted_at,updated_at) "
"VALUES('old-habit','user','Walking',0,2000000000)"
)
db.execute("INSERT INTO habit_days VALUES('old-habit',20260925,1,3,0,2000000000)")
db.execute("INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('old-habit',20260925,1,3,0,2000000000)")
db.execute("INSERT INTO sync_outbox VALUES('habit','old-habit',0)")
habit_response = json.dumps(
{
+30 -4
View File
@@ -18,6 +18,7 @@
#import, file "../src/habits/habit_memory.zi";
#import, file "../src/storage/storage_habits.zi";
#import, file "../src/storage/sync_review.zi";
#import, file "../src/storage/storage_habit_sync.zi";
#import, file "../src/habits/habit_model.zi";
#import, file "../src/habits/habit_calendar.zi";
#import, file "../src/habits/habit_schedule.zi";
@@ -1091,7 +1092,7 @@ test_social_cache_is_server_authored :: () {
test_review_preview_and_choices :: () {
remote_seed: TextBuffer
append(*remote_seed, REMOTE_SQL)
append(*remote_seed, "INSERT INTO habit_days VALUES('remote-habit',20260905,0,0,0,1782290000);INSERT INTO habit_days VALUES('remote-habit',20260906,0,3,0,1782290000);")
append(*remote_seed, "INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('remote-habit',20260905,0,0,0,1782290000);INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('remote-habit',20260906,0,3,0,1782290000);")
append(*remote_seed, "INSERT INTO elist_lists VALUES('remote-review-list',(SELECT id FROM users LIMIT 1),'Remote list',0,0,1782290000);INSERT INTO elist_items VALUES('remote-review-item',(SELECT id FROM users LIMIT 1),'remote-review-list','Remote item','',0,0,0,1782290000);")
remote_records("review-preview-source", TextFromCString(*remote_seed.bytes[0]))
seed: TextBuffer
@@ -1204,7 +1205,7 @@ test_review_social_differences :: () {
test_review_no_changes_resolves_automatically :: () {
remote_seed: TextBuffer
append(*remote_seed, LOCAL_SQL)
append(*remote_seed, "UPDATE sessions SET activity=3;INSERT INTO habit_days VALUES('local-habit',20260905,0,0,0,1782290000);")
append(*remote_seed, "UPDATE sessions SET activity=3;INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('local-habit',20260905,0,0,0,1782290000);")
remote_records("review-no-changes-source", TextFromCString(*remote_seed.bytes[0]))
seed: TextBuffer
append(*seed, LOCAL_SQL)
@@ -1289,14 +1290,38 @@ test_waiting_review_merges :: () {
storage_close()
}
// A habit's questions and a day's answers reach another device. A record
// from an app before them, without these fields, keeps what is there.
test_questions_and_answers_sync :: () {
remote_records("questions-remote", "INSERT INTO habits(id,user_id,name,color_r,color_g,color_b,sync_mode,sync_activity,counter_enabled,sort_order,deleted_at,updated_at,questions) VALUES('meal',(SELECT id FROM users LIMIT 1),'First meal',1,2,3,0,0,0,1,0,1782290000,'[{\"id\":7,\"type\":\"time\",\"text\":\"Started eating\"}]');INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at,answers) VALUES('meal',20260624,1,1,0,1782290000,'[{\"id\":7,\"type\":\"time\",\"question\":\"Started eating\",\"value\":\"07:30\"}]');")
root := make_root("questions-local")
check_true("init local device", storage_init(root) != 0)
set_account()
check_true("apply the remote records",
storage_apply_sync_response_json(snapshot_response(20, "questions-hash")) != 0)
check_int("questions arrive with the habit", count_of(root,
"SELECT COUNT(*) FROM habits WHERE id='meal' AND json_extract(questions,'$[0].text')='Started eating' AND json_extract(questions,'$[0].type')='time'"), 1)
check_int("answers arrive with the day", count_of(root,
"SELECT COUNT(*) FROM habit_days WHERE habit_id='meal' AND local_date=20260624 AND json_extract(answers,'$[0].value')='07:30' AND completed=1"), 1)
older: string = "{\"protocol_version\":6,\"server_version\":21,\"server_state_hash\":\"older-hash\",\"changes\":{\"habits\":[{\"id\":\"meal\",\"name\":\"First meal\",\"color_r\":1,\"color_g\":2,\"color_b\":3,\"sync_mode\":0,\"sync_activity\":0,\"counter_enabled\":false,\"counter_target\":1,\"sort_order\":1,\"deleted_at\":0,\"updated_at\":\"2026-06-30T00:00:00Z\"}],\"habit_days\":[{\"habit_id\":\"meal\",\"local_date\":20260624,\"completed\":true,\"count\":1,\"updated_at\":\"2026-06-30T00:00:00Z\"}]}}"
// Decrypted records go through the same habit and day apply.
check_true("apply an older app's habit", storage_apply_sync_habits_json(older) != 0)
check_true("apply an older app's day", storage_apply_sync_habit_days_json(older) != 0)
check_int("an older app's habit keeps the questions", count_of(root,
"SELECT COUNT(*) FROM habits WHERE id='meal' AND json_extract(questions,'$[0].text')='Started eating' AND updated_at>1782290000"), 1)
check_int("an older app's day keeps the answers", count_of(root,
"SELECT COUNT(*) FROM habit_days WHERE habit_id='meal' AND json_extract(answers,'$[0].value')='07:30' AND updated_at>1782290000"), 1)
storage_close()
}
test_review_completion_changes :: () {
remote_seed: TextBuffer
append(*remote_seed, REMOTE_SQL)
append(*remote_seed, "DELETE FROM sessions;UPDATE habit_days SET completed=0,count=0,session_count=0;INSERT INTO habit_days VALUES('remote-habit',20260905,0,0,0,1782290000);")
append(*remote_seed, "DELETE FROM sessions;UPDATE habit_days SET completed=0,count=0,session_count=0;INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('remote-habit',20260905,0,0,0,1782290000);")
remote_records("review-completion-source", TextFromCString(*remote_seed.bytes[0]))
seed: TextBuffer
append(*seed, REMOTE_SQL)
append(*seed, "DELETE FROM sessions;INSERT INTO habit_days VALUES('remote-habit',20260904,0,0,0,1782290000);")
append(*seed, "DELETE FROM sessions;INSERT INTO habit_days(habit_id,local_date,completed,count,session_count,updated_at) VALUES('remote-habit',20260904,0,0,0,1782290000);")
unused local_device("review-completion-local", TextFromCString(*seed.bytes[0]), "")
snapshot := snapshot_response(24, "review-completion-hash")
plan: *u8 = null
@@ -1641,5 +1666,6 @@ Check :: () -> s32 {
test_review_completion_changes()
test_review_no_changes_resolves_automatically()
test_waiting_review_merges()
test_questions_and_answers_sync()
return failures
}