Files
nahodka-front/src/utils/foundAt.js
SlimusMinus 6dc61050d9
Some checks failed
deploy-frontend / deploy (push) Failing after 11s
Add Docker build and deploy pipeline
2026-10-07 23:27:38 +03:00

81 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Дата, когда объявление было отмечено как «найдено».
//
// Бэкенд статус отдаёт, но момент перехода в CLOSED в ответе /api/v1/posts
// сейчас не приходит, а в карточке он нужен («Найдено 3 октября»). Поэтому:
// 1) если поле closedAt/closedDate появится в DTO — берём его (приоритет);
// 2) иначе — дата, которую клиент запомнил в момент нажатия «Вернулось к
// владельцу» (rememberFoundAt), т.е. точная для текущего устройства;
// 3) иначе — null: показываем просто «Найдено», без выдуманной даты.
const STORAGE_KEY = "postFoundAt";
// Хранилище не должно расти бесконечно: держим последние отметки.
const MAX_ENTRIES = 100;
function readStore() {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
// Приватный режим / отключённое хранилище — работаем без даты.
return {};
}
}
function writeStore(store) {
try {
const entries = Object.entries(store).slice(-MAX_ENTRIES);
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(Object.fromEntries(entries)));
} catch {
// Не смогли записать — дата просто не запомнится, это не критично.
}
}
export function rememberFoundAt(postId, iso = new Date().toISOString()) {
if (postId === undefined || postId === null) return;
const store = readStore();
store[postId] = iso;
writeStore(store);
}
export function forgetFoundAt(postId) {
const store = readStore();
if (!(postId in store)) return;
delete store[postId];
writeStore(store);
}
export function getFoundAt(ad) {
if (!ad) return null;
return ad.closedAt || ad.closedDate || readStore()[ad.id] || null;
}
/**
* Intl.DateTimeFormat дорого создавать, а дата рендерится в каждой закрытой
* карточке ленты — держим по одному форматтеру на локаль.
*/
const formatterCache = new Map();
function getFormatter(locale) {
const cached = formatterCache.get(locale);
if (cached) return cached;
const formatter = new Intl.DateTimeFormat(locale, { day: "numeric", month: "long" });
formatterCache.set(locale, formatter);
return formatter;
}
/**
* «3 октября» / «October 3» — коротко и по-человечески, без года.
* Возвращает null на невалидную дату, чтобы не показывать «Invalid Date».
*/
export function formatFoundDate(value, language) {
if (!value) return null;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
const locale = language === "en" ? "en-US" : "ru-RU";
try {
return getFormatter(locale).format(date);
} catch {
return date.toLocaleDateString(locale);
}
}