//! Localization: the supported languages, the message catalogue, count and date //! formatting, and language resolution from the request. //! //! Every message is one arm of [`t`]'s single `match` over [`Msg`], and each arm gives //! both languages. A message without a Turkish text does not compile. use topcoat::{ context::Cx, cookie::{Cookie, Cookies, SameSite, cookies, time::Duration}, router::request::headers, }; /// Name of the cookie that stores the language choice. pub const LANG_COOKIE: &str = "lang"; /// How long the language choice is remembered. pub const LANG_COOKIE_DAYS: i64 = 365; /// A supported interface language. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Lang { En, Tr, } impl Lang { /// The value stored in the cookie and used in the `lang` attribute of ``. pub fn code(self) -> &'static str { match self { Self::En => "en", Self::Tr => "tr", } } /// Parses a cookie or form value. Returns `None` for unsupported languages. pub fn from_code(code: &str) -> Option { match code { "en" => Some(Self::En), "tr" => Some(Self::Tr), _ => None, } } } /// Every interface message. Add a variant here, then its texts in [`t`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Msg { AppName, MainNavigation, SkipToContent, Search, SearchLabel, SearchPlaceholder, NewNote, NewNotebook, NewNotebookLabel, Add, AllNotes, Unfiled, Trash, Notebooks, Theme, ThemeLight, ThemeDark, ThemeSystem, ColorScheme, Language, LanguageEnglish, LanguageTurkish, HideSidebar, ShowSidebar, OpenMenu, CloseMenu, Undo, Dismiss, ToastTrashed, ToastRestored, ToastNotebookCreated, ToastNotebookDeleted, ToastMoved, Untitled, JustNow, Yesterday, NoNotesYet, CreateOneHint, EmptyNotebook, EmptyUnfiled, EmptyTrash, SelectNote, GroupToday, GroupPrevious7, GroupEarlier, BackToList, /// Link under a list that has more rows than are shown. ShowMore, MoveToNotebook, AlreadyHere, FindNotebook, NotebookByName, NoSuchNotebook, ExportAs, ExportMarkdown, ExportHtml, ExportPdf, ExportAll, MoveToTrash, InTrash, AlreadyInTrash, RestoreFirst, Restore, DeleteForever, EmptyTrashAction, TrashRetention, Trashed, ConfirmEmptyTrashTitle, ConfirmForeverTitle, CannotUndo, Cancel, Rename, RenameNotebook, NotebookOptions, DeleteNotebook, DeleteNotebookTitle, DeleteNotebookBody, Breadcrumb, NoMatches, GuestName, GuestSubtitle, AccountMenu, SearchOptions, MatchCase, WholeWord, ExactPhrase, RegexSearch, InvalidRegex, InvalidRegexHint, SearchPartial, SearchAll, CheckSpelling, NoteActions, VersionHistory, CurrentVersion, NoVersionsYet, RestoreVersion, BackToNote, ToastVersionRestored, Import, ImportMarkdown, ImportHelp, ChooseFiles, ChooseFolder, ImportProgress, ImportDoneOne, ImportDoneMany, ImportFailed, ImportNoFiles, ImportGoToNotes, LinkedFrom, NoNoteNamed, CreateNote, // Editor EditorPlaceholder, EditorToolbarLabel, EditorBubbleLabel, EditorBlockMenu, EditorNoMatches, EditorNavigate, EditorInsert, EditorClose, EditorUnavailable, EditorUndo, EditorRedo, EditorParagraph, EditorHeading1, EditorHeading2, EditorHeading3, EditorBold, EditorItalic, EditorInlineCode, EditorLink, EditorBulletList, EditorNumberedList, EditorQuote, EditorCodeBlock, EditorDivider, EditorText, EditorLinkDialog, EditorLinkMenu, EditorLinkUrl, EditorLinkInvalid, EditorLinkNeedsLink, EditorApply, EditorRemove, EditorOpen, EditorEdit, EditorStatusSaved, EditorStatusSaving, EditorStatusLocal, EditorStatusReconnecting, EditorStatusConnecting, EditorAnnounceOffline, EditorAnnounceOnline, EditorPasteAsText, EditorNoteMenu, EditorCreateNote, EditorNoNotesFound, EditorUntitled, EditorCodeLanguage, EditorCodeAuto, EditorCodeFormat, EditorCodeFormatting, EditorCodeFormatFailed, EditorCodeFormatUnsupported, EditorCodeCopy, EditorCodeCopied, EditorCodeAutoFormat, EditorAttach, EditorRecordAudio, EditorStopRecording, EditorMediaFailed, EditorMicDenied, EditorRecordingNow, EditorRecordingLost, EditorContinueRecording, } /// The text of `msg` in `lang`. pub fn t(lang: Lang, msg: Msg) -> &'static str { // (English, Turkish) for every message. let (en, tr) = match msg { Msg::AppName => ("Notes", "Notlar"), Msg::MainNavigation => ("Main navigation", "Ana gezinme"), Msg::SkipToContent => ("Skip to content", "İçeriğe geç"), Msg::Search => ("Search", "Ara"), Msg::SearchLabel => ("Search notes", "Notlarda ara"), Msg::SearchPlaceholder => ("Search notes", "Notlarda ara"), Msg::NewNote => ("New note", "Yeni not"), Msg::NewNotebook => ("New notebook", "Yeni defter"), Msg::NewNotebookLabel => ("Notebook name", "Defter adı"), Msg::Add => ("Add", "Ekle"), Msg::AllNotes => ("All notes", "Tüm notlar"), Msg::Unfiled => ("Unfiled", "Dosyalanmamış"), Msg::Trash => ("Trash", "Çöp kutusu"), Msg::Notebooks => ("Notebooks", "Defterler"), Msg::Theme => ("Theme", "Tema"), Msg::ThemeLight => ("Light", "Açık"), Msg::ThemeDark => ("Dark", "Koyu"), Msg::ThemeSystem => ("System", "Sistem"), Msg::ColorScheme => ("Color scheme", "Renk şeması"), Msg::Language => ("Language", "Dil"), Msg::LanguageEnglish => ("English", "English"), Msg::LanguageTurkish => ("Türkçe", "Türkçe"), Msg::HideSidebar => ("Hide sidebar", "Kenar çubuğunu gizle"), Msg::ShowSidebar => ("Show sidebar", "Kenar çubuğunu göster"), Msg::OpenMenu => ("Open menu", "Menüyü aç"), Msg::CloseMenu => ("Close menu", "Menüyü kapat"), Msg::Undo => ("Undo", "Geri al"), Msg::Dismiss => ("Dismiss", "Kapat"), Msg::ToastTrashed => ("Note moved to trash.", "Not çöp kutusuna taşındı."), Msg::ToastRestored => ("Note restored.", "Not geri yüklendi."), Msg::ToastNotebookCreated => ("Notebook created.", "Defter oluşturuldu."), Msg::ToastNotebookDeleted => ("Notebook deleted.", "Defter silindi."), Msg::ToastMoved => ("Note moved.", "Not taşındı."), Msg::Untitled => ("Untitled", "Adsız"), Msg::JustNow => ("Just now", "Az önce"), Msg::Yesterday => ("Yesterday", "Dün"), Msg::NoNotesYet => ("No notes yet.", "Henüz not yok."), Msg::CreateOneHint => ("to create one.", "ile yeni not oluştur."), Msg::EmptyNotebook => ("Nothing in this notebook.", "Bu defterde not yok."), Msg::EmptyUnfiled => ("Nothing unfiled.", "Dosyalanmamış not yok."), Msg::EmptyTrash => ("Trash is empty.", "Çöp kutusu boş."), Msg::SelectNote => ("Select a note", "Bir not seçin"), Msg::GroupToday => ("Today", "Bugün"), Msg::GroupPrevious7 => ("Previous 7 days", "Önceki 7 gün"), Msg::GroupEarlier => ("Earlier", "Daha önce"), Msg::BackToList => ("Back to list", "Listeye dön"), Msg::ShowMore => ("Show more", "Daha fazla göster"), Msg::MoveToNotebook => ("Move to notebook", "Defterine taşı"), Msg::AlreadyHere => ("Already in this notebook.", "Zaten bu defterde."), Msg::FindNotebook => ("Find a notebook…", "Defter bul…"), Msg::NotebookByName => ("Notebook name", "Defter adı"), Msg::NoSuchNotebook => ("No notebook has that name.", "Bu adda defter yok."), Msg::ExportAs => ("Export as", "Şu biçimde dışa aktar"), Msg::ExportMarkdown => ("Markdown (.md)", "Markdown (.md)"), Msg::ExportHtml => ("HTML (.html)", "HTML (.html)"), Msg::ExportPdf => ("PDF (print)", "PDF (yazdır)"), Msg::ExportAll => ("Export all notes (.zip)", "Tüm notları dışa aktar (.zip)"), Msg::MoveToTrash => ("Move to trash", "Çöp kutusuna taşı"), Msg::InTrash => ("This note is in the trash.", "Bu not çöp kutusunda."), Msg::AlreadyInTrash => ("Already in the trash.", "Zaten çöp kutusunda."), Msg::RestoreFirst => ("Restore the note to move it.", "Notu taşımak için geri yükleyin."), Msg::Restore => ("Restore", "Geri yükle"), Msg::DeleteForever => ("Delete forever", "Kalıcı olarak sil"), Msg::EmptyTrashAction => ("Empty trash", "Çöp kutusunu boşalt"), Msg::TrashRetention => ( "Notes in the trash are deleted after 30 days.", "Çöp kutusundaki notlar 30 gün sonra silinir.", ), Msg::Trashed => ("Trashed", "Çöpe taşındı"), Msg::ConfirmEmptyTrashTitle => ("Empty trash?", "Çöp kutusu boşaltılsın mı?"), Msg::ConfirmForeverTitle => ("Delete this note forever?", "Bu not kalıcı olarak silinsin mi?"), Msg::CannotUndo => ("This cannot be undone.", "Bu işlem geri alınamaz."), Msg::Cancel => ("Cancel", "İptal"), Msg::Rename => ("Rename", "Yeniden adlandır"), Msg::RenameNotebook => ("Rename notebook", "Defteri yeniden adlandır"), Msg::NotebookOptions => ("Notebook options", "Defter seçenekleri"), Msg::DeleteNotebook => ("Delete notebook", "Defteri sil"), Msg::DeleteNotebookTitle => ("Delete notebook?", "Defter silinsin mi?"), Msg::DeleteNotebookBody => ("Its notes move to Unfiled.", "Notları Dosyalanmamış bölümüne taşınır."), Msg::Breadcrumb => ("Breadcrumb", "Konum"), Msg::NoMatches => ("No notes match.", "Eşleşen not yok."), Msg::GuestName => ("Guest", "Misafir"), Msg::GuestSubtitle => ("Personal library", "Kişisel kitaplık"), Msg::AccountMenu => ("Account menu", "Hesap menüsü"), Msg::SearchOptions => ("Search options", "Arama seçenekleri"), Msg::MatchCase => ("Match case", "Büyük/küçük harfe duyarlı"), Msg::WholeWord => ("Whole word", "Tam kelime"), Msg::ExactPhrase => ("Exact phrase", "Tam ifade"), Msg::RegexSearch => ("Regular expression", "Düzenli ifade"), Msg::InvalidRegex => ("Not a valid regular expression.", "Geçerli bir düzenli ifade değil."), Msg::InvalidRegexHint => ("Check the brackets and escapes.", "Parantezleri ve kaçış karakterlerini kontrol edin."), Msg::SearchPartial => ("Some long notes were not searched yet.", "Bazı uzun notlarda henüz aranmadı."), Msg::SearchAll => ("Search all", "Tümünde ara"), Msg::CheckSpelling => ( "Check the spelling or try fewer words.", "Yazımı kontrol edin ya da daha az kelime deneyin.", ), Msg::NoteActions => ("Note actions", "Not işlemleri"), Msg::Import => ("Import Markdown", "Markdown içe aktar"), Msg::ImportMarkdown => ("Import Markdown…", "Markdown içe aktar…"), Msg::ImportHelp => ( "Import .md files or a whole folder (e.g. an Obsidian vault). Each subfolder becomes a notebook.", "Tek tek .md dosyaları ya da bütün bir klasörü (ör. bir Obsidian kasası) içe aktarın. Her alt klasör bir deftere dönüşür.", ), Msg::ChooseFiles => ("Choose files", "Dosya seç"), Msg::ChooseFolder => ("Choose folder", "Klasör seç"), Msg::ImportProgress => ("Importing {done} of {total}…", "{done} / {total} içe aktarılıyor…"), Msg::ImportDoneOne => ("Imported {n} note.", "{n} not içe aktarıldı."), Msg::ImportDoneMany => ("Imported {n} notes.", "{n} not içe aktarıldı."), Msg::ImportFailed => ("{m} failed.", "{m} başarısız."), Msg::ImportNoFiles => ( "No .md, .markdown or .txt files found.", ".md, .markdown ya da .txt dosyası bulunamadı.", ), Msg::ImportGoToNotes => ("Go to notes", "Notlara git"), Msg::LinkedFrom => ("Linked from", "Bağlantı veren notlar"), Msg::NoNoteNamed => ("No note named \u{201c}{title}\u{201d}.", "\u{201c}{title}\u{201d} adlı not yok."), Msg::CreateNote => ("Create note", "Not oluştur"), Msg::VersionHistory => ("Version history", "Sürüm geçmişi"), Msg::CurrentVersion => ("Current version", "Güncel sürüm"), Msg::NoVersionsYet => ( "No earlier versions yet. Versions are saved every 10 minutes while you write.", "Henüz önceki sürüm yok. Yazarken sürümler her 10 dakikada bir kaydedilir.", ), Msg::RestoreVersion => ("Restore this version", "Bu sürümü geri yükle"), Msg::BackToNote => ("Back to note", "Nota dön"), Msg::ToastVersionRestored => ("Version restored.", "Sürüm geri yüklendi."), // Editor Msg::EditorPlaceholder => ("Start writing…", "Yazmaya başla…"), Msg::EditorToolbarLabel => ("Formatting", "Biçimlendirme"), Msg::EditorBubbleLabel => ("Text formatting", "Metin biçimlendirme"), Msg::EditorBlockMenu => ("Insert block", "Blok ekle"), Msg::EditorNoMatches => ("No matches", "Eşleşme yok"), Msg::EditorNavigate => ("navigate", "gezin"), Msg::EditorInsert => ("insert", "ekle"), Msg::EditorClose => ("close", "kapat"), Msg::EditorUnavailable => ("Not available here", "Bu alanda kullanılamaz"), Msg::EditorUndo => ("Undo", "Geri al"), Msg::EditorRedo => ("Redo", "Yinele"), Msg::EditorParagraph => ("Paragraph", "Metin"), Msg::EditorHeading1 => ("Heading 1", "Başlık 1"), Msg::EditorHeading2 => ("Heading 2", "Başlık 2"), Msg::EditorHeading3 => ("Heading 3", "Başlık 3"), Msg::EditorBold => ("Bold", "Kalın"), Msg::EditorItalic => ("Italic", "İtalik"), Msg::EditorInlineCode => ("Inline code", "Kod"), Msg::EditorLink => ("Link", "Bağlantı"), Msg::EditorBulletList => ("Bullet list", "Madde listesi"), Msg::EditorNumberedList => ("Numbered list", "Numaralı liste"), Msg::EditorQuote => ("Quote", "Alıntı"), Msg::EditorCodeBlock => ("Code block", "Kod bloğu"), Msg::EditorDivider => ("Divider", "Ayırıcı"), Msg::EditorText => ("Text", "Metin"), Msg::EditorLinkDialog => ("Link", "Bağlantı"), Msg::EditorLinkMenu => ("Link options", "Bağlantı seçenekleri"), Msg::EditorLinkUrl => ("Link URL", "Bağlantı adresi"), Msg::EditorLinkInvalid => ( "Enter a valid link, such as example.com", "Geçerli bir bağlantı girin, ör. example.com", ), Msg::EditorLinkNeedsLink => ("Add a link first", "Önce bir bağlantı ekleyin"), Msg::EditorApply => ("Apply", "Uygula"), Msg::EditorRemove => ("Remove", "Kaldır"), Msg::EditorOpen => ("Open", "Aç"), Msg::EditorEdit => ("Edit", "Düzenle"), Msg::EditorStatusSaved => ("Saved", "Kaydedildi"), Msg::EditorStatusSaving => ("Saving…", "Kaydediliyor…"), Msg::EditorStatusLocal => ("Saved on this device", "Bu cihazda kaydedildi"), Msg::EditorStatusReconnecting => ("Reconnecting…", "Yeniden bağlanıyor…"), Msg::EditorStatusConnecting => ("Connecting…", "Bağlanıyor…"), Msg::EditorAnnounceOffline => ( "You are offline. Changes stay on this device.", "Çevrimdışısınız. Değişiklikler bu cihazda kalır.", ), Msg::EditorAnnounceOnline => ("Back online.", "Yeniden çevrimiçisiniz."), Msg::EditorPasteAsText => ("Paste as plain text", "Düz metin olarak yapıştır"), Msg::EditorNoteMenu => ("Link to a note", "Nota bağlantısı"), Msg::EditorCreateNote => ("Create note “{q}”", "“{q}” notunu oluştur"), Msg::EditorNoNotesFound => ("No notes found", "Not bulunamadı"), Msg::EditorUntitled => ("Untitled", "Adsız"), Msg::EditorCodeLanguage => ("Language", "Dil"), Msg::EditorCodeAuto => ("Auto", "Otomatik"), Msg::EditorCodeFormat => ("Format", "Biçimlendir"), Msg::EditorCodeFormatting => ("Formatting…", "Biçimlendiriliyor…"), Msg::EditorCodeFormatFailed => ("Couldn't format", "Biçimlendirilemedi"), Msg::EditorCodeFormatUnsupported => ("Formatting isn't available for this language", "Bu dil için biçimlendirme yok"), Msg::EditorCodeCopy => ("Copy code", "Kodu kopyala"), Msg::EditorCodeCopied => ("Copied", "Kopyalandı"), Msg::EditorCodeAutoFormat => ("Format when leaving the block", "Bloktan çıkınca biçimlendir"), Msg::EditorAttach => ("Attach file", "Dosya ekle"), Msg::EditorRecordAudio => ("Record audio", "Ses kaydet"), Msg::EditorStopRecording => ("Stop recording", "Kaydı durdur"), Msg::EditorMediaFailed => ("Upload failed", "Yükleme başarısız"), Msg::EditorMicDenied => ("Microphone unavailable", "Mikrofon kullanılamıyor"), Msg::EditorRecordingNow => ("Recording…", "Kaydediliyor…"), Msg::EditorRecordingLost => ("Connection lost, reconnecting…", "Bağlantı koptu, yeniden bağlanılıyor…"), Msg::EditorContinueRecording => ("Continue recording", "Kayda devam et"), }; match lang { Lang::En => en, Lang::Tr => tr, } } /// The editor's UI strings, keyed by their original `web/src/i18n.ts` key, in that file's order. pub const EDITOR_MSGS: &[(&str, Msg)] = &[ ("placeholder", Msg::EditorPlaceholder), ("toolbarLabel", Msg::EditorToolbarLabel), ("bubbleLabel", Msg::EditorBubbleLabel), ("blockMenu", Msg::EditorBlockMenu), ("noMatches", Msg::EditorNoMatches), ("navigate", Msg::EditorNavigate), ("insert", Msg::EditorInsert), ("close", Msg::EditorClose), ("unavailable", Msg::EditorUnavailable), ("undo", Msg::EditorUndo), ("redo", Msg::EditorRedo), ("paragraph", Msg::EditorParagraph), ("heading1", Msg::EditorHeading1), ("heading2", Msg::EditorHeading2), ("heading3", Msg::EditorHeading3), ("bold", Msg::EditorBold), ("italic", Msg::EditorItalic), ("inlineCode", Msg::EditorInlineCode), ("link", Msg::EditorLink), ("bulletList", Msg::EditorBulletList), ("numberedList", Msg::EditorNumberedList), ("quote", Msg::EditorQuote), ("codeBlock", Msg::EditorCodeBlock), ("divider", Msg::EditorDivider), ("text", Msg::EditorText), ("linkDialog", Msg::EditorLinkDialog), ("linkMenu", Msg::EditorLinkMenu), ("linkUrl", Msg::EditorLinkUrl), ("linkInvalid", Msg::EditorLinkInvalid), ("linkNeedsLink", Msg::EditorLinkNeedsLink), ("apply", Msg::EditorApply), ("remove", Msg::EditorRemove), ("open", Msg::EditorOpen), ("edit", Msg::EditorEdit), ("statusSaved", Msg::EditorStatusSaved), ("statusSaving", Msg::EditorStatusSaving), ("statusLocal", Msg::EditorStatusLocal), ("statusReconnecting", Msg::EditorStatusReconnecting), ("statusConnecting", Msg::EditorStatusConnecting), ("announceOffline", Msg::EditorAnnounceOffline), ("announceOnline", Msg::EditorAnnounceOnline), ("pasteAsText", Msg::EditorPasteAsText), ("noteMenu", Msg::EditorNoteMenu), ("createNote", Msg::EditorCreateNote), ("noNotesFound", Msg::EditorNoNotesFound), ("untitled", Msg::EditorUntitled), ("codeLanguage", Msg::EditorCodeLanguage), ("codeAuto", Msg::EditorCodeAuto), ("codeFormat", Msg::EditorCodeFormat), ("codeFormatting", Msg::EditorCodeFormatting), ("codeFormatFailed", Msg::EditorCodeFormatFailed), ("codeFormatUnsupported", Msg::EditorCodeFormatUnsupported), ("codeCopy", Msg::EditorCodeCopy), ("codeCopied", Msg::EditorCodeCopied), ("codeAutoFormat", Msg::EditorCodeAutoFormat), ("attach", Msg::EditorAttach), ("recordAudio", Msg::EditorRecordAudio), ("stopRecording", Msg::EditorStopRecording), ("mediaFailed", Msg::EditorMediaFailed), ("micDenied", Msg::EditorMicDenied), ("recordingNow", Msg::EditorRecordingNow), ("recordingLost", Msg::EditorRecordingLost), ("continueRecording", Msg::EditorContinueRecording), ]; /// "1 note" / "3 notes". Turkish does not inflect the noun after a number: "1 not", "3 not". pub fn notes_count(lang: Lang, n: usize) -> String { match lang { Lang::En if n == 1 => "1 note".to_owned(), Lang::En => format!("{n} notes"), Lang::Tr => format!("{n} not"), } } /// "1 result for “rust”" / "3 results for “rust”", or the Turkish "3 sonuç “rust” için". pub fn results_for(lang: Lang, n: usize, query: &str) -> String { match lang { Lang::En if n == 1 => format!("1 result for \u{201c}{query}\u{201d}"), Lang::En => format!("{n} results for \u{201c}{query}\u{201d}"), Lang::Tr => format!("{n} sonuç \u{201c}{query}\u{201d} için"), } } /// The consequence line of the empty-trash dialog: "This deletes 3 notes forever." / /// "3 not kalıcı olarak silinecek." pub fn forever_count(lang: Lang, n: usize) -> String { match lang { Lang::En => format!("This deletes {} forever.", notes_count(lang, n)), Lang::Tr => format!("{} kalıcı olarak silinecek.", notes_count(lang, n)), } } /// A relative time such as "5 min ago" or "5 dk önce", a day name, or a date for older /// times. `now_ms` is the current time in Unix milliseconds. pub fn relative_time(lang: Lang, updated_ms: i64, now_ms: i64) -> String { let secs = (now_ms - updated_ms).max(0) / 1000; let mins = secs / 60; let hours = secs / 3600; let days = secs / 86_400; if secs < 60 { t(lang, Msg::JustNow).to_owned() } else if secs < 3600 { match lang { Lang::En => format!("{mins} min ago"), Lang::Tr => format!("{mins} dk önce"), } } else if secs < 86_400 { match lang { Lang::En => format!("{hours} h ago"), Lang::Tr => format!("{hours} sa önce"), } } else if days == 1 { t(lang, Msg::Yesterday).to_owned() } else if days < 7 { match lang { Lang::En => format!("{days} days ago"), Lang::Tr => format!("{days} gün önce"), } } else { date(lang, updated_ms) } } /// A calendar date in UTC: "Oct 27, 2026" in English, "27 Eki 2026" in Turkish. pub fn date(lang: Lang, ms: i64) -> String { const EN: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const TR: [&str; 12] = [ "Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara", ]; // Civil-from-days (Howard Hinnant's algorithm). let z = ms.div_euclid(86_400_000) + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = doy - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 }; let idx = (month - 1) as usize; match lang { Lang::En => format!("{} {}, {}", EN[idx], day, year), Lang::Tr => format!("{} {} {}", day, TR[idx], year), } } /// A date and UTC time: "Oct 27, 2026 14:05" in English, "27 Eki 2026 14:05" in Turkish. pub fn date_time(lang: Lang, ms: i64) -> String { let minutes = ms.rem_euclid(86_400_000) / 60_000; format!("{} {:02}:{:02}", date(lang, ms), minutes / 60, minutes % 60) } /// Picks the language from an `Accept-Language` header: the first listed language that is /// English or Turkish. Anything else falls back to English. pub fn from_accept_language(header: &str) -> Lang { for part in header.split(',') { let tag = part.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); if tag.starts_with("tr") { return Lang::Tr; } if tag.starts_with("en") { return Lang::En; } } Lang::En } /// The language of this request. The `lang` cookie wins; without it, the browser's /// `Accept-Language` decides; otherwise English. pub fn lang(cx: &Cx) -> Lang { if let Some(cookie) = cookies(cx).get(LANG_COOKIE) { if let Some(lang) = Lang::from_code(cookie.value()) { return lang; } } let header = headers(cx) .get("accept-language") .and_then(|value| value.to_str().ok()) .unwrap_or(""); from_accept_language(header) } /// The cookie that remembers `lang` for a year. pub fn lang_cookie(lang: Lang) -> Cookie<'static> { Cookie::build((LANG_COOKIE, lang.code())) .path("/") .same_site(SameSite::Lax) .max_age(Duration::days(LANG_COOKIE_DAYS)) .build() } /// The editor's strings as a JSON object, safe inside `