SHA256
Compare commits
44
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
3f0d71f788 | ||
|
|
f2ba7ce630 | ||
|
|
edc3d50136 | ||
|
|
a7a600035a | ||
|
|
3f05806563 | ||
|
|
2fb19ee66d | ||
|
|
d91ca5fbb3 | ||
|
|
7173f33d5f | ||
|
|
b3f9e1fe21 | ||
|
|
401ba918ad | ||
|
|
82d5a768f8 | ||
|
|
835109c81a | ||
|
|
d5f2c12fe7 | ||
|
|
11f169b080 | ||
|
|
96d23b16fc | ||
|
|
26db18e250 | ||
|
|
8fee7e1a9b | ||
|
|
e7cf98889b | ||
|
|
3fdff2a92b | ||
|
|
4d5a485933 | ||
|
|
b9cbbb857b | ||
|
|
56de0f2c74 | ||
|
|
68fe0532ce | ||
|
|
3edde418a2 | ||
|
|
923f281bf6 | ||
|
|
9ea276ba77 | ||
|
|
cfb0f9b734 | ||
|
|
993930eb82 | ||
|
|
17d6cb5be0 | ||
|
|
bb725ee451 | ||
|
|
b5ce7b0fa0 | ||
|
|
58de6a025d | ||
|
|
e6937cb49c | ||
|
|
7ac9e5a806 | ||
|
|
89630878af | ||
|
|
8b2012fad3 | ||
|
|
07ddaf5e4c | ||
|
|
4d10096ba2 | ||
|
|
5e9699613d | ||
|
|
b56a3a795f | ||
|
|
70fac068d0 | ||
|
|
d138bd9464 | ||
|
|
e14e3dfa21 | ||
|
|
30541ae4af |
@@ -79,6 +79,7 @@ shine-solana/shine/scripts/**/TEMP_*.md
|
||||
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
||||
ESP32/esp32-config-tool/
|
||||
ESP32/local-sketches/
|
||||
ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/
|
||||
ESP32/**/.git/
|
||||
ESP32/**/.idea/
|
||||
ESP32-wallet/.idea/
|
||||
|
||||
@@ -47,13 +47,15 @@ case "${MODE}" in
|
||||
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
|
||||
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
|
||||
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
|
||||
breath-dual-mode-monitor) SKETCH_DIR="${ROOT_DIR}/test_sketches/breath_dual_mode_monitor" ;;
|
||||
usb-contact-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_test" ;;
|
||||
usb-contact-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_debug_test" ;;
|
||||
usb-contact-resistance-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_resistance_test" ;;
|
||||
usb-contact-screen-start-stub) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_screen_start_stub" ;;
|
||||
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
||||
*)
|
||||
echo "Unknown mode: ${MODE}" >&2
|
||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, usb-contact-test, usb-contact-debug-test, usb-contact-screen-start-stub" >&2
|
||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, breath-dual-mode-monitor, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
||||
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
||||
- `breath_dual_mode_monitor/` - dual-mode breath monitor в стиле GFX-скетча: старт USB-датчика или внешних кнопок `KEY3/BOOT`, настройки лимита и громкости, повторяющиеся звуковые предупреждения
|
||||
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
||||
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
||||
- `usb_contact_resistance_test/` - тест измерения сопротивления между USB D-/D+ через ADC на GPIO20; рассчитан на внешний известный резистор 10 kΩ с D+ на GND
|
||||
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
||||
|
||||
## Запуск
|
||||
@@ -31,5 +33,7 @@
|
||||
- `./burn.sh lvgl-official-based-test`
|
||||
- `./burn.sh lvgl-subserver-touch-test`
|
||||
- `./burn.sh lvgl-russian-font-test`
|
||||
- `./burn.sh breath-dual-mode-monitor`
|
||||
- `./burn.sh usb-contact-test`
|
||||
- `./burn.sh usb-contact-debug-test`
|
||||
- `./burn.sh usb-contact-resistance-test`
|
||||
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <lvgl.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include "pin_config.h"
|
||||
#include "TouchDrvCSTXXX.hpp"
|
||||
|
||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
||||
|
||||
// ESP32-S3 native USB data pins.
|
||||
static constexpr int kUsbDmPin = 19; // USB D-
|
||||
static constexpr int kUsbDpPin = 20; // USB D+, ADC input in resistance mode.
|
||||
static constexpr uint32_t kUiRefreshMs = 120;
|
||||
static constexpr uint32_t kAdcSamples = 32;
|
||||
|
||||
// For a stable ohm reading connect a known resistor from D+ / GPIO20 to GND.
|
||||
// The measured resistance must be connected between D- / GPIO19 and D+ / GPIO20.
|
||||
static constexpr float kKnownPulldownOhms = 10000.0f;
|
||||
static constexpr float kSourceMillivolts = 3300.0f;
|
||||
static constexpr float kOpenThresholdMillivolts = 25.0f;
|
||||
|
||||
static lv_disp_draw_buf_t gDrawBuf;
|
||||
static lv_color_t *gBuf1 = nullptr;
|
||||
static lv_color_t *gBuf2 = nullptr;
|
||||
static lv_obj_t *gModeLabel = nullptr;
|
||||
static lv_obj_t *gResistanceLabel = nullptr;
|
||||
static lv_obj_t *gRawLabel = nullptr;
|
||||
static lv_obj_t *gHintLabel = nullptr;
|
||||
static lv_obj_t *gActionButton = nullptr;
|
||||
static lv_obj_t *gActionButtonLabel = nullptr;
|
||||
|
||||
static TouchDrvCST92xx gTouch;
|
||||
static int16_t gTouchX[5];
|
||||
static int16_t gTouchY[5];
|
||||
|
||||
static bool gSensorMode = false;
|
||||
static uint32_t gLastUiRefreshMs = 0;
|
||||
|
||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
||||
|
||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
||||
uint32_t w = area->x2 - area->x1 + 1;
|
||||
uint32_t h = area->y2 - area->y1 + 1;
|
||||
#if (LV_COLOR_16_SWAP != 0)
|
||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#else
|
||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#endif
|
||||
lv_disp_flush_ready(disp);
|
||||
}
|
||||
|
||||
static void lvglTick(void *arg) {
|
||||
LV_UNUSED(arg);
|
||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
||||
LV_UNUSED(indevDrv);
|
||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
||||
if (touched > 0) {
|
||||
data->state = LV_INDEV_STATE_PR;
|
||||
data->point.x = gTouchX[0];
|
||||
data->point.y = gTouchY[0];
|
||||
return;
|
||||
}
|
||||
data->state = LV_INDEV_STATE_REL;
|
||||
}
|
||||
|
||||
static uint32_t readAverageRaw() {
|
||||
uint32_t sum = 0;
|
||||
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||
sum += analogRead(kUsbDpPin);
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
return sum / kAdcSamples;
|
||||
}
|
||||
|
||||
static uint32_t readAverageMillivolts() {
|
||||
uint32_t sum = 0;
|
||||
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||
sum += analogReadMilliVolts(kUsbDpPin);
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
return sum / kAdcSamples;
|
||||
}
|
||||
|
||||
static void setResistanceText(float ohms) {
|
||||
if (ohms >= 1000000.0f) {
|
||||
String text = String(ohms / 1000000.0f, 2) + " Mohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
} else if (ohms >= 1000.0f) {
|
||||
String text = String(ohms / 1000.0f, 2) + " kohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
} else {
|
||||
String text = String(ohms, 0) + " ohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
static void updateResistanceUi() {
|
||||
if (!gSensorMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
if (now - gLastUiRefreshMs < kUiRefreshMs) {
|
||||
return;
|
||||
}
|
||||
gLastUiRefreshMs = now;
|
||||
|
||||
uint32_t raw = readAverageRaw();
|
||||
uint32_t millivolts = readAverageMillivolts();
|
||||
|
||||
if (millivolts <= kOpenThresholdMillivolts) {
|
||||
lv_label_set_text(gResistanceLabel, "OPEN");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0xFFD166), 0);
|
||||
} else if (millivolts >= (uint32_t)(kSourceMillivolts - 80.0f)) {
|
||||
lv_label_set_text(gResistanceLabel, "SHORT / LOW");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
} else {
|
||||
float rx = kKnownPulldownOhms * ((kSourceMillivolts / (float)millivolts) - 1.0f);
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
setResistanceText(rx);
|
||||
}
|
||||
|
||||
String rawText = "ADC raw: " + String(raw);
|
||||
rawText += "\nD+ voltage: " + String(millivolts) + " mV";
|
||||
rawText += "\nKnown pulldown: 10 kohm to GND";
|
||||
lv_label_set_text(gRawLabel, rawText.c_str());
|
||||
}
|
||||
|
||||
static void enterSensorMode() {
|
||||
Serial.flush();
|
||||
delay(30);
|
||||
|
||||
pinMode(kUsbDmPin, OUTPUT);
|
||||
digitalWrite(kUsbDmPin, HIGH);
|
||||
|
||||
pinMode(kUsbDpPin, INPUT);
|
||||
analogReadResolution(12);
|
||||
analogSetPinAttenuation(kUsbDpPin, ADC_11db);
|
||||
|
||||
gSensorMode = true;
|
||||
gLastUiRefreshMs = 0;
|
||||
|
||||
lv_label_set_text(gModeLabel, "Resistance mode");
|
||||
lv_label_set_text(gHintLabel, "D- is 3.3V source. D+ is ADC input.\nUse 10 kohm from D+ to GND for accurate readings.");
|
||||
lv_label_set_text(gActionButtonLabel, "Restart to USB");
|
||||
updateResistanceUi();
|
||||
}
|
||||
|
||||
static void actionButtonEventCb(lv_event_t *event) {
|
||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!gSensorMode) {
|
||||
enterSensorMode();
|
||||
return;
|
||||
}
|
||||
|
||||
lv_label_set_text(gModeLabel, "Restarting...");
|
||||
lv_label_set_text(gHintLabel, "USB mode will return after reboot.");
|
||||
lv_timer_handler();
|
||||
delay(150);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void createUi() {
|
||||
lv_obj_t *screen = lv_scr_act();
|
||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||
|
||||
lv_obj_t *title = lv_label_create(screen);
|
||||
lv_label_set_text(title, "USB RESISTANCE TEST");
|
||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 24);
|
||||
|
||||
gModeLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gModeLabel, "USB mode");
|
||||
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0xB8C8DC), 0);
|
||||
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
|
||||
lv_obj_align(gModeLabel, LV_ALIGN_TOP_MID, 0, 68);
|
||||
|
||||
gResistanceLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gResistanceLabel, "READY");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_obj_set_style_text_font(gResistanceLabel, &lv_font_montserrat_40, 0);
|
||||
lv_obj_align(gResistanceLabel, LV_ALIGN_CENTER, 0, -72);
|
||||
|
||||
gRawLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gRawLabel, "ADC raw: -\nD+ voltage: -\nKnown pulldown: 10 kohm to GND");
|
||||
lv_obj_set_width(gRawLabel, 420);
|
||||
lv_label_set_long_mode(gRawLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gRawLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0xD5DCE5), 0);
|
||||
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_16, 0);
|
||||
lv_obj_align(gRawLabel, LV_ALIGN_CENTER, 0, -8);
|
||||
|
||||
gHintLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gHintLabel, "USB is normal now.\nTap Start to measure resistance between D- and D+.");
|
||||
lv_obj_set_width(gHintLabel, 420);
|
||||
lv_label_set_long_mode(gHintLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gHintLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_color(gHintLabel, lv_color_hex(0xAAB7C6), 0);
|
||||
lv_obj_set_style_text_font(gHintLabel, &lv_font_montserrat_14, 0);
|
||||
lv_obj_align(gHintLabel, LV_ALIGN_CENTER, 0, 72);
|
||||
|
||||
gActionButton = lv_btn_create(screen);
|
||||
lv_obj_set_size(gActionButton, 260, 72);
|
||||
lv_obj_align(gActionButton, LV_ALIGN_BOTTOM_MID, 0, -42);
|
||||
lv_obj_set_style_radius(gActionButton, 18, 0);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), 0);
|
||||
lv_obj_set_style_border_width(gActionButton, 0, 0);
|
||||
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_CLICKED, nullptr);
|
||||
|
||||
gActionButtonLabel = lv_label_create(gActionButton);
|
||||
lv_label_set_text(gActionButtonLabel, "Start");
|
||||
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_22, 0);
|
||||
lv_obj_center(gActionButtonLabel);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
Wire.begin(IIC_SDA, IIC_SCL);
|
||||
|
||||
pinMode(TP_RST, OUTPUT);
|
||||
pinMode(TP_INT, INPUT);
|
||||
digitalWrite(TP_RST, LOW);
|
||||
delay(30);
|
||||
digitalWrite(TP_RST, HIGH);
|
||||
delay(50);
|
||||
delay(1000);
|
||||
|
||||
gTouch.setPins(TP_RST, TP_INT);
|
||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
||||
if (!touchOk) {
|
||||
Serial.println("Touch init failed");
|
||||
} else {
|
||||
gTouch.sleep();
|
||||
gTouch.reset();
|
||||
gTouch.setMaxCoordinates(480, 480);
|
||||
gTouch.setSwapXY(true);
|
||||
gTouch.setMirrorXY(true, false);
|
||||
}
|
||||
|
||||
gfx->begin();
|
||||
gBus->writeC8D8(0x36, 0xA0);
|
||||
gfx->setBrightness(220);
|
||||
gfx->fillScreen(0x0000);
|
||||
|
||||
lv_init();
|
||||
|
||||
uint32_t screenWidth = gfx->width();
|
||||
uint32_t screenHeight = gfx->height();
|
||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
||||
|
||||
static lv_disp_drv_t dispDrv;
|
||||
lv_disp_drv_init(&dispDrv);
|
||||
dispDrv.hor_res = screenWidth;
|
||||
dispDrv.ver_res = screenHeight;
|
||||
dispDrv.flush_cb = lvglFlushCb;
|
||||
dispDrv.draw_buf = &gDrawBuf;
|
||||
lv_disp_drv_register(&dispDrv);
|
||||
|
||||
static lv_indev_drv_t indevDrv;
|
||||
lv_indev_drv_init(&indevDrv);
|
||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
||||
indevDrv.read_cb = lvglTouchRead;
|
||||
lv_indev_drv_register(&indevDrv);
|
||||
|
||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
||||
.callback = &lvglTick,
|
||||
.name = "lvgl_tick"};
|
||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
||||
|
||||
createUi();
|
||||
Serial.println("USB resistance test ready; native USB remains active until Start is tapped.");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
updateResistanceUi();
|
||||
lv_timer_handler();
|
||||
delay(5);
|
||||
}
|
||||
@@ -4,6 +4,8 @@ Diagnostic sketches:
|
||||
|
||||
- `main-device/test_sketches/usb_contact_sensor_test/usb_contact_sensor_test.ino`
|
||||
- `main-device/test_sketches/usb_contact_sensor_debug_test/usb_contact_sensor_debug_test.ino`
|
||||
- `main-device/test_sketches/breath_dual_mode_monitor/breath_dual_mode_monitor.ino`
|
||||
- `main-device/test_sketches/usb_contact_resistance_test/usb_contact_resistance_test.ino`
|
||||
- `main-device/test_sketches/usb_contact_screen_start_stub/usb_contact_screen_start_stub.ino`
|
||||
|
||||
## Purpose
|
||||
@@ -51,6 +53,33 @@ Sensor mode starts from the physical BOOT/user button on GPIO0, active LOW. The
|
||||
|
||||
While in sensor mode, pressing the BOOT/user button again restarts the device and returns normal USB mode on the next boot.
|
||||
|
||||
## Resistance version
|
||||
|
||||
The `usb_contact_resistance_test` sketch starts in normal USB mode and does not reconfigure GPIO19/20 until `Start` is tapped.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `USB RESISTANCE TEST`
|
||||
- mode: `USB mode`
|
||||
- state: `READY`
|
||||
- action button: `Start`
|
||||
|
||||
After `Start`:
|
||||
|
||||
- GPIO19 / USB `D-` is configured as `OUTPUT HIGH`
|
||||
- GPIO20 / USB `D+` is configured as ADC input
|
||||
- the measured resistance is connected between `D-` and `D+`
|
||||
- a known external 10 kΩ pulldown resistor must be connected from `D+` to `GND` for meaningful ohm calculation
|
||||
- UI shows calculated resistance, raw ADC value, and measured `D+` millivolts
|
||||
- very low ADC voltage is shown as `OPEN`
|
||||
- near-source voltage is shown as `SHORT / LOW`
|
||||
|
||||
The calculation assumes a divider where the unknown resistance is the high-side resistor from 3.3 V to ADC and the known 10 kΩ resistor is the low-side resistor from ADC to GND:
|
||||
|
||||
`Rx = 10000 * (3300 / Vadc - 1)`
|
||||
|
||||
This test is intended to check whether the USB contact pair can be reused as an ADC-measured resistance input, for example before wiring a 10 kΩ potentiometer. Native USB data is unavailable while resistance mode owns GPIO19/20. Pressing `Restart to USB` calls `ESP.restart()`; after reboot normal USB mode is restored.
|
||||
|
||||
## GFX breath monitor version
|
||||
|
||||
The `usb_contact_screen_start_stub` sketch is a breath monitor firmware based on the production `Arduino_GFX` display path instead of LVGL.
|
||||
@@ -86,3 +115,45 @@ After tapping `START`:
|
||||
- reset/power cycle restores ordinary native USB boot
|
||||
|
||||
This version is intended to monitor breathing cadence from a dry-contact USB D-/D+ sensor.
|
||||
|
||||
## Dual-mode GFX breath monitor version
|
||||
|
||||
The `breath_dual_mode_monitor` sketch reuses the production-style `Arduino_GFX` visual approach, audio path, settings sliders, and average-cycle alert behavior from the USB contact breath monitor. It supports two start modes on one firmware: USB contact sensor mode and external button mode.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `BREATH MONITOR`
|
||||
- state: `READY`
|
||||
- action button: `START USB SENSOR`
|
||||
- action button: `START BUTTONS`
|
||||
|
||||
After `START USB SENSOR`:
|
||||
|
||||
- GPIO19 / USB `D-` is configured as `OUTPUT LOW`
|
||||
- GPIO20 / USB `D+` is configured as `INPUT_PULLUP`
|
||||
- closed contact is treated as `EXHALE`
|
||||
- open contact is treated as `INHALE`
|
||||
- USB sensor cycles shorter than 3 seconds are ignored without resetting the current cycle timer
|
||||
- a short `KEY3 / GPIO18` press opens or closes settings in USB sensor mode
|
||||
- the bottom line shows the durations of the last 5 accepted USB sensor cycles
|
||||
|
||||
After `START BUTTONS`:
|
||||
|
||||
- `KEY3 / GPIO18` is the external `INHALE` button, active LOW
|
||||
- `BOOT / GPIO0` is the external `EXHALE` button, active LOW
|
||||
- do not hold `BOOT` while booting or resetting the board
|
||||
- the working screen does not show touch `INHALE`/`EXHALE` buttons
|
||||
- long-holding `KEY3 / INHALE` for about 850 ms opens settings; the long press still counts as an inhale press
|
||||
- while settings are open, the next `KEY3 / INHALE` press closes settings and also counts as an inhale press
|
||||
|
||||
In both modes:
|
||||
|
||||
- one breathing cycle is measured from one `EXHALE` tap to the next `EXHALE` tap
|
||||
- inhale before any exhale does not create a cycle
|
||||
- button-mode cycles shorter than 1.5 seconds are ignored
|
||||
- USB sensor cycles shorter than 3 seconds are ignored
|
||||
- the UI shows current cycle time, arithmetic average over the last 5 completed cycles, elapsed session time, selected limit, long-pause count, short-average count, and current short-average streak
|
||||
- the lower numeric fields use a larger font than before
|
||||
- if the average of the last up to 5 completed cycles is shorter than the selected limit, warning beeps are played like in the USB contact breath monitor
|
||||
- if the current cycle reaches 60 seconds, 5 loud warning beeps are played, then after 5 seconds another 5 loud warning beeps are played, repeating until the user changes phase / exits the long cycle
|
||||
- settings keep the same sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
|
||||
|
||||
@@ -22,8 +22,10 @@ public final class DatabaseInitializer {
|
||||
public static final int DB_FORMAT_VERSION = 2;
|
||||
public static final int SCHEMA_VERSION_1 = 1;
|
||||
public static final int SCHEMA_VERSION_31 = 31;
|
||||
public static final int SCHEMA_VERSION_32 = 32;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -119,9 +121,13 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_31) {
|
||||
if (currentVersion == SCHEMA_VERSION_31) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_32) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 31, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 32, found " + currentVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Read-only поиск по серверному индексу актуальных публичных каналов. */
|
||||
public final class ChannelSearchDAO {
|
||||
private ChannelSearchDAO() {}
|
||||
|
||||
public record Match(String ownerLogin, String slug, String displayName, String description,
|
||||
String avatarAr, String avatarSha256, String ownerBlockchainName,
|
||||
int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {}
|
||||
|
||||
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
|
||||
private static String escapedPattern(String text) {
|
||||
return text.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||
}
|
||||
|
||||
private static String normalized(String text) {
|
||||
return (text == null ? "" : text.trim()).toLowerCase(Locale.ROOT).replace('ё', 'е');
|
||||
}
|
||||
|
||||
public static List<Match> search(Connection c, String query, String ownerLogin, int limit) throws SQLException {
|
||||
String needle = normalized(query).replaceFirst("^@", "");
|
||||
String ownerFilter = normalized(ownerLogin).replaceFirst("^@", "");
|
||||
boolean ownerOnly = query != null && query.trim().startsWith("@") && !needle.contains("/");
|
||||
String channelNeedle = needle;
|
||||
if (needle.contains("/")) {
|
||||
String[] parts = needle.split("/", 2);
|
||||
if (ownerFilter.isBlank()) ownerFilter = parts[0];
|
||||
channelNeedle = parts[1];
|
||||
}
|
||||
// Если указан owner/название, техническое и публичное название ищем только у владельца.
|
||||
boolean hasOwner = !ownerFilter.isBlank();
|
||||
String exact = channelNeedle;
|
||||
String anywhere = "%" + escapedPattern(exact) + "%";
|
||||
String prefix = escapedPattern(exact) + "%";
|
||||
String ownerExact = ownerFilter;
|
||||
String ownerPrefix = escapedPattern(ownerExact) + "%";
|
||||
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
|
||||
String sql = """
|
||||
SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description,
|
||||
cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
|
||||
cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash,
|
||||
COALESCE(cs.subscribers_count, 0) AS subscribers_count
|
||||
FROM channel_names_state cn
|
||||
LEFT JOIN channel_stats_state cs
|
||||
ON cs.owner_bch_name = cn.owner_bch_name
|
||||
AND cs.channel_root_block_number = cn.channel_root_block_number
|
||||
AND cs.channel_root_block_hash = cn.channel_root_block_hash
|
||||
WHERE cn.channel_type_code = 1 AND NOT cn.is_deleted
|
||||
AND (? = '' OR replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||
AND (
|
||||
(? = true AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||
OR (? = false AND (
|
||||
replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!'
|
||||
OR replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!'
|
||||
OR (? = false AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||
OR (? = true AND ? = '' AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||
))
|
||||
)
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN replace(lower(cn.display_name), 'ё','е') = ? THEN 0
|
||||
WHEN replace(lower(cn.slug), 'ё','е') = ? THEN 1
|
||||
WHEN replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!' THEN 2
|
||||
WHEN replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!' THEN 3
|
||||
WHEN replace(lower(cn.owner_login), 'ё','е') = ? THEN 4
|
||||
WHEN replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!' THEN 5
|
||||
WHEN replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!' THEN 6
|
||||
ELSE 7
|
||||
END,
|
||||
COALESCE(cs.subscribers_count, 0) DESC,
|
||||
lower(cn.owner_login), lower(cn.slug), cn.owner_bch_name
|
||||
LIMIT ?
|
||||
""";
|
||||
// ownerOnly = поиск @login. Когда указан владелец — ограничиваем выборку,
|
||||
// а пустой сегмент / означает «все каналы этого пользователя».
|
||||
String term = exact;
|
||||
boolean filterByOwner = hasOwner && !ownerOnly;
|
||||
List<Match> matches = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, filterByOwner ? ownerFilter : "");
|
||||
ps.setString(i++, ownerPrefix);
|
||||
ps.setBoolean(i++, ownerOnly);
|
||||
ps.setString(i++, "%" + escapedPattern(term) + "%");
|
||||
ps.setBoolean(i++, ownerOnly);
|
||||
ps.setString(i++, anywhere);
|
||||
ps.setString(i++, anywhere);
|
||||
ps.setBoolean(i++, filterByOwner);
|
||||
ps.setString(i++, anywhere);
|
||||
ps.setBoolean(i++, filterByOwner);
|
||||
ps.setString(i++, exact);
|
||||
ps.setString(i++, ownerAnywhere);
|
||||
ps.setString(i++, term);
|
||||
ps.setString(i++, term);
|
||||
ps.setString(i++, prefix);
|
||||
ps.setString(i++, prefix);
|
||||
ps.setString(i++, term);
|
||||
ps.setString(i++, anywhere);
|
||||
ps.setString(i++, anywhere);
|
||||
ps.setInt(i, Math.min(50, Math.max(1, limit)));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) matches.add(new Match(
|
||||
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"),
|
||||
rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_sha256"),
|
||||
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"),
|
||||
rs.getString("root_hash"), rs.getInt("subscribers_count")
|
||||
));
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,53 @@ public final class CurrentUsersDAO {
|
||||
}
|
||||
}
|
||||
|
||||
/** Поиск логинов и публичных имён; результат не раскрывает приватные ключи PDA. */
|
||||
public record SearchUserCard(String login, String displayName, String avatarAr) {}
|
||||
|
||||
public List<SearchUserCard> searchDirectory(String query, Boolean isServer, int limit) throws SQLException {
|
||||
String term = query.trim().toLowerCase(java.util.Locale.ROOT).replace('ё', 'е');
|
||||
String escaped = term.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||
String sql = """
|
||||
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
||||
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
|
||||
FROM solana_user_pda_current su
|
||||
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
|
||||
WHERE (? IS NULL OR su.is_server = ?)
|
||||
AND (
|
||||
replace(lower(su.login), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||
OR replace(lower(coalesce(up.first_name, '') || ' ' || coalesce(up.last_name, '')), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||
OR replace(lower(coalesce(up.last_name, '') || ' ' || coalesce(up.first_name, '')), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||
)
|
||||
ORDER BY
|
||||
CASE WHEN replace(lower(su.login), 'ё','е') = ? THEN 0
|
||||
WHEN replace(lower(su.login), 'ё','е') LIKE ? ESCAPE '!' THEN 1
|
||||
WHEN replace(lower(coalesce(up.first_name, '') || ' ' || coalesce(up.last_name, '')), 'ё', 'е') LIKE ? ESCAPE '!' THEN 2
|
||||
ELSE 3 END,
|
||||
lower(su.login)
|
||||
LIMIT ?
|
||||
""";
|
||||
List<SearchUserCard> users = new ArrayList<>();
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
if (isServer == null) { ps.setNull(i++, Types.BOOLEAN); ps.setNull(i++, Types.BOOLEAN); }
|
||||
else { ps.setBoolean(i++, isServer); ps.setBoolean(i++, isServer); }
|
||||
ps.setString(i++, escaped + "%");
|
||||
ps.setString(i++, "%" + escaped + "%");
|
||||
ps.setString(i++, "%" + escaped + "%");
|
||||
ps.setString(i++, term);
|
||||
ps.setString(i++, escaped + "%");
|
||||
ps.setString(i++, escaped + "%");
|
||||
ps.setInt(i, Math.min(50, Math.max(1, limit)));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
String publicName = (rs.getString("first_name") + " " + rs.getString("last_name")).trim();
|
||||
users.add(new SearchUserCard(rs.getString("login"), publicName, rs.getString("ava_ar")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
// -------------------- MAPPER --------------------
|
||||
|
||||
private CurrentUserEntry mapRow(ResultSet rs) throws SQLException {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Поиск публичных каналов и отображаемых имён (SHiNE DB v32).
|
||||
BEGIN;
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_display
|
||||
ON channel_names_state USING gin ((replace(lower(display_name), 'ё', 'е')) gin_trgm_ops)
|
||||
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_slug
|
||||
ON channel_names_state USING gin ((replace(lower(slug), 'ё', 'е')) gin_trgm_ops)
|
||||
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_owner
|
||||
ON channel_names_state USING gin ((replace(lower(owner_login), 'ё', 'е')) gin_trgm_ops)
|
||||
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name
|
||||
ON user_profile_state USING gin ((replace(lower(coalesce(first_name, '') || ' ' || coalesce(last_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name_reverse
|
||||
ON user_profile_state USING gin ((replace(lower(coalesce(last_name, '') || ' ' || coalesce(first_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||
UPDATE db_schema_version SET schema_version = 32,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id = 1;
|
||||
COMMIT;
|
||||
@@ -2658,6 +2658,15 @@ CREATE TABLE IF NOT EXISTS canonical_rebuild_staging (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_canonical_rebuild_staging_login ON canonical_rebuild_staging(login,logical_block_number);
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,31,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
|
||||
-- v32: триграммные индексы публичного поиска.
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_display ON channel_names_state USING gin ((replace(lower(display_name), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_slug ON channel_names_state USING gin ((replace(lower(slug), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_names_search_owner ON channel_names_state USING gin ((replace(lower(owner_login), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name ON user_profile_state USING gin ((replace(lower(coalesce(first_name, '') || ' ' || coalesce(last_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name_reverse ON user_profile_state USING gin ((replace(lower(coalesce(last_name, '') || ' ' || coalesce(first_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,32,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
|
||||
COMMIT;
|
||||
|
||||
+4
@@ -96,6 +96,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handle
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListGroupChats200_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListSubscriptionsFeed_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_SearchChannels_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetUserCounters_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_SetChannelReadState_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelsCounters_Request;
|
||||
@@ -106,6 +107,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageLi
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetPersonalDiary_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SetChannelReadState_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.connections.Net_GetUserConnectionsGraph_Handler;
|
||||
@@ -182,6 +184,7 @@ public final class JsonHandlerRegistry {
|
||||
private static final Map<String, JsonMessageHandler> HANDLERS = Map.ofEntries(
|
||||
Map.entry("GetUser", new Net_GetUser_Handler()),
|
||||
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
||||
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
||||
@@ -286,6 +289,7 @@ public final class JsonHandlerRegistry {
|
||||
private static final Map<String, Class<? extends Net_Request>> REQUEST_TYPES = Map.ofEntries(
|
||||
Map.entry("GetUser", Net_GetUser_Request.class),
|
||||
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
||||
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
||||
|
||||
+4
-1
@@ -20,7 +20,10 @@ public final class RemoteUserOperationPolicy {
|
||||
"ClientErrorLog",
|
||||
"ClientDebugLog",
|
||||
"CloseActiveSession",
|
||||
"ResolveLoginForAuth"
|
||||
"ResolveLoginForAuth",
|
||||
// Публичный read-only поиск доступен и REMOTE-сессии.
|
||||
"SearchChannels",
|
||||
"SearchUsers"
|
||||
);
|
||||
|
||||
private RemoteUserOperationPolicy() {}
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
import shine.db.dao.ChannelSearchDAO;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Net_SearchChannels_Handler implements JsonMessageHandler {
|
||||
@Override
|
||||
public Net_Response handle(Net_Request base, ConnectionContext ctx) {
|
||||
Net_SearchChannels_Request req = (Net_SearchChannels_Request) base;
|
||||
String query = req.getQuery() == null ? "" : req.getQuery().trim();
|
||||
String owner = req.getOwnerLogin() == null ? "" : req.getOwnerLogin().trim();
|
||||
if ((query.isEmpty() && owner.isEmpty()) || query.equals("@") || query.startsWith("/")
|
||||
|| query.startsWith("@/") || query.length() > 120 || owner.length() > 80
|
||||
|| (req.getLimit() != null && (req.getLimit() < 1 || req.getLimit() > 50))) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||
"BAD_FIELDS", "Нужен query или ownerLogin; limit от 1 до 50; длина query до 120 символов.");
|
||||
}
|
||||
int limit = req.getLimit() == null ? 10 : req.getLimit();
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
List<Net_SearchChannels_Response.ChannelItem> channels = new ArrayList<>();
|
||||
for (var match : ChannelSearchDAO.search(c, query, owner, limit)) {
|
||||
var item = new Net_SearchChannels_Response.ChannelItem();
|
||||
item.setOwnerLogin(match.ownerLogin()); item.setSlug(match.slug());
|
||||
item.setDisplayName(match.displayName()); item.setDescription(match.description());
|
||||
item.setAvatarAr(match.avatarAr()); item.setAvatarSha256(match.avatarSha256());
|
||||
item.setOwnerBlockchainName(match.ownerBlockchainName());
|
||||
item.setRootBlockNumber(match.rootBlockNumber()); item.setRootBlockHashHex(match.rootBlockHashHex());
|
||||
item.setSubscribersCount(match.subscribersCount());
|
||||
channels.add(item);
|
||||
}
|
||||
var resp = new Net_SearchChannels_Response();
|
||||
resp.setOp(req.getOp()); resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK); resp.setChannels(channels);
|
||||
return resp;
|
||||
} catch (SQLException e) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR,
|
||||
"DB_ERROR", "Ошибка БД при поиске каналов");
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** Поиск публичных каналов по названию, slug и логину владельца. */
|
||||
public class Net_SearchChannels_Request extends Net_Request {
|
||||
private String query;
|
||||
private String ownerLogin;
|
||||
private Integer limit;
|
||||
|
||||
public String getQuery() { return query; }
|
||||
public void setQuery(String query) { this.query = query; }
|
||||
public String getOwnerLogin() { return ownerLogin; }
|
||||
public void setOwnerLogin(String ownerLogin) { this.ownerLogin = ownerLogin; }
|
||||
public Integer getLimit() { return limit; }
|
||||
public void setLimit(Integer limit) { this.limit = limit; }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Net_SearchChannels_Response extends Net_Response {
|
||||
private List<ChannelItem> channels = new ArrayList<>();
|
||||
public List<ChannelItem> getChannels() { return channels; }
|
||||
public void setChannels(List<ChannelItem> channels) { this.channels = channels; }
|
||||
|
||||
public static class ChannelItem {
|
||||
private String ownerLogin, slug, displayName, description, avatarAr, avatarSha256,
|
||||
ownerBlockchainName, rootBlockHashHex;
|
||||
private int rootBlockNumber, subscribersCount;
|
||||
public String getOwnerLogin() { return ownerLogin; }
|
||||
public void setOwnerLogin(String v) { ownerLogin = v; }
|
||||
public String getSlug() { return slug; }
|
||||
public void setSlug(String v) { slug = v; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String v) { displayName = v; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String v) { description = v; }
|
||||
public String getAvatarAr() { return avatarAr; }
|
||||
public void setAvatarAr(String v) { avatarAr = v; }
|
||||
public String getAvatarSha256() { return avatarSha256; }
|
||||
public void setAvatarSha256(String v) { avatarSha256 = v; }
|
||||
public String getOwnerBlockchainName() { return ownerBlockchainName; }
|
||||
public void setOwnerBlockchainName(String v) { ownerBlockchainName = v; }
|
||||
public int getRootBlockNumber() { return rootBlockNumber; }
|
||||
public void setRootBlockNumber(int v) { rootBlockNumber = v; }
|
||||
public String getRootBlockHashHex() { return rootBlockHashHex; }
|
||||
public void setRootBlockHashHex(String v) { rootBlockHashHex = v; }
|
||||
public int getSubscribersCount() { return subscribersCount; }
|
||||
public void setSubscribersCount(int v) { subscribersCount = v; }
|
||||
}
|
||||
}
|
||||
+14
-7
@@ -25,7 +25,8 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_SearchUsers_Request req = (Net_SearchUsers_Request) baseRequest;
|
||||
|
||||
if (req.getPrefix() == null || req.getPrefix().isBlank()) {
|
||||
if (req.getPrefix() == null || req.getPrefix().isBlank() || req.getPrefix().length() > 120
|
||||
|| (req.getLimit() != null && (req.getLimit() < 1 || req.getLimit() > 50))) {
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.BAD_REQUEST,
|
||||
@@ -39,13 +40,18 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
||||
|
||||
try {
|
||||
CurrentUsersDAO dao = CurrentUsersDAO.getInstance();
|
||||
List<CurrentUserEntry> users = dao.searchByLoginPrefix(prefix, isServer); // case-insensitive + LIMIT 5
|
||||
|
||||
// Старые клиенты по-прежнему получают массив строк logins.
|
||||
// Новый поиск дополнительно учитывает человекочитаемое имя.
|
||||
var cards = dao.searchDirectory(prefix, isServer, req.getLimit() == null ? 5 : req.getLimit());
|
||||
List<String> logins = new ArrayList<>();
|
||||
for (CurrentUserEntry u : users) {
|
||||
if (u != null && u.getLogin() != null) {
|
||||
logins.add(u.getLogin()); // регистр как в БД
|
||||
}
|
||||
List<Net_SearchUsers_Response.UserItem> users = new ArrayList<>();
|
||||
for (var card : cards) {
|
||||
logins.add(card.login());
|
||||
var item = new Net_SearchUsers_Response.UserItem();
|
||||
item.setLogin(card.login());
|
||||
item.setDisplayName(card.displayName());
|
||||
item.setAvatarAr(card.avatarAr());
|
||||
users.add(item);
|
||||
}
|
||||
|
||||
Net_SearchUsers_Response resp = new Net_SearchUsers_Response();
|
||||
@@ -53,6 +59,7 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
resp.setLogins(logins);
|
||||
resp.setUsers(users);
|
||||
|
||||
log.info("✅ SearchUsers ok: prefix='{}', isServer={} -> {}", prefix, isServer, logins.size());
|
||||
return resp;
|
||||
|
||||
+3
@@ -19,7 +19,10 @@ public class Net_SearchUsers_Request extends Net_Request {
|
||||
|
||||
private String prefix;
|
||||
private Boolean isServer;
|
||||
private Integer limit;
|
||||
|
||||
public Integer getLimit() { return limit; }
|
||||
public void setLimit(Integer value) { limit = value; }
|
||||
public String getPrefix() { return prefix; }
|
||||
public void setPrefix(String prefix) { this.prefix = prefix; }
|
||||
public Boolean getIsServer() { return isServer; }
|
||||
|
||||
+14
@@ -23,6 +23,20 @@ import java.util.List;
|
||||
public class Net_SearchUsers_Response extends Net_Response {
|
||||
|
||||
private List<String> logins = new ArrayList<>();
|
||||
private List<UserItem> users = new ArrayList<>();
|
||||
public List<UserItem> getUsers() { return users; }
|
||||
public void setUsers(List<UserItem> users) { this.users = users; }
|
||||
|
||||
public static class UserItem {
|
||||
private String login, displayName, avatarAr;
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String value) { login = value; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String value) { displayName = value; }
|
||||
public String getAvatarAr() { return avatarAr; }
|
||||
public void setAvatarAr(String value) { avatarAr = value; }
|
||||
}
|
||||
|
||||
|
||||
public List<String> getLogins() { return logins; }
|
||||
public void setLogins(List<String> logins) { this.logins = logins; }
|
||||
|
||||
@@ -14,11 +14,15 @@ import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
@@ -37,10 +41,10 @@ import java.util.regex.Pattern;
|
||||
* имя, расширение, MIME или владельца внутри пути файла. Одинаковые байты всех
|
||||
* пользователей дедуплицируются в один объект: data/public-files/<sha256>.
|
||||
*
|
||||
* В production GET/HEAD /files/<sha256> рекомендуется отдавать Caddy напрямую с
|
||||
* того же каталога и кэшировать Cloudflare. Этот servlet оставляет GET/HEAD как
|
||||
* рабочий fallback; PUT всегда проходит через Java, с проверкой session-signature
|
||||
* и повторным вычислением SHA-256 полученных байтов.
|
||||
* GET поддерживает HTTP Range для потокового просмотра видео без полной загрузки.
|
||||
* Проверка SHA-256 выполняется при PUT; GET/HEAD читают метаданные файла без
|
||||
* повторного хеширования всего содержимого. Caddy также может отдавать immutable
|
||||
* файлы напрямую, если настроен на корректную выдачу байтовых диапазонов и MIME.
|
||||
*/
|
||||
public final class PublicFileServlet extends HttpServlet {
|
||||
|
||||
@@ -202,29 +206,118 @@ public final class PublicFileServlet extends HttpServlet {
|
||||
|
||||
String fileId = extractFileId(req);
|
||||
Path target = fileId == null ? null : safeTarget(fileId);
|
||||
if (target == null || !Files.isRegularFile(target)) {
|
||||
// Не следуем по символическим ссылкам: без повторной проверки хеша GET не должен
|
||||
// иметь возможность прочитать посторонний файл из-за подмены пути.
|
||||
if (target == null || !Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
||||
return;
|
||||
}
|
||||
|
||||
StoredObjectCheck stored = verifyStoredObject(target, fileId);
|
||||
if (!stored.valid()) {
|
||||
Files.deleteIfExists(target);
|
||||
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
||||
return;
|
||||
}
|
||||
|
||||
resp.setStatus(HttpServletResponse.SC_OK);
|
||||
resp.setContentType("application/octet-stream");
|
||||
resp.setHeader("Content-Length", Long.toString(stored.size()));
|
||||
resp.setHeader("ETag", "\"" + fileId + "\"");
|
||||
long size = Files.size(target);
|
||||
String etag = "\"" + fileId + "\"";
|
||||
resp.setHeader("ETag", etag);
|
||||
resp.setHeader("Accept-Ranges", "bytes");
|
||||
resp.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
|
||||
if (!headOnly) {
|
||||
try (InputStream in = Files.newInputStream(target); OutputStream out = resp.getOutputStream()) {
|
||||
in.transferTo(out);
|
||||
resp.setContentType(detectContentType(target));
|
||||
|
||||
// По HTTP заголовок Range относится к GET. Для HEAD отдаём обычные
|
||||
// метаданные целого объекта, что нужно в том числе проверке вложений в UI.
|
||||
String rangeHeader = headOnly ? null : req.getHeader("Range");
|
||||
String ifRange = req.getHeader("If-Range");
|
||||
if (rangeHeader != null && ifRange != null && !ifRange.trim().equals(etag)) {
|
||||
rangeHeader = null; // неподтверждённая версия: отправляем обычный 200
|
||||
}
|
||||
ByteRange range = null;
|
||||
if (rangeHeader != null) {
|
||||
range = parseSingleRange(rangeHeader, size);
|
||||
if (range == null) {
|
||||
resp.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
resp.setHeader("Content-Range", "bytes */" + size);
|
||||
resp.setHeader("Content-Length", "0");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
long firstByte = range == null ? 0L : range.start();
|
||||
long byteCount = range == null ? size : range.length();
|
||||
resp.setStatus(range == null ? HttpServletResponse.SC_OK : HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
resp.setHeader("Content-Length", Long.toString(byteCount));
|
||||
if (range != null) resp.setHeader("Content-Range", "bytes " + range.start() + "-" + range.end() + "/" + size);
|
||||
if (headOnly || byteCount == 0) return;
|
||||
|
||||
// Файловый канал позиционируется в начале запрошенного участка — не читаем
|
||||
// все предыдущие байты и не буферизуем видео целиком в памяти.
|
||||
try (FileChannel channel = FileChannel.open(target, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||
channel.position(firstByte);
|
||||
OutputStream out = resp.getOutputStream();
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
long remaining = byteCount;
|
||||
while (remaining > 0) {
|
||||
ByteBuffer chunk = ByteBuffer.wrap(buffer, 0, (int) Math.min(buffer.length, remaining));
|
||||
int read = channel.read(chunk);
|
||||
if (read < 0) break; // файл мог быть удалён/усечён во время чтения
|
||||
if (read == 0) continue;
|
||||
out.write(buffer, 0, read);
|
||||
remaining -= read;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Поддерживается один диапазон (стандартные запросы браузерных <video>).
|
||||
// Некорректные, составные или не удовлетворяемые диапазоны отвечают 416.
|
||||
static ByteRange parseSingleRange(String header, long size) {
|
||||
if (header == null || !header.startsWith("bytes=") || size <= 0) return null;
|
||||
String value = header.substring("bytes=".length()).trim();
|
||||
if (value.indexOf(',') >= 0) return null;
|
||||
int dash = value.indexOf('-');
|
||||
if (dash < 0 || dash != value.lastIndexOf('-')) return null;
|
||||
String first = value.substring(0, dash).trim();
|
||||
String last = value.substring(dash + 1).trim();
|
||||
if (first.isEmpty() && last.isEmpty()) return null;
|
||||
try {
|
||||
if (first.isEmpty()) {
|
||||
long suffixBytes = Long.parseLong(last);
|
||||
if (suffixBytes <= 0) return null;
|
||||
return new ByteRange(size - Math.min(suffixBytes, size), size - 1);
|
||||
}
|
||||
long start = Long.parseLong(first);
|
||||
if (start < 0 || start >= size) return null;
|
||||
long end = last.isEmpty() ? size - 1 : Long.parseLong(last);
|
||||
if (end < start) return null;
|
||||
return new ByteRange(start, Math.min(end, size - 1));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Объекты на диске не имеют расширений. Тип распознаём по сигнатуре первых
|
||||
// байтов; обычные файлы по-прежнему отдаются как application/octet-stream.
|
||||
private static String detectContentType(Path target) throws IOException {
|
||||
byte[] signature = new byte[16];
|
||||
int count;
|
||||
try (InputStream in = Files.newInputStream(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||
count = in.read(signature);
|
||||
}
|
||||
if (count >= 12 && signature[4] == 'f' && signature[5] == 't'
|
||||
&& signature[6] == 'y' && signature[7] == 'p') {
|
||||
return "video/mp4";
|
||||
}
|
||||
if (count >= 4 && (signature[0] & 0xff) == 0x1a && (signature[1] & 0xff) == 0x45
|
||||
&& (signature[2] & 0xff) == 0xdf && (signature[3] & 0xff) == 0xa3) {
|
||||
return "video/webm";
|
||||
}
|
||||
if (count >= 4 && signature[0] == 'O' && signature[1] == 'g'
|
||||
&& signature[2] == 'g' && signature[3] == 'S') return "video/ogg";
|
||||
if (count >= 12 && signature[0] == 'R' && signature[1] == 'I'
|
||||
&& signature[2] == 'F' && signature[3] == 'F'
|
||||
&& signature[8] == 'A' && signature[9] == 'V'
|
||||
&& signature[10] == 'I' && signature[11] == ' ') return "video/x-msvideo";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
record ByteRange(long start, long end) {
|
||||
long length() { return end - start + 1; }
|
||||
}
|
||||
|
||||
private static StoredObjectCheck verifyStoredObject(Path target, String expectedFileId) throws IOException {
|
||||
@@ -361,8 +454,8 @@ public final class PublicFileServlet extends HttpServlet {
|
||||
resp.setHeader("Access-Control-Allow-Origin", "*");
|
||||
resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, PUT, OPTIONS");
|
||||
resp.setHeader("Access-Control-Allow-Headers",
|
||||
"Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Content-Length, X-Shine-Signature");
|
||||
resp.setHeader("Access-Control-Expose-Headers", "Content-Length, ETag");
|
||||
"Content-Type, Range, If-Range, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Content-Length, X-Shine-Signature");
|
||||
resp.setHeader("Access-Control-Expose-Headers", "Content-Length, ETag, Accept-Ranges, Content-Range, Content-Type");
|
||||
resp.setHeader("Vary", "Origin");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package server.files;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PublicFileRangeTest {
|
||||
|
||||
private static void assertRange(String header, long size, long start, long end) {
|
||||
PublicFileServlet.ByteRange range = PublicFileServlet.parseSingleRange(header, size);
|
||||
assertNotNull(range);
|
||||
assertEquals(start, range.start());
|
||||
assertEquals(end, range.end());
|
||||
assertEquals(end - start + 1, range.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsExplicitOpenAndSuffixRanges() {
|
||||
assertRange("bytes=0-1023", 2048, 0, 1023);
|
||||
assertRange("bytes=1024-", 2048, 1024, 2047);
|
||||
assertRange("bytes=-256", 2048, 1792, 2047);
|
||||
assertRange("bytes=-4096", 2048, 0, 2047);
|
||||
assertRange("bytes=2047-9999", 2048, 2047, 2047);
|
||||
assertRange("bytes=0-0", 2048, 0, 0);
|
||||
assertRange("bytes=0-0", 1, 0, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsatisfiableAndMalformedRanges() {
|
||||
for (String header : new String[] {
|
||||
"bytes=2048-", "bytes=2000-1999", "bytes=-0", "bytes=-", "bytes=0-1,10-20",
|
||||
"bytes=a-b", "bytes=-9223372036854775808", "bytes=9223372036854775808-",
|
||||
"items=0-1", "bytes=-1-2", "bytes=0--1"
|
||||
}) {
|
||||
assertNull(PublicFileServlet.parseSingleRange(header, 2048), header);
|
||||
}
|
||||
assertNull(PublicFileServlet.parseSingleRange("bytes=0-0", 0));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
client.version=1.14.16
|
||||
server.version=1.12.13
|
||||
client.version=1.19.21
|
||||
server.version=1.15.0
|
||||
|
||||
@@ -37,6 +37,28 @@ chmod 755 /home/player/shine-public-files
|
||||
|
||||
## 2. Caddyfile
|
||||
|
||||
### Вариант A: GET/HEAD/PUT через Java (надежный MIME и HTTP Range)
|
||||
|
||||
Для запуска предпросмотра видео проще всего добавить **в каждый site block**
|
||||
(`shineup.me`, `:80` и соответствующие тестовые домены) до общего SPA `handle`:
|
||||
|
||||
```caddyfile
|
||||
@shinePublicFiles path_regexp shine_public_file ^/files/[0-9a-f]{64}$
|
||||
handle @shinePublicFiles {
|
||||
reverse_proxy 127.0.0.1:7070
|
||||
}
|
||||
```
|
||||
|
||||
Java проверяет подпись/хеш при PUT, а при GET поддерживает `206`, Range,
|
||||
`Accept-Ranges`, `Content-Range`, узнаёт MP4/WebM по сигнатуре и отдаёт
|
||||
байты потоково без SHA-256 проверки при каждом скачивании. Маршрут должен
|
||||
располагаться раньше SPA fallback; иначе `/files/<sha256>` может получить HTML.
|
||||
Проверьте порт Java-сервера (в примере `7070`). Для больших потоков это
|
||||
проще в настройке, но нагружает Java больше, чем прямая раздача Caddy.
|
||||
|
||||
### Вариант B: прямая отдача Caddy (лучше для большого трафика)
|
||||
|
||||
|
||||
Маршруты `/files/*` должны стоять **до SPA fallback**.
|
||||
|
||||
```caddyfile
|
||||
@@ -92,7 +114,7 @@ shineup.me {
|
||||
|
||||
Если используется отдельный `:80` site block, тот же `/files` routing нужно добавить и туда либо перенаправлять HTTP на HTTPS.
|
||||
|
||||
После изменения:
|
||||
После изменения любого варианта:
|
||||
|
||||
```bash
|
||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
@@ -142,6 +164,9 @@ UI дополнительно уже отправляет `Cache-Control: no-sto
|
||||
|
||||
```bash
|
||||
curl -I https://shineup.me/files/<sha256>
|
||||
curl -i -H 'Range: bytes=0-1023' https://shineup.me/files/<sha256> -o /dev/null -D -
|
||||
# Ожидается: HTTP 206, Content-Range: bytes 0-1023/<size>, Content-Length: 1024
|
||||
# Без Range: 200; Range: bytes=999999999999- : 416 + Content-Range: bytes */<size>
|
||||
```
|
||||
|
||||
Ожидается:
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
|
||||
### Назначение
|
||||
|
||||
Поиск пользователей по префиксу логина. Операция зарегистрирована в серверном API и используется как вспомогательная dev/test операция.
|
||||
Поиск пользователей по префиксу логина и фрагменту публичного имени (`first_name`, `last_name`) без учёта регистра и с нормализацией `ё/е`. Совместимый ответ — массив строк `logins`.
|
||||
При необходимости можно включить фильтр только по server PDA.
|
||||
|
||||
### Запрос
|
||||
@@ -129,12 +129,14 @@
|
||||
"requestId": "search-001",
|
||||
"payload": {
|
||||
"prefix": "an",
|
||||
"isServer": true
|
||||
"isServer": true,
|
||||
"limit": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `prefix` — обязательный префикс логина.
|
||||
- `prefix` — обязательный поисковый фрагмент (до 120 символов); логины ищутся по началу, публичные имена — по подстроке.
|
||||
- `limit` — необязательное число результатов 1–50, по умолчанию **5** (совместимость с клиентами).
|
||||
- `isServer` — необязательный boolean-флаг; если `true`, сервер вернёт только логины,
|
||||
у которых в `solana_user_pda_current` стоит `is_server = true`.
|
||||
|
||||
@@ -147,7 +149,11 @@
|
||||
"status": 200,
|
||||
"ok": true,
|
||||
"payload": {
|
||||
"logins": ["anya", "andrey"]
|
||||
"logins": ["anya", "andrey"],
|
||||
"users": [
|
||||
{ "login": "anya", "displayName": "Анна", "avatarAr": "" },
|
||||
{ "login": "andrey", "displayName": "Андрей", "avatarAr": "" }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -587,3 +587,58 @@ Channel/message responses expose three counters:
|
||||
- `shiningLikesCount` — likes from users who are currently both `primary` and `shining`.
|
||||
|
||||
Changing `account_role` or `shine` does not alter the raw reaction. The two qualified counters are recalculated from `reactions_state`; therefore old likes automatically enter or leave qualified counters when the actor's current status changes.
|
||||
|
||||
|
||||
## `SearchChannels` — публичный поиск каналов (v32)
|
||||
|
||||
Операция **без авторизации**, на текущем сервере (не федеративный поиск).
|
||||
Результаты берутся из актуального состояния `channel_names_state`; публичные каналы — `channel_type_code = 1`, не удалённые (`is_deleted = false`).
|
||||
|
||||
Запрос:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "SearchChannels",
|
||||
"requestId": "search-ch-1",
|
||||
"payload": { "query": "гриб", "limit": 10 }
|
||||
}
|
||||
```
|
||||
|
||||
- `query` — текст от 1 до 120 символов. Не обязателен, если указан `ownerLogin`.
|
||||
- `ownerLogin` — дополнительное ограничение по началу логина владельца, до 80 символов.
|
||||
- `limit` — число результатов, по умолчанию 10, допустимо 1–50. Курсора и пагинации нет.
|
||||
- `@anna` — каналы владельцев, чьи логины содержат `anna`.
|
||||
- `anna/art` — каналы владельца `anna`, у которых публичное либо техническое название содержит `art`.
|
||||
- `anna/` — все доступные каналы владельца `anna`.
|
||||
- В обычном запросе ищутся **подстроки** в публичном имени `display_name`, техническом `slug` и логине `owner_login`. Регистр не важен, `ё` приравнивается к `е`. Вводимые `%`, `_` и `!` не работают как SQL-маски.
|
||||
- Сначала идут точные совпадения с названием или slug, затем префиксные, затем частичные, далее учитывается количество подписчиков.
|
||||
|
||||
Ответ:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "SearchChannels",
|
||||
"requestId": "search-ch-1",
|
||||
"status": 200,
|
||||
"ok": true,
|
||||
"payload": {
|
||||
"channels": [{
|
||||
"ownerLogin": "anna",
|
||||
"slug": "fungal-art",
|
||||
"displayName": "Грибной мир",
|
||||
"description": "Картины и грибы",
|
||||
"avatarAr": "",
|
||||
"avatarSha256": "",
|
||||
"ownerBlockchainName": "anna-001",
|
||||
"rootBlockNumber": 12,
|
||||
"rootBlockHashHex": "<hex>",
|
||||
"subscribersCount": 128
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Массив `channels` пустой при отсутствии совпадений; URL не возвращается.
|
||||
`ownerBlockchainName` и корневой блок позволяют клиенту открыть канонический канал через существующую маршрутизацию.
|
||||
Неверные поля: HTTP-подобный статус `400`, код `BAD_FIELDS`; ошибки чтения БД: `SERVER_DATA_ERROR`, `DB_ERROR`.
|
||||
Структура блокчейна не меняется. Индексы поиска добавлены миграцией БД v32 (`pg_trgm`).
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
| Операция | Раздел документации | Кратко |
|
||||
| --- | --- | --- |
|
||||
| `GetUser` | `01_User_Registration_API.md` | чтение/проверка пользователя + server-состояние его блокчейна |
|
||||
| `SearchUsers` | `01_User_Registration_API.md` | поиск логинов по префиксу |
|
||||
| `SearchUsers` | `01_User_Registration_API.md` | поиск логинов и публичных имён пользователей |
|
||||
| `SearchChannels` | `06_Channels_Read_API.md` | поиск публичных каналов по названию, slug и логину владельца |
|
||||
| `ResolveLoginForAuth` | `02_Authentication_API.md` | проверка login перед входом: LOCAL / REMOTE / NOT_FOUND / NO_ACCESS_SERVER + URL правильного access server |
|
||||
| `AuthChallenge` | `02_Authentication_API.md` | challenge для создания новой сессии |
|
||||
| `CreateAuthSession` | `02_Authentication_API.md` | создание новой авторизованной сессии |
|
||||
|
||||
@@ -65,19 +65,55 @@ SHA256(received bytes) == sha256 из URL
|
||||
|
||||
Если корректный объект уже существует и размер совпадает, PUT идемпотентно отвечает `alreadyExists=true`.
|
||||
|
||||
## 4. GET и HEAD
|
||||
## 4. GET и HEAD (включая HTTP Range)
|
||||
|
||||
Java servlet умеет `GET` и `HEAD` как fallback. В production рекомендуется не пропускать чтение через Java: Caddy должен отдавать файл непосредственно с диска.
|
||||
Java servlet обслуживает `GET /files/<sha256>` и `HEAD /files/<sha256>`.
|
||||
Проверка SHA-256 **при чтении не выполняется**: хеш проверяется при исходном PUT,
|
||||
файл immutable, а скачивание не должно требовать предварительного прочтения всех байтов.
|
||||
Проверка корректности при повторном PUT уже имеющегося объекта сохранена.
|
||||
|
||||
Ответ immutable:
|
||||
Полный GET, как и прежде, возвращает `200 OK` и `Content-Length` всего файла.
|
||||
HEAD всегда возвращает метаданные **полного объекта** без тела и без обхода
|
||||
всего файла по байтам (Range в HEAD игнорируется).
|
||||
|
||||
```text
|
||||
Cache-Control: public, max-age=31536000, immutable
|
||||
ETag: "<sha256>"
|
||||
Content-Type: application/octet-stream
|
||||
Для `GET` с одним диапазоном:
|
||||
|
||||
```http
|
||||
Range: bytes=0-262143
|
||||
```
|
||||
|
||||
Файловое хранилище не определяет тип контента. Официальный клиент решает, как интерпретировать байты, на основании имени `nm` из `S:att`. Если пользователь указал неверное расширение или положил неподходящие байты, клиент просто не сможет отобразить такой media-файл.
|
||||
Ответ:
|
||||
|
||||
```http
|
||||
HTTP/1.1 206 Partial Content
|
||||
Accept-Ranges: bytes
|
||||
Content-Range: bytes 0-262143/<общий размер>
|
||||
Content-Length: 262144
|
||||
ETag: "<sha256>"
|
||||
```
|
||||
|
||||
Поддерживаются формы `bytes=START-END`, `bytes=START-` и `bytes=-SUFFIX`.
|
||||
Для составных или неудовлетворяемых диапазонов сервер возвращает `416` +
|
||||
`Content-Range: bytes */<общий размер>`. `If-Range` поддерживает точный
|
||||
совпадающий ETag; при несовпадении возвращается полный `200`.
|
||||
|
||||
Остальные заголовки:
|
||||
|
||||
```http
|
||||
Cache-Control: public, max-age=31536000, immutable
|
||||
Cross-Origin-Resource-Policy: cross-origin
|
||||
Access-Control-Allow-Origin: *
|
||||
```
|
||||
|
||||
Тип для MP4, WebM, Ogg и AVI Java определяет по первым байтам файла.
|
||||
Неизвестные типы остаются `application/octet-stream`. Протокол `S:att`
|
||||
не меняется, имя файла/тип на сервере не сохраняются.
|
||||
|
||||
При прямой выдаче Caddy (`file_server`) Range обеспечивает Caddy, а не Java.
|
||||
Следует проверить `Content-Type` (у файлов с именем SHA-256 нет расширения),
|
||||
а также корректность ответа `206` через публичный домен, особенно с CDN.
|
||||
Если нужен корректный MIME по сигнатуре, используйте HTTP reverse_proxy к Java
|
||||
из инструкции `deploy/PUBLIC_FILES_CADDY_CLOUDFLARE.md`.
|
||||
|
||||
## 5. Связь с `S:att`
|
||||
|
||||
@@ -101,4 +137,6 @@ https://<current-access-server>/files/<sha256>
|
||||
|
||||
## 6. Preview
|
||||
|
||||
В UI видео со storage=server получает прямую ссылку `/files/<sha256>` (без полного `fetch` в Blob): браузер сам запрашивает диапазоны, читает длительность и загружает стартовый кадр. Размер берётся из `sz` вложения. Для Arweave частичная загрузка зависит от gateway.
|
||||
|
||||
Отдельных preview-файлов сейчас нет. `preAr`, `preSha256`, `previewAr`, `previewSha256` не являются частью текущего протокола.
|
||||
|
||||
@@ -228,6 +228,23 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
|
||||
|
||||
Это правило не меняет wire/API-формат DM и не меняет байтовый формат tombstone.
|
||||
|
||||
## UI чата: поиск, переход к дате, «Медиа и файлы», «без звука», закрепление (12.10.2026)
|
||||
|
||||
Всё ниже работает на клиенте и не меняет ни формат DM, ни серверный API.
|
||||
|
||||
- Поиск по переписке и календарь «перейти к дате» работают по расшифрованным сообщениям на устройстве. Если история загружена не целиком, клиент сам долистывает её обычным `GetDirectMessages` (страницы по 50) до начала. Экран «Медиа и файлы» (`/chat/<login>/media`) делает то же самое и показывает фото и видео (`<S:file...>` до 20 МБ) сеткой, а остальные файлы списком. Голосовые в этот экран не попадают.
|
||||
- При разборе страницы истории ключ `clientKey` достаётся из локального хранилища ключей один раз на страницу, а не для каждого сообщения. Сама расшифровка (X25519 + HKDF + AES-GCM) не меняется.
|
||||
- «Без звука» и «закреплён» – настройки этого устройства. Они хранятся в `localStorage` отдельно для каждого `ownerLogin`, на сервер не передаются и с другими устройствами не синхронизируются. Для чата «без звука» входящее сообщение доставляется и считается непрочитанным как обычно, но клиент не проигрывает сигнал и не показывает системное уведомление. Список таких чатов дублируется в Cache Storage, чтобы service worker не показывал push `new_message` от этого собеседника. Если в push нет `toLogin`, проверяются списки всех профилей устройства.
|
||||
- Закреплённые чаты показываются в списке выше остальных, независимо от фильтра по типу связи. Последний закреплённый показывается первым.
|
||||
|
||||
## UI: список чатов и «без звука» на время (13.10.2026)
|
||||
|
||||
Тоже только клиент: формат DM и серверный API не меняются.
|
||||
|
||||
- Список чатов: сначала переписки – по времени последнего сообщения, закреплённые выше всех. Связи без переписки идут ниже отдельной группой «Начать переписку»: во «Всех» – только близкие и друзья (первые пять и «Показать всех»), в фильтре по типу связи – все люди этого типа, в поиске по чатам – все совпадения. Так сотни контактов не вытесняют сами переписки.
|
||||
- «Без звука» выбирается на 1 час, 8 часов, сутки, неделю или навсегда. Срок хранится рядом со списком (`mutedUntil`: собеседник → время в мс); когда он выходит, звук включается сам – и в открытом приложении (значки в списке и шапке чата обновляются), и в service worker, который сверяет срок при каждом push.
|
||||
- Формат для service worker в Cache Storage: `{ ownerLogin: { peerLogin: untilMs } }`, где `0` – навсегда. Прежний формат `{ ownerLogin: [peerLogin] }` worker тоже понимает.
|
||||
|
||||
|
||||
## 15. Файлы в личных сообщениях
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Ссылки в тексте сообщений SHiNE (UI)
|
||||
|
||||
Состояние: 10.10.2026. Изменений формата блокчейна и серверного API нет.
|
||||
|
||||
## Поддерживаемые текстовые ссылки
|
||||
|
||||
- `SHiNE/aidar/news/34` — ссылка на публикацию №34. В ленте открывает `/SHiNE/aidar/news/s/34`; при просмотре отдельной публикации, комментариев или личного чата — `/SHiNE/aidar/news/34`.
|
||||
- `SHiNE/aidar/news/s/34` — явно открывает ленту и прокручивает к публикации №34 независимо от исходного экрана.
|
||||
- `SHiNE/aidar/news` — канал, `SHiNE/aidar` — профиль.
|
||||
- Допускается ведущий `/`; используется текущий origin браузера, без привязки к конкретному серверу доступа.
|
||||
- `http://`, `https://` и `www.` — внешние ссылки, открываются в новой вкладке с `rel="noopener noreferrer"`.
|
||||
- Все ссылки могут находиться в обычном тексте публикаций, их обсуждений и личных сообщений. Текст передаётся и сохраняется без преобразований; ссылки становятся кликабельными исключительно при отображении.
|
||||
|
||||
## Техническое поведение
|
||||
|
||||
Обработчик `shine-UI/js/services/shine-message-links.js` безопасно создаёт DOM-ссылки через `textContent`, не вставляет пользовательский текст как HTML. Для внутренних переходов используется существующий `navigate()`; стандартный `href` позволяет копировать ссылку и открывать её в новой вкладке. Просмотр из контекста ленты передаётся опцией `viewMode: 'feed'` (без глобального переключателя режима). Вход из чата или извне без контекста по умолчанию открывает отдельную публикацию.
|
||||
|
||||
Порядковые номера определяются уже существующим `channel-message-ordinals.js`. Этот патч **не пересчитывает и не меняет** правила нумерации. Стабильность номера при позднем импорте/форке требует отдельной проверки.
|
||||
|
||||
В этой UI-реализации **пока не введена строгая проверка времени создания целевой публикации по отношению к конкретной редакции сообщения**. Проверка при записи (в том числе для сторонних клиентов), форки и варианты встроенных сокращённых ссылок отложены; их нельзя считать обеспеченными клиентским преобразованием текста. Редактирование старой публикации и добавление ссылки на уже существующую новую публикацию не блокируется UI.
|
||||
|
||||
## Тестирование
|
||||
|
||||
Из корня проекта:
|
||||
|
||||
```bash
|
||||
node --test shine-UI/tests/shine-message-links.test.mjs
|
||||
```
|
||||
|
||||
Проверяются маршруты, режим ленты, принудительный `/s/N`, внешние URL, текстовая безопасность и взаимодействие с текущим роутером. Для выпуска дополнительно требуется ручная проверка навигации в браузере из трёх экранов: лента, отдельная запись, личный чат.
|
||||
@@ -14,6 +14,12 @@ class SpaHandler(SimpleHTTPRequestHandler):
|
||||
rel = Path(translated).relative_to(Path.cwd())
|
||||
return str(ROOT / rel)
|
||||
|
||||
def end_headers(self):
|
||||
# Локальная разработка: модули без версии в адресе (./router.js) иначе берутся из эвристического
|
||||
# кэша браузера – новый app.js встречается со старым router.js и приложение не стартует.
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
super().end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
file_path = Path(self.translate_path(self.path.split("?", 1)[0]))
|
||||
if file_path.exists() and file_path.is_file():
|
||||
|
||||
@@ -74,6 +74,31 @@ function encodeCallPushPayloadForUrl(payload) {
|
||||
}
|
||||
}
|
||||
|
||||
// Чаты «без звука» (пишет приложение, см. js/services/dm-chat-prefs.js):
|
||||
// { владелец: { собеседник: срок в мс, 0 – навсегда } }; прежний формат – { владелец: [собеседники] }.
|
||||
async function isMutedDirectMessage(toLogin, fromLogin) {
|
||||
try {
|
||||
const owner = String(toLogin || '').trim().toLowerCase();
|
||||
const peer = String(fromLogin || '').trim().toLowerCase();
|
||||
if (!peer) return false;
|
||||
const cache = await caches.open('shine-dm-prefs');
|
||||
const response = await cache.match('/__shine/dm-muted.json');
|
||||
if (!response) return false;
|
||||
const muted = await response.json();
|
||||
// Сервер сейчас не кладёт в push получателя: тогда смотрим списки всех аккаунтов этого устройства.
|
||||
const lists = owner ? [muted?.[owner]] : Object.values(muted || {});
|
||||
const now = Date.now();
|
||||
return lists.some((list) => {
|
||||
if (Array.isArray(list)) return list.includes(peer);
|
||||
if (!list || typeof list !== 'object' || !Object.prototype.hasOwnProperty.call(list, peer)) return false;
|
||||
const until = Number(list[peer] || 0);
|
||||
return !until || until > now;
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener('push', (event) => {
|
||||
let body = '';
|
||||
let rawText = '';
|
||||
@@ -130,7 +155,7 @@ self.addEventListener('push', (event) => {
|
||||
: 'SHiNE: входящее сообщение');
|
||||
|
||||
const notifyPromise = shouldNotify
|
||||
? self.registration.showNotification(notificationTitle, {
|
||||
? (kind === 'new_message' ? isMutedDirectMessage(toLogin, fromLogin) : Promise.resolve(false)).then((muted) => (muted ? undefined : self.registration.showNotification(notificationTitle, {
|
||||
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
|
||||
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
|
||||
renotify: true,
|
||||
@@ -152,7 +177,7 @@ self.addEventListener('push', (event) => {
|
||||
{ action: 'decline', title: 'Сбросить' },
|
||||
]
|
||||
: [],
|
||||
})
|
||||
})))
|
||||
: Promise.resolve();
|
||||
|
||||
const closeOnStopPromise = kind === 'stop_call' && callId
|
||||
|
||||
+46
-12
@@ -39,32 +39,59 @@
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
window.__SHINE_BUILD_HASH__ = '20261007235900';
|
||||
window.__SHINE_BUILD_HASH__ = '20261013113000';
|
||||
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
||||
</script>
|
||||
<script>
|
||||
(function attachStylesWithBuildHash() {
|
||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/network-graph.css'];
|
||||
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/network-graph.css'];
|
||||
// Стили, добавленные скриптом, браузер не ждёт перед первой отрисовкой: без этого
|
||||
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
|
||||
const root = document.documentElement;
|
||||
let pending = cssFiles.length;
|
||||
const reveal = () => root.classList.add('shine-styles-ready');
|
||||
const settle = () => { pending -= 1; if (pending <= 0) reveal(); };
|
||||
cssFiles.forEach((file) => {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = `${file}?v=${v}`;
|
||||
link.onload = settle;
|
||||
link.onerror = settle;
|
||||
document.head.appendChild(link);
|
||||
});
|
||||
setTimeout(reveal, 4000);
|
||||
}());
|
||||
</script>
|
||||
<style>
|
||||
html { background: var(--background, #121419); }
|
||||
html[data-theme='light'] { background: var(--background, #f3f2f7); }
|
||||
html:not(.shine-styles-ready) body { visibility: hidden; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="initial-splash" class="initial-splash" aria-label="Сияние">
|
||||
<div class="initial-splash__logo-wrap">
|
||||
<img
|
||||
class="initial-splash__logo"
|
||||
src="./img/shine-logo-transparent-final.png"
|
||||
alt="Логотип Сияние"
|
||||
/>
|
||||
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||
<div id="initial-splash" class="initial-splash">
|
||||
<div class="initial-splash__frame">
|
||||
<section class="auth-screen auth-screen--welcome">
|
||||
<div class="auth-logo-wrap">
|
||||
<img class="auth-logo" src="./img/shine-logo-transparent-final.png" alt="Логотип Сияние" />
|
||||
</div>
|
||||
<div class="stack auth-brand-block">
|
||||
<h1 class="auth-brand"><svg class="shine-wordmark" viewBox="52 -722 7294 744" role="img" aria-label="Сияние"><path fill="currentColor" d="M721 -129Q619 -33 479 -33Q401 -33 341 -60Q281 -87 241 -132Q201 -177 180.5 -236Q160 -295 160 -359Q160 -427 181.5 -483.5Q203 -540 242 -581Q281 -622 334.5 -645Q388 -668 451 -668Q494 -668 529.5 -658Q565 -648 592.5 -632Q620 -616 637.5 -595.5Q655 -575 662 -554H736Q721 -588 697.5 -617Q674 -646 639 -667Q604 -688 557 -700Q510 -712 450 -712Q363 -712 291.5 -687Q220 -662 169 -615.5Q118 -569 90 -503.5Q62 -438 62 -357Q62 -287 84.5 -220.5Q107 -154 154 -102.5Q201 -51 274 -19.5Q347 12 448 12Q512 12 562.5 0Q613 -12 650.5 -29.5Q688 -47 713 -67Q738 -87 751 -102ZM1542 -82V-700H1451V0H1542L1957 -625V0H2048V-700H1957ZM3316 -700V0H3225V-309H3181Q3153 -309 3134.5 -304Q3116 -299 3101 -287Q3086 -275 3073 -256Q3060 -237 3042 -209L2963 -92Q2948 -69 2933.5 -50Q2919 -31 2902 -17.5Q2885 -4 2863.5 4Q2842 12 2812 12Q2790 12 2776 10Q2762 8 2748 0V-37Q2753 -36 2758 -35.5Q2763 -35 2768 -35Q2789 -35 2805 -41Q2821 -47 2835 -58.5Q2849 -70 2862 -86.5Q2875 -103 2889 -124Q2931 -185 2954 -221.5Q2977 -258 2990.5 -278Q3004 -298 3012.5 -307Q3021 -316 3033 -322L3043 -327V-331Q2995 -334 2960.5 -352Q2926 -370 2904 -397Q2882 -424 2872 -455.5Q2862 -487 2862 -517Q2862 -544 2872.5 -576Q2883 -608 2908.5 -635.5Q2934 -663 2978 -681.5Q3022 -700 3089 -700ZM3225 -656H3124Q3086 -656 3055.5 -645Q3025 -634 3003 -614.5Q2981 -595 2969.5 -568Q2958 -541 2958 -509Q2958 -482 2968.5 -454.5Q2979 -427 3000 -404.5Q3021 -382 3051.5 -368Q3082 -354 3122 -354H3225ZM4197 -348H4616V0H4707V-700H4616V-394H4197V-700H4106V0H4197ZM5588 -82V-700H5497V0H5588L6003 -625V0H6094V-700H6003ZM6884 -700V0H7336V-55H6975V-346H7285V-394H6975V-645H7336V-700Z"/></svg></h1>
|
||||
<p class="meta-muted auth-site-name" id="initial-splash-host"></p>
|
||||
</div>
|
||||
<div class="auth-actions shine-actions initial-splash__actions" aria-hidden="true">
|
||||
<span class="shine-btn"></span>
|
||||
<span class="secondary-btn shine-btn--register"></span>
|
||||
<span class="text-btn start-language-link"></span>
|
||||
<span class="text-btn start-settings-link"></span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="initial-splash__brand">Сияние</div>
|
||||
<script>
|
||||
document.getElementById('initial-splash-host').textContent = window.location.host || 'shineup.me';
|
||||
</script>
|
||||
</div>
|
||||
<div class="app-shell">
|
||||
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
||||
@@ -445,11 +472,18 @@ window.__SHINE_BUILD_HASH__ = '20261007235900';
|
||||
}());
|
||||
</script>
|
||||
<script>
|
||||
(function attachAppWithBuildHash() {
|
||||
(async function attachAppWithBuildHash() {
|
||||
const isLocalPreview = ['localhost', '127.0.0.1', '::1'].includes(String(window.location.hostname || '').toLowerCase());
|
||||
if (isLocalPreview && 'serviceWorker' in navigator) {
|
||||
try {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||
} catch {}
|
||||
}
|
||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||
const script = document.createElement('script');
|
||||
script.type = 'module';
|
||||
script.src = `./js/app.js?v=${v}`;
|
||||
script.src = isLocalPreview ? `./js/app.js?v=${v}&local=${Date.now()}` : `./js/app.js?v=${v}`;
|
||||
document.body.appendChild(script);
|
||||
}());
|
||||
</script>
|
||||
|
||||
+115
-15
@@ -3,6 +3,7 @@ import {
|
||||
getRoute,
|
||||
PRE_AUTH_PAGES,
|
||||
syncTrackedRouteHistory,
|
||||
consumeHistoryLayerPop,
|
||||
} from './router.js';
|
||||
import { renderToolbar } from './components/toolbar.js';
|
||||
import {
|
||||
@@ -16,6 +17,7 @@ import { initPwaInstallPromptHandling } from './services/pwa-install-service.js'
|
||||
import { initPwaPush } from './services/pwa-push-service.js';
|
||||
import { initCallUiOverlay } from './services/call-ui-service.js';
|
||||
import { showToast } from './services/channels-ux.js';
|
||||
import { toUserMessage } from './services/ui-error-texts.js';
|
||||
import { KeyRotationClient } from './services/key-rotation-service.js';
|
||||
import {
|
||||
handleCallPushAction,
|
||||
@@ -50,6 +52,8 @@ import {
|
||||
markOutgoingDeliveryState,
|
||||
markOutgoingReadByBaseKey,
|
||||
normalizeDmChatId,
|
||||
applyUrlServerLoginOverrideIfNeeded,
|
||||
hasUrlEntrySettingsOverride,
|
||||
setContacts,
|
||||
} from './state.js';
|
||||
|
||||
@@ -67,14 +71,17 @@ import * as loginOtherDeviceView from './pages/login-other-device-view.js?v=2026
|
||||
import * as loginPasswordView from './pages/login-password-view.js?v=202606201650';
|
||||
import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
||||
|
||||
import * as profileView from './pages/profile-view.js?v=202609260900';
|
||||
import * as profileView from './pages/profile-view.js?v=202610130400';
|
||||
import * as profileEditView from './pages/profile-edit-view.js';
|
||||
import * as profilesView from './pages/profiles-view.js';
|
||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||
import * as settingsView from './pages/settings-view.js';
|
||||
import * as accessKeysView from './pages/access-keys-view.js';
|
||||
import * as myBlockchainView from './pages/my-blockchain-view.js';
|
||||
import * as myBlockchainHistoryView from './pages/my-blockchain-history-view.js';
|
||||
import * as keyRotationView from './pages/key-rotation-view.js';
|
||||
import * as accessServersView from './pages/access-servers-view.js';
|
||||
import * as settingsServersView from './pages/settings-servers-view.js';
|
||||
import * as developerSettingsView from './pages/developer-settings-view.js';
|
||||
import * as advancedSettingsView from './pages/advanced-settings-view.js';
|
||||
import * as serverSettingsView from './pages/server-settings-view.js?v=202609260900';
|
||||
@@ -90,25 +97,32 @@ import * as deviceCameraView from './pages/device-camera-view.js';
|
||||
import * as showKeysView from './pages/show-keys-view.js';
|
||||
import * as clientSessionView from './pages/device-session-view.js?v=202606131435';
|
||||
import * as languageView from './pages/language-view.js';
|
||||
import * as appearanceView from './pages/appearance-view.js';
|
||||
import * as notificationSettingsView from './pages/notification-settings-view.js';
|
||||
import * as appLogView from './pages/app-log-view.js';
|
||||
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
||||
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||
import * as solanaRpcCheckView from './pages/solana-rpc-check-view.js';
|
||||
import * as messagesList from './pages/messages-list.js?v=202609260900';
|
||||
import * as messagesList from './pages/messages-list.js?v=202610130400';
|
||||
import * as contactSearchView from './pages/contact-search-view.js';
|
||||
import * as chatView from './pages/chat-view.js?v=202609260900';
|
||||
import * as chatView from './pages/chat-view.js?v=202610130200';
|
||||
import * as chatMediaView from './pages/chat-media-view.js';
|
||||
import { isDmChatMuted } from './services/dm-chat-prefs.js';
|
||||
import { getDevicePref } from './services/device-prefs.js';
|
||||
import { isDeveloperToolsEnabled } from './services/feature-settings.js';
|
||||
import * as userProfileView from './pages/user-profile-view.js';
|
||||
import * as userProfileListView from './pages/user-profile-list-view.js';
|
||||
import * as userRelationManageView from './pages/user-relation-manage-view.js';
|
||||
import * as channelsList from './pages/channels-list.js?v=202609260900';
|
||||
import * as channelsList from './pages/channels-list.js?v=20261011-search';
|
||||
import * as searchView from './pages/search-view.js';
|
||||
import * as channelView from './pages/channel-view.js';
|
||||
import * as channelAboutView from './pages/channel-about-view.js';
|
||||
import * as channelDonateView from './pages/channel-donate-view.js';
|
||||
import * as channelThreadView from './pages/channel-thread-view.js';
|
||||
import * as addChannelView from './pages/add-channel-view.js';
|
||||
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-view.js';
|
||||
import * as networkView from './pages/network-view.js?v=202609260900';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202609260900';
|
||||
import * as networkView from './pages/network-view.js?v=202610130200';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||
@@ -141,9 +155,12 @@ const routes = {
|
||||
'profiles-view': profilesView,
|
||||
'wallet-view': walletView,
|
||||
'settings-view': settingsView,
|
||||
'access-keys-view': accessKeysView,
|
||||
'my-blockchain-view': myBlockchainView,
|
||||
'my-blockchain-history-view': myBlockchainHistoryView,
|
||||
'key-rotation-view': keyRotationView,
|
||||
'access-servers-view': accessServersView,
|
||||
'settings-servers-view': settingsServersView,
|
||||
'developer-settings-view': developerSettingsView,
|
||||
'advanced-settings-view': advancedSettingsView,
|
||||
'server-settings-view': serverSettingsView,
|
||||
@@ -158,6 +175,8 @@ const routes = {
|
||||
'show-keys-view': showKeysView,
|
||||
'device-session-view': clientSessionView,
|
||||
'language-view': languageView,
|
||||
'appearance-view': appearanceView,
|
||||
'notification-settings-view': notificationSettingsView,
|
||||
'app-log-view': appLogView,
|
||||
'pwa-diagnostics-view': pwaDiagnosticsView,
|
||||
'solana-users-init-view': solanaUsersInitView,
|
||||
@@ -165,10 +184,12 @@ const routes = {
|
||||
'messages-list': messagesList,
|
||||
'contact-search-view': contactSearchView,
|
||||
'chat-view': chatView,
|
||||
'chat-media-view': chatMediaView,
|
||||
user: userProfileView,
|
||||
'user-profile-list-view': userProfileListView,
|
||||
'user-relation-manage-view': userRelationManageView,
|
||||
'channels-list': channelsList,
|
||||
'search-view': searchView,
|
||||
'channel-view': channelView,
|
||||
'channel-about-view': channelAboutView,
|
||||
'channel-donate-view': channelDonateView,
|
||||
@@ -196,6 +217,35 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
||||
let currentCleanup = null;
|
||||
let pingIntervalId = null;
|
||||
let reconnectIntervalId = null;
|
||||
let channelsPrefetchTimerId = null;
|
||||
let channelsPrefetchEpoch = 0;
|
||||
const CHANNELS_PREFETCH_INTERVAL_MS = 60_000;
|
||||
|
||||
// Раз в минуту, пока вкладка на экране, подтягиваем каналы в память, чтобы они открывались сразу.
|
||||
function startChannelsPrefetch() {
|
||||
stopChannelsPrefetch();
|
||||
const epoch = ++channelsPrefetchEpoch;
|
||||
let running = false;
|
||||
const tick = async () => {
|
||||
if (running || document.visibilityState !== 'visible' || !wsIsOpen()) return;
|
||||
running = true;
|
||||
try {
|
||||
await channelsList.refreshChannelsInBackground({ isCurrent: () => epoch === channelsPrefetchEpoch });
|
||||
} catch {
|
||||
// Сеть недоступна – попробуем на следующем круге.
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
channelsPrefetchTimerId = window.setInterval(() => void tick(), CHANNELS_PREFETCH_INTERVAL_MS);
|
||||
window.setTimeout(() => { if (epoch === channelsPrefetchEpoch) void tick(); }, 3_000);
|
||||
}
|
||||
|
||||
function stopChannelsPrefetch() {
|
||||
channelsPrefetchEpoch += 1;
|
||||
if (channelsPrefetchTimerId) window.clearInterval(channelsPrefetchTimerId);
|
||||
channelsPrefetchTimerId = null;
|
||||
}
|
||||
let sessionRuntimeStarted = false;
|
||||
let connectionState = '';
|
||||
let connectionStatusText = '';
|
||||
@@ -220,6 +270,11 @@ const SCROLL_TO_BOTTOM_PAGE_IDS = new Set([
|
||||
'channel-thread-view',
|
||||
]);
|
||||
|
||||
function isLocalPreviewHost() {
|
||||
const host = String(window.location.hostname || '').toLowerCase();
|
||||
return host === 'localhost' || host === '127.0.0.1' || host === '::1';
|
||||
}
|
||||
|
||||
const FILLED_ACTION_BUTTON_PAGE_IDS = new Set([
|
||||
...PRE_AUTH_PAGES.filter((pageId) => pageId !== 'entry-settings-view'),
|
||||
'settings-view',
|
||||
@@ -228,6 +283,7 @@ const FILLED_ACTION_BUTTON_PAGE_IDS = new Set([
|
||||
|
||||
const SETTINGS_BORDERED_ACTION_PAGE_IDS = new Set([
|
||||
'access-servers-view',
|
||||
'settings-servers-view',
|
||||
'server-settings-view',
|
||||
'arweave-uploads-view',
|
||||
'developer-settings-view',
|
||||
@@ -253,6 +309,7 @@ const GUEST_ALLOWED_PAGES = new Set([
|
||||
'language-view',
|
||||
'network-view',
|
||||
'channels-list',
|
||||
'search-view',
|
||||
'channel-view',
|
||||
'channel-about-view',
|
||||
'channel-thread-view',
|
||||
@@ -263,6 +320,8 @@ const GUEST_ALLOWED_PAGES = new Set([
|
||||
|
||||
setClientErrorTransport((payload) => authService.reportClientUiError(payload));
|
||||
setClientErrorSentNotifier((payload) => {
|
||||
// Технические подробности – только с включёнными инструментами разработчика.
|
||||
if (!isDeveloperToolsEnabled()) return;
|
||||
const login = String(state.session.login || 'guest').trim();
|
||||
const isoTs = new Date(Number(payload?.clientTs || Date.now())).toISOString();
|
||||
showToast(`Ошибка отправлена на сервер · ${login} · ${isoTs}`);
|
||||
@@ -601,6 +660,8 @@ async function unlockHiddenDmAudio() {
|
||||
|
||||
async function playDmSignal({ extended = false } = {}) {
|
||||
try {
|
||||
// «Звук в открытом приложении» выключен в настройках уведомлений.
|
||||
if (getDevicePref('dmSound', true) === false) return false;
|
||||
if (!hiddenDmAudioUnlocked || !hiddenDmAudioContext) return false;
|
||||
if (hiddenDmAudioContext.state === 'suspended') {
|
||||
await hiddenDmAudioContext.resume();
|
||||
@@ -886,7 +947,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
const currentLogin = String(state.session.login || '').trim();
|
||||
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
||||
if (!savedProfileExists(targetLogin)) {
|
||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`);
|
||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`, { kind: 'info' });
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -906,7 +967,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
showToast(`Не удалось переключить профиль: ${error?.message || 'unknown'}`);
|
||||
showToast(toUserMessage(error, 'Не удалось переключить профиль.'), { kind: 'error' });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1236,7 +1297,17 @@ async function ensureSessionAfterWsReconnect() {
|
||||
return wsSessionRestoreInFlight;
|
||||
}
|
||||
|
||||
// Без инструментов разработчика – спокойное сообщение вместо окна со стеком вызовов,
|
||||
// не чаще раза в полминуты (ошибка уже записана в журнал и отправлена на сервер).
|
||||
let lastCrashNoticeAt = 0;
|
||||
function showGlobalErrorAlert(title, details = {}) {
|
||||
if (!isDeveloperToolsEnabled()) {
|
||||
const now = Date.now();
|
||||
if (now - lastCrashNoticeAt < 30000) return;
|
||||
lastCrashNoticeAt = now;
|
||||
showToast('Что-то пошло не так. Сведения об ошибке уже отправлены разработчикам – попробуйте ещё раз.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
const lines = [title];
|
||||
if (details.message) lines.push(`Сообщение: ${details.message}`);
|
||||
if (details.pageId) lines.push(`Экран: ${details.pageId}`);
|
||||
@@ -1395,6 +1466,14 @@ async function redirectToActiveKeyRotationIfNeeded() {
|
||||
function renderApp() {
|
||||
syncTrackedRouteHistory(window.location.pathname || '/');
|
||||
const route = getRoute();
|
||||
if (state.session.isAuthorized) {
|
||||
const returnPath = window.sessionStorage.getItem('shine-public-return-path');
|
||||
if (returnPath && returnPath.startsWith('/SHiNE/')) {
|
||||
window.sessionStorage.removeItem('shine-public-return-path');
|
||||
navigate(returnPath);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const pageId = route.pageId || (state.session.isAuthorized ? 'messages-list' : 'start-view');
|
||||
|
||||
if (!state.session.isAuthorized && !PRE_AUTH_PAGES.includes(pageId) && !GUEST_ALLOWED_PAGES.has(pageId)) {
|
||||
@@ -1433,7 +1512,7 @@ function renderApp() {
|
||||
try {
|
||||
const chrome = createChromeController(showAppChrome, page.pageMeta?.shellMode);
|
||||
currentChromeCleanup = () => chrome.dispose();
|
||||
// В переписке нижняя панель прячется (pageMeta.hideToolbar), чтобы не отнимать место у сообщений.
|
||||
// Нижняя панель видна везде, кроме экранов с pageMeta.hideToolbar (например, смена ключей).
|
||||
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
||||
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
||||
toolbarHeightObserver?.sync?.();
|
||||
@@ -1513,12 +1592,15 @@ async function ensureSessionRuntimeStarted() {
|
||||
if (!state.session.isAuthorized || sessionRuntimeStarted) return;
|
||||
sessionRuntimeStarted = true;
|
||||
|
||||
await initPwaPush({
|
||||
authService,
|
||||
onLog: (entry) => addAppLogEntry(entry),
|
||||
});
|
||||
if (!isLocalPreviewHost()) {
|
||||
await initPwaPush({
|
||||
authService,
|
||||
onLog: (entry) => addAppLogEntry(entry),
|
||||
});
|
||||
}
|
||||
|
||||
startConnectionMonitor();
|
||||
startChannelsPrefetch();
|
||||
|
||||
if (reconnectIntervalId) {
|
||||
window.clearInterval(reconnectIntervalId);
|
||||
@@ -1570,6 +1652,7 @@ async function init() {
|
||||
|
||||
setSessionResetHandler(() => {
|
||||
sessionRuntimeStarted = false;
|
||||
stopChannelsPrefetch();
|
||||
startConnectionMonitor();
|
||||
clearKeepAliveEntries();
|
||||
if (reconnectIntervalId) {
|
||||
@@ -1759,7 +1842,8 @@ async function init() {
|
||||
if (added && isIncomingForCurrent) {
|
||||
shouldRefreshToolbarUnread = true;
|
||||
}
|
||||
if (added && isIncomingForCurrent && !payload.backlog) {
|
||||
// Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления.
|
||||
if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) {
|
||||
const parsedText = parseDmTechBlocks(text);
|
||||
const displayText = String(parsedText.displayText || '');
|
||||
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
|
||||
@@ -1941,6 +2025,19 @@ async function init() {
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
let urlEntrySettingsReady = true;
|
||||
try {
|
||||
await applyUrlServerLoginOverrideIfNeeded();
|
||||
} catch (error) {
|
||||
urlEntrySettingsReady = false;
|
||||
addAppLogEntry({
|
||||
level: 'warn',
|
||||
source: 'entry-settings',
|
||||
message: 'Не удалось применить сервер из URL',
|
||||
details: { error: error?.message || 'unknown' },
|
||||
});
|
||||
}
|
||||
if (hasUrlEntrySettingsOverride() && !urlEntrySettingsReady) return;
|
||||
await tryAutoLogin();
|
||||
if (initialNotificationOpenPayload) {
|
||||
await handleNotificationClick(initialNotificationOpenPayload);
|
||||
@@ -1956,7 +2053,10 @@ async function init() {
|
||||
}
|
||||
})();
|
||||
|
||||
window.addEventListener('popstate', renderApp);
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (event.isTrusted && consumeHistoryLayerPop()) return;
|
||||
renderApp();
|
||||
});
|
||||
document.addEventListener('pointerdown', () => {
|
||||
void unlockHiddenDmAudio();
|
||||
}, { passive: true });
|
||||
|
||||
@@ -591,7 +591,7 @@ export function openArweaveAttachmentManager({
|
||||
</div>
|
||||
${turboMode
|
||||
? `
|
||||
<p class="ar-attachment-note"><strong>Turbo</strong> — более удобный способ загрузки файлов в Arweave через сторонний сервис. Обычно дешевле прямой загрузки. Файлы до 100 КБ загружаются бесплатно.</p>
|
||||
<p class="ar-attachment-note"><strong>Turbo</strong> – более удобный способ загрузки файлов в Arweave через сторонний сервис. Обычно дешевле прямой загрузки. Файлы до 100 КБ загружаются бесплатно.</p>
|
||||
`
|
||||
: `
|
||||
<div class="form-field">
|
||||
|
||||
@@ -76,7 +76,7 @@ export function openChannelAttachmentManager({
|
||||
</div>
|
||||
|
||||
<div class="public-attachment-manager__arweave" data-panel="arweave" hidden>
|
||||
<p class="meta-muted">Выберите Turbo — более удобный способ загрузки в Arweave через сторонний сервис — или прямую загрузку в сеть Arweave.</p>
|
||||
<p class="meta-muted">Выберите Turbo – более удобный способ загрузки в Arweave через сторонний сервис – или прямую загрузку в сеть Arweave.</p>
|
||||
<div class="public-attachment-manager__arweave-loading meta-muted">Открываем настройки Arweave…</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,8 @@ import { state } from '../state.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
|
||||
import { resolvePublicFileUrl } from '../services/public-file-service.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
const drafts = new Map();
|
||||
|
||||
@@ -14,6 +16,24 @@ function draftKey(key) {
|
||||
return `${login}:${String(key || 'editor')}`;
|
||||
}
|
||||
|
||||
// Превью вложения в редакторе: картинки и видео – миниатюрой (как в Threads), остальное – строкой с именем.
|
||||
const previewUrls = new Map();
|
||||
function attachmentKind(item) {
|
||||
const name = String(item?.name || '').toLowerCase();
|
||||
if (/\.(jpe?g|png|gif|webp|avif|heic|bmp)$/.test(name)) return 'image';
|
||||
if (/\.(mp4|webm|mov|m4v|ogv)$/.test(name)) return 'video';
|
||||
return 'file';
|
||||
}
|
||||
function attachmentPreviewUrl(item, login) {
|
||||
const key = item?.ar ? `ar:${item.ar}` : `sha:${item?.sha256 || ''}`;
|
||||
if (!previewUrls.has(key)) {
|
||||
previewUrls.set(key, item?.ar
|
||||
? Promise.resolve(`${String(state.entrySettings.arweaveServer || 'https://arweave.net').replace(/\/$/, '')}/${item.ar}`)
|
||||
: resolvePublicFileUrl({ sha256: item?.sha256, authorLogin: login, solanaEndpoint: state.entrySettings.solanaServer, fallbackServerLogin: state.entrySettings.shineServerLogin }).catch(() => ''));
|
||||
}
|
||||
return previewUrls.get(key);
|
||||
}
|
||||
|
||||
function attachmentLabel(item) {
|
||||
const name = String(item?.name || 'Файл');
|
||||
const size = Number(item?.size || 0);
|
||||
@@ -36,6 +56,7 @@ export function openChannelEditor({
|
||||
allowEmptyText = false,
|
||||
allowAttachments = true,
|
||||
rawText = false,
|
||||
openAttachOnStart = false,
|
||||
onSubmit,
|
||||
isActive = () => true,
|
||||
} = {}) {
|
||||
@@ -87,12 +108,45 @@ export function openChannelEditor({
|
||||
const draftMark = document.createElement('span');
|
||||
draftMark.className = 'channel-editor__draft';
|
||||
draftMark.textContent = 'Черновик';
|
||||
header.append(closeButton, heading, draftMark);
|
||||
const headerEnd = document.createElement('div');
|
||||
headerEnd.className = 'channel-editor__header-end';
|
||||
header.append(closeButton, heading, headerEnd);
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'channel-editor__body';
|
||||
|
||||
if (context && (context.author || context.text || context.attachmentLabel)) {
|
||||
// Цепочка как в Threads: исходная запись и ответы до той, на которую отвечаем, сверху вниз, соединены линией.
|
||||
// Поле ввода – последним звеном; к началу цепочки – прокруткой вверх.
|
||||
const chain = Array.isArray(context?.chain) ? context.chain.filter(Boolean) : [];
|
||||
if (chain.length) {
|
||||
const chainBox = document.createElement('ol');
|
||||
chainBox.className = 'channel-editor__chain';
|
||||
chainBox.setAttribute('aria-label', 'На что вы отвечаете');
|
||||
chain.forEach((item) => {
|
||||
const row = document.createElement('li');
|
||||
row.className = 'channel-editor__chain-item';
|
||||
const avatar = item.avatar instanceof Node ? item.avatar : renderUserAvatar({ login: item.author || 'unknown', className: 'avatar-plain', size: 'sm' });
|
||||
avatar.classList.add('channel-editor__chain-avatar');
|
||||
const main = document.createElement('div');
|
||||
main.className = 'channel-editor__chain-main';
|
||||
const head = document.createElement('div');
|
||||
head.className = 'channel-editor__chain-head';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = String(item.title || item.author || '');
|
||||
head.append(name);
|
||||
if (item.time) {
|
||||
const time = document.createElement('span');
|
||||
time.textContent = item.time;
|
||||
head.append(time);
|
||||
}
|
||||
const text = document.createElement('p');
|
||||
text.textContent = String(item.text || item.attachmentLabel || 'Запись без текста');
|
||||
main.append(head, text);
|
||||
row.append(avatar, main);
|
||||
chainBox.append(row);
|
||||
});
|
||||
body.append(chainBox);
|
||||
} else if (context && (context.author || context.text || context.attachmentLabel)) {
|
||||
const contextBox = document.createElement('div');
|
||||
contextBox.className = 'channel-editor__context';
|
||||
const contextTitle = document.createElement('strong');
|
||||
@@ -115,6 +169,7 @@ export function openChannelEditor({
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'channel-editor__input';
|
||||
textarea.rows = 1;
|
||||
textarea.maxLength = 2000;
|
||||
textarea.placeholder = placeholder;
|
||||
textarea.setAttribute('aria-label', placeholder);
|
||||
@@ -131,7 +186,7 @@ export function openChannelEditor({
|
||||
const clearButton = document.createElement('button');
|
||||
clearButton.type = 'button';
|
||||
clearButton.className = 'text-btn channel-editor__clear';
|
||||
clearButton.textContent = 'Очистить черновик';
|
||||
clearButton.textContent = 'Очистить';
|
||||
|
||||
const author = document.createElement('div');
|
||||
author.className = 'channel-editor__author';
|
||||
@@ -147,17 +202,24 @@ export function openChannelEditor({
|
||||
authorText.append(where);
|
||||
}
|
||||
author.append(authorText);
|
||||
if (chain.length) author.classList.add('is-chained');
|
||||
body.append(author);
|
||||
body.append(textarea, attachmentsBox, error, clearButton);
|
||||
|
||||
const footer = document.createElement('footer');
|
||||
footer.className = 'channel-editor__footer';
|
||||
const attachButton = document.createElement('button');
|
||||
attachButton.type = 'button';
|
||||
attachButton.className = 'secondary-btn channel-editor__attach';
|
||||
attachButton.innerHTML = `${iconHtml('clip')}<span class="sr-only">Прикрепить</span>`;
|
||||
attachButton.title = 'Прикрепить файл';
|
||||
attachButton.className = 'icon-btn channel-editor__attach';
|
||||
attachButton.innerHTML = `${iconHtml('image')}<span class="sr-only">Прикрепить фото, видео или файл</span>`;
|
||||
attachButton.title = 'Фото, видео или файл';
|
||||
attachButton.hidden = !allowAttachments;
|
||||
// Как в Threads: текст пишется прямо под именем, без рамки; под ним – вложения.
|
||||
// «Прикрепить» – в нижней панели у кнопки отправки, «Очистить» – в шапке, пока есть что очищать.
|
||||
const compose = document.createElement('div');
|
||||
compose.className = 'channel-editor__compose';
|
||||
compose.append(textarea, attachmentsBox, error);
|
||||
authorText.append(compose);
|
||||
headerEnd.append(clearButton, draftMark);
|
||||
const counter = document.createElement('span');
|
||||
counter.className = 'channel-editor__counter';
|
||||
const submitButton = document.createElement('button');
|
||||
@@ -184,15 +246,42 @@ export function openChannelEditor({
|
||||
|
||||
const sync = () => {
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = `${Math.max(160, textarea.scrollHeight)}px`;
|
||||
textarea.style.height = `${Math.max(24, textarea.scrollHeight)}px`;
|
||||
const length = textarea.value.length;
|
||||
counter.textContent = `${length} / 2000`;
|
||||
counter.classList.toggle('is-near-limit', length >= 1800);
|
||||
// Счётчик нужен только у предела, пустой «0 / 2000» лишь шумит.
|
||||
counter.classList.toggle('is-hidden', length < 1500);
|
||||
submitButton.disabled = inFlight || picking || length > textarea.maxLength || (!allowEmptyText && !textarea.value.trim() && attachments.length === 0);
|
||||
dialog.setAttribute('aria-busy', String(inFlight || picking));
|
||||
clearButton.hidden = !textarea.value && attachments.length === 0;
|
||||
draftMark.hidden = !clearButton.hidden;
|
||||
attachmentsBox.replaceChildren();
|
||||
attachments.forEach((item, index) => {
|
||||
const kind = attachmentKind(item);
|
||||
if (kind !== 'file') {
|
||||
const thumb = document.createElement('div');
|
||||
thumb.className = `channel-editor__thumb channel-editor__thumb--${kind}`;
|
||||
thumb.title = attachmentLabel(item);
|
||||
const media = document.createElement(kind === 'image' ? 'img' : 'video');
|
||||
if (kind === 'image') media.alt = String(item?.name || 'Изображение');
|
||||
else { media.muted = true; media.preload = 'metadata'; media.playsInline = true; }
|
||||
void attachmentPreviewUrl(item, login).then((url) => { if (url && media.isConnected !== false) media.src = url; });
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'channel-editor__thumb-remove';
|
||||
remove.setAttribute('aria-label', `Убрать вложение ${item?.name || ''}`);
|
||||
remove.innerHTML = iconHtml('close');
|
||||
remove.disabled = inFlight;
|
||||
remove.addEventListener('click', () => {
|
||||
attachments.splice(index, 1);
|
||||
saveDraft();
|
||||
sync();
|
||||
});
|
||||
thumb.append(media, remove);
|
||||
attachmentsBox.append(thumb);
|
||||
return;
|
||||
}
|
||||
const card = document.createElement('div');
|
||||
card.className = 'channel-editor__attachment';
|
||||
const label = document.createElement('span');
|
||||
@@ -213,19 +302,13 @@ export function openChannelEditor({
|
||||
});
|
||||
};
|
||||
|
||||
const openedUrl = location.href;
|
||||
const historyId = `${Date.now()}:${Math.random()}`;
|
||||
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
|
||||
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
|
||||
const viewport = window.visualViewport;
|
||||
const updateViewport = () => {
|
||||
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
||||
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}px`);
|
||||
};
|
||||
const onBack = (event) => {
|
||||
if (closed) return;
|
||||
event.stopImmediatePropagation();
|
||||
close({ fromHistory: true });
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||
});
|
||||
@@ -239,14 +322,8 @@ export function openChannelEditor({
|
||||
viewport?.removeEventListener('resize', updateViewport);
|
||||
viewport?.removeEventListener('scroll', updateViewport);
|
||||
window.removeEventListener('resize', updateViewport);
|
||||
window.removeEventListener('popstate', onBack, true);
|
||||
overlay.remove();
|
||||
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (location.href === openedUrl) event.stopImmediatePropagation();
|
||||
}, { capture: true, once: true });
|
||||
history.back();
|
||||
}
|
||||
if (!fromHistory) historyLayer.close();
|
||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||
};
|
||||
overlay.cleanup = () => close({ restoreFocus: false });
|
||||
@@ -362,7 +439,6 @@ export function openChannelEditor({
|
||||
});
|
||||
submitButton.addEventListener('click', () => void submit());
|
||||
document.addEventListener('keydown', onDocumentKeydown);
|
||||
window.addEventListener('popstate', onBack, true);
|
||||
viewport?.addEventListener('resize', updateViewport);
|
||||
viewport?.addEventListener('scroll', updateViewport);
|
||||
window.addEventListener('resize', updateViewport);
|
||||
@@ -375,7 +451,9 @@ export function openChannelEditor({
|
||||
const expand = overlay.querySelector('.channel-editor__context-toggle');
|
||||
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
|
||||
sync();
|
||||
textarea.focus();
|
||||
if (chain.length) body.scrollTop = author.offsetTop - body.offsetTop - 120;
|
||||
textarea.focus({ preventScroll: chain.length > 0 });
|
||||
if (openAttachOnStart && allowAttachments) attachButton.click();
|
||||
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
|
||||
});
|
||||
return { close };
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать».
|
||||
// Общие для ленты чата и экрана «Медиа и файлы».
|
||||
import { decryptDmFileToBlob, downloadAndDecryptDmFile } from '../services/dm-file-service.js';
|
||||
import { formatBytes, getAttachmentKind } from '../services/attachment-format.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { createSpinner } from './feedback.js';
|
||||
|
||||
// Картинки и видео в личке показываются так же, как в каналах (карусель + просмотрщик),
|
||||
// только файл сначала расшифровывается. Большие файлы остаются карточками со «Скачать»,
|
||||
// чтобы не тратить трафик на автозагрузку.
|
||||
const DM_INLINE_MEDIA_MAX_BYTES = 20 * 1024 * 1024;
|
||||
const DM_MEDIA_MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml', mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg' };
|
||||
const dmMediaBlobs = new Map();
|
||||
const DM_MEDIA_CACHE_LIMIT = 40;
|
||||
|
||||
export function isDmInlineMedia(attachment) {
|
||||
if (attachment?.kind === 'voice') return false;
|
||||
const size = Number(attachment?.size || 0);
|
||||
if (!(size > 0 && size <= DM_INLINE_MEDIA_MAX_BYTES)) return false;
|
||||
const kind = getAttachmentKind(attachment);
|
||||
return kind === 'image' || kind === 'video';
|
||||
}
|
||||
|
||||
// Расшифрованный файл держим в памяти: лента перерисовывается на каждое новое сообщение,
|
||||
// и без кэша картинка расшифровывалась бы и мигала заново.
|
||||
export function resolveDmMediaUrl(attachment) {
|
||||
const key = String(attachment?.id || attachment?.url || '');
|
||||
let pending = dmMediaBlobs.get(key);
|
||||
if (!pending) {
|
||||
const ext = String(attachment?.name || '').split('.').pop().toLowerCase();
|
||||
pending = decryptDmFileToBlob(attachment)
|
||||
.then((blob) => new Blob([blob], { type: DM_MEDIA_MIME[ext] || blob.type || 'application/octet-stream' }));
|
||||
pending.catch(() => dmMediaBlobs.delete(key));
|
||||
dmMediaBlobs.set(key, pending);
|
||||
if (dmMediaBlobs.size > DM_MEDIA_CACHE_LIMIT) dmMediaBlobs.delete(dmMediaBlobs.keys().next().value);
|
||||
}
|
||||
return pending.then((blob) => ({ url: URL.createObjectURL(blob), objectUrl: true }));
|
||||
}
|
||||
|
||||
export function createDmFileAttachmentCard(attachment) {
|
||||
const fileCard = document.createElement('div');
|
||||
fileCard.className = 'dm-file-card';
|
||||
|
||||
const fileIcon = document.createElement('span');
|
||||
fileIcon.className = 'dm-file-card__icon';
|
||||
fileIcon.setAttribute('aria-hidden', 'true');
|
||||
fileIcon.innerHTML = iconHtml('doc');
|
||||
|
||||
const fileCopy = document.createElement('span');
|
||||
fileCopy.className = 'dm-file-card__copy';
|
||||
const fileName = document.createElement('strong');
|
||||
fileName.className = 'dm-file-card__name';
|
||||
fileName.textContent = attachment.name || 'file';
|
||||
const fileMeta = document.createElement('span');
|
||||
fileMeta.className = 'dm-file-card__meta';
|
||||
const metaParts = [formatBytes(attachment.size)];
|
||||
if (Number(attachment?.version || 1) >= 2) metaParts.push('BitTorrent v2');
|
||||
fileMeta.textContent = metaParts.join(' · ');
|
||||
fileCopy.append(fileName, fileMeta);
|
||||
|
||||
// Круглая кнопка со стрелкой; пока файл качается и расшифровывается – проценты в ней же.
|
||||
const downloadBtn = document.createElement('button');
|
||||
downloadBtn.type = 'button';
|
||||
downloadBtn.className = 'dm-file-card__download';
|
||||
downloadBtn.title = 'Скачать';
|
||||
downloadBtn.setAttribute('aria-label', `Скачать ${attachment.name || 'файл'}`);
|
||||
const showDownloadIcon = () => {
|
||||
downloadBtn.classList.remove('is-busy');
|
||||
downloadBtn.innerHTML = iconHtml('download');
|
||||
};
|
||||
showDownloadIcon();
|
||||
downloadBtn.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
if (downloadBtn.disabled) return;
|
||||
downloadBtn.disabled = true;
|
||||
downloadBtn.classList.add('is-busy');
|
||||
downloadBtn.replaceChildren(createSpinner({ size: 'sm', label: 'Скачивание' }));
|
||||
try {
|
||||
const result = await downloadAndDecryptDmFile(attachment, {
|
||||
onProgress: ({ processedBytes, totalBytes }) => {
|
||||
if (!totalBytes) return;
|
||||
const percent = Math.min(100, Math.max(0, Math.round((processedBytes / totalBytes) * 100)));
|
||||
downloadBtn.textContent = `${percent}%`;
|
||||
},
|
||||
});
|
||||
if (!result?.cancelled) {
|
||||
// Сохранён сразу на диск (по частям) или отдан браузеру – для человека это одно и то же.
|
||||
showToast(result?.streamed ? 'Файл сохранён' : 'Файл скачан', { timeoutMs: 1600 });
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error?.message || 'Не удалось скачать файл', { kind: 'error', timeoutMs: 2800 });
|
||||
} finally {
|
||||
downloadBtn.disabled = false;
|
||||
showDownloadIcon();
|
||||
}
|
||||
});
|
||||
|
||||
fileCard.append(fileIcon, fileCopy, downloadBtn);
|
||||
return fileCard;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Пункт меню чата «Без звука» со сроком – общий для шапки чата и меню строки в списке чатов.
|
||||
// Срок выбирается во вложенном списке того же меню; включённый звук возвращается одним нажатием.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { formatDmMuteUntil, getDmChatMutedUntil, setDmChatMuted } from '../services/dm-chat-prefs.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const DURATIONS = [
|
||||
['На 1 час', HOUR],
|
||||
['На 8 часов', 8 * HOUR],
|
||||
['На сутки', 24 * HOUR],
|
||||
['На неделю', 7 * 24 * HOUR],
|
||||
['Навсегда', 0],
|
||||
];
|
||||
|
||||
export function createDmMuteMenuItem(chatId, { iconClass = '', onChange = null } = {}) {
|
||||
const until = getDmChatMutedUntil(chatId);
|
||||
if (until !== null) {
|
||||
return {
|
||||
label: 'Включить звук',
|
||||
hint: until ? `Без звука ${formatDmMuteUntil(until)}` : '',
|
||||
iconHtml: iconHtml('bell', false, iconClass),
|
||||
action: () => {
|
||||
setDmChatMuted(chatId, false);
|
||||
showToast('Уведомления включены', { timeoutMs: 1400 });
|
||||
onChange?.(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
label: 'Без звука',
|
||||
iconHtml: iconHtml('bell-off', false, iconClass),
|
||||
submenu: DURATIONS.map(([label, ms]) => ({
|
||||
label,
|
||||
action: () => {
|
||||
const untilMs = ms ? Date.now() + ms : 0;
|
||||
setDmChatMuted(chatId, true, { untilMs });
|
||||
showToast(untilMs ? `Уведомления выключены ${formatDmMuteUntil(untilMs)}` : 'Уведомления от этого чата выключены', { timeoutMs: 1800 });
|
||||
onChange?.(true);
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
let activeDropdown = null;
|
||||
|
||||
function normalizeItems(items) {
|
||||
@@ -73,8 +75,29 @@ export function createDropdownMenu({
|
||||
menuEl.style.top = `${Math.round(top)}px`;
|
||||
};
|
||||
|
||||
const appendItems = () => {
|
||||
normalizeItems(items).forEach((item) => {
|
||||
// Пункт с submenu не закрывает меню, а показывает вложенный список на том же месте
|
||||
// (сверху – «назад»): так выбирают, например, срок «без звука».
|
||||
const appendItems = (levelItems = items, parentTitle = '') => {
|
||||
if (parentTitle) {
|
||||
const back = document.createElement('button');
|
||||
back.type = 'button';
|
||||
back.className = 'dropdown-menu__item dropdown-menu__back';
|
||||
back.setAttribute('aria-label', `Назад: ${parentTitle}`);
|
||||
back.innerHTML = `<span class="dropdown-menu__icon">${iconHtml('back')}</span>`;
|
||||
const backLabel = document.createElement('span');
|
||||
backLabel.textContent = parentTitle;
|
||||
back.append(backLabel);
|
||||
back.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
showLevel(items, '');
|
||||
});
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dropdown-menu__divider';
|
||||
divider.setAttribute('role', 'separator');
|
||||
menuEl.append(back, divider);
|
||||
}
|
||||
normalizeItems(levelItems).forEach((item) => {
|
||||
if (item.divider) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dropdown-menu__divider';
|
||||
@@ -105,11 +128,33 @@ export function createDropdownMenu({
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = String(item.label || '');
|
||||
button.append(label);
|
||||
if (item.hint) {
|
||||
const text = document.createElement('span');
|
||||
text.className = 'dropdown-menu__text';
|
||||
const hint = document.createElement('small');
|
||||
hint.className = 'dropdown-menu__hint';
|
||||
hint.textContent = String(item.hint);
|
||||
text.append(label, hint);
|
||||
button.append(text);
|
||||
} else {
|
||||
button.append(label);
|
||||
}
|
||||
if (item.submenu) {
|
||||
button.setAttribute('aria-haspopup', 'menu');
|
||||
const chevron = document.createElement('span');
|
||||
chevron.className = 'dropdown-menu__chevron';
|
||||
chevron.setAttribute('aria-hidden', 'true');
|
||||
chevron.innerHTML = iconHtml('chevron');
|
||||
button.append(chevron);
|
||||
}
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (button.disabled) return;
|
||||
if (item.submenu) {
|
||||
showLevel(item.submenu, String(item.submenuTitle || item.label || ''));
|
||||
return;
|
||||
}
|
||||
close({ focusAnchor: true });
|
||||
await item.action?.();
|
||||
});
|
||||
@@ -117,6 +162,16 @@ export function createDropdownMenu({
|
||||
});
|
||||
};
|
||||
|
||||
const showLevel = (levelItems, parentTitle) => {
|
||||
if (!menuEl) return;
|
||||
menuEl.replaceChildren();
|
||||
appendItems(levelItems, parentTitle);
|
||||
position();
|
||||
// Во вложенном списке фокус – на первый вариант, а не на «назад».
|
||||
(menuEl.querySelector('button:not(:disabled):not(.dropdown-menu__back)')
|
||||
|| menuEl.querySelector('button:not(:disabled)'))?.focus();
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
if (destroyed || !anchorEl || portal) return;
|
||||
if (activeDropdown && activeDropdown !== api) activeDropdown.close();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Общие состояния экрана: загрузка, «пусто» и ошибка – один вид на всё приложение.
|
||||
// Индикатор загрузки появляется с задержкой (CSS): если данные пришли быстро, его не видно
|
||||
// вовсе, и экран не мелькает.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function createSpinner({ size = 'md', label = 'Загрузка' } = {}) {
|
||||
const el = document.createElement('span');
|
||||
el.className = `spinner spinner--${size}`;
|
||||
el.setAttribute('role', 'status');
|
||||
el.setAttribute('aria-label', label);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createLoadingState({ label = 'Загрузка', delayMs = 350, className = '' } = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `loading-state${className ? ` ${className}` : ''}`;
|
||||
el.style.setProperty('--loading-delay', `${Math.max(0, Number(delayMs) || 0)}ms`);
|
||||
el.append(createSpinner({ label }));
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение вместо содержимого: пусто или ошибка, с необязательным действием.
|
||||
* @param {{ kind?: 'empty'|'error', icon?: string, title?: string, text?: string,
|
||||
* actionLabel?: string, onAction?: Function, className?: string }} opts
|
||||
*/
|
||||
export function createStateMessage({
|
||||
kind = 'empty', icon = '', title = '', text = '', actionLabel = '', onAction = null, className = '',
|
||||
} = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `state-message state-message--${kind}${className ? ` ${className}` : ''}`;
|
||||
if (kind === 'error') el.setAttribute('role', 'alert');
|
||||
if (icon) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'state-message__icon';
|
||||
badge.innerHTML = iconHtml(icon);
|
||||
el.append(badge);
|
||||
}
|
||||
if (title) {
|
||||
const heading = document.createElement('p');
|
||||
heading.className = 'state-message__title';
|
||||
heading.textContent = title;
|
||||
el.append(heading);
|
||||
}
|
||||
if (text) {
|
||||
const body = document.createElement('p');
|
||||
body.className = 'state-message__text';
|
||||
body.textContent = text;
|
||||
el.append(body);
|
||||
}
|
||||
if (actionLabel && typeof onAction === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `${kind === 'error' ? 'secondary-btn' : 'primary-btn'} state-message__action`;
|
||||
button.textContent = actionLabel;
|
||||
button.addEventListener('click', onAction);
|
||||
el.append(button);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createErrorState({
|
||||
title = 'Не удалось загрузить',
|
||||
text = 'Проверьте соединение и попробуйте ещё раз.',
|
||||
onRetry = null,
|
||||
className = '',
|
||||
} = {}) {
|
||||
return createStateMessage({
|
||||
kind: 'error', icon: 'alert', title, text, actionLabel: onRetry ? 'Повторить' : '', onAction: onRetry, className,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Шторка «Заметка о человеке»: текст и цветная метка, видны только владельцу аккаунта.
|
||||
// Открывается с карты связей и из профиля человека; хранение – services/people-notes.js.
|
||||
import { openSheet } from './sheet.js';
|
||||
import { NOTE_MARKS, PERSON_NOTE_MAX_TEXT, getPersonNote, setPersonNote } from '../services/people-notes.js';
|
||||
|
||||
export function openPersonNoteSheet({ login, name = '', onClose = null } = {}) {
|
||||
const current = getPersonNote(login);
|
||||
let mark = current?.mark || '';
|
||||
return openSheet({
|
||||
title: `Заметка: ${name || login}`,
|
||||
className: 'person-note-sheet',
|
||||
onClose,
|
||||
content: (sheet) => {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack person-note';
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'meta-muted person-note__hint';
|
||||
hint.textContent = 'Видна только вам. Пока хранится на этом устройстве.';
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.className = 'input person-note__text';
|
||||
textarea.rows = 5;
|
||||
textarea.maxLength = PERSON_NOTE_MAX_TEXT;
|
||||
textarea.placeholder = 'Кто это, откуда знакомы, о чём договорились…';
|
||||
textarea.value = current?.text || '';
|
||||
textarea.setAttribute('aria-label', 'Текст заметки');
|
||||
textarea.autofocus = true;
|
||||
|
||||
const marksLabel = document.createElement('div');
|
||||
marksLabel.className = 'person-note__label';
|
||||
marksLabel.id = `person-note-marks-${Math.random().toString(36).slice(2, 8)}`;
|
||||
marksLabel.textContent = 'Метка на карте связей';
|
||||
const marks = document.createElement('div');
|
||||
marks.className = 'person-note__marks';
|
||||
marks.setAttribute('role', 'radiogroup');
|
||||
marks.setAttribute('aria-labelledby', marksLabel.id);
|
||||
const markButtons = [];
|
||||
const syncMarks = () => markButtons.forEach((button) => button.setAttribute('aria-checked', String(button.dataset.mark === mark)));
|
||||
for (const option of [{ id: '', label: 'Без метки' }, ...NOTE_MARKS]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'person-note__mark';
|
||||
button.dataset.mark = option.id;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-label', option.label);
|
||||
button.title = option.label;
|
||||
button.addEventListener('click', () => { mark = option.id; syncMarks(); });
|
||||
markButtons.push(button);
|
||||
marks.append(button);
|
||||
}
|
||||
syncMarks();
|
||||
wrap.append(hint, textarea, marksLabel, marks);
|
||||
|
||||
if (current) {
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'ghost-btn person-note__remove';
|
||||
remove.textContent = 'Удалить';
|
||||
remove.addEventListener('click', () => {
|
||||
setPersonNote(login, { text: '', mark: '' });
|
||||
sheet.close();
|
||||
});
|
||||
sheet.footer.append(remove);
|
||||
}
|
||||
const save = document.createElement('button');
|
||||
save.type = 'button';
|
||||
save.className = 'primary-btn person-note__save';
|
||||
save.textContent = 'Сохранить';
|
||||
save.addEventListener('click', () => {
|
||||
setPersonNote(login, { text: textarea.value, mark });
|
||||
sheet.close();
|
||||
});
|
||||
sheet.footer.append(save);
|
||||
return wrap;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Готовый блок заметки (для карточки на карте и профиля); null, если заметки нет.
|
||||
export function createPersonNotePreview(note, { className = '', onClick = null } = {}) {
|
||||
if (!note) return null;
|
||||
const el = document.createElement(onClick ? 'button' : 'div');
|
||||
if (onClick) {
|
||||
el.type = 'button';
|
||||
el.title = 'Изменить заметку';
|
||||
el.addEventListener('click', onClick);
|
||||
}
|
||||
el.className = `person-note-preview${className ? ` ${className}` : ''}`;
|
||||
if (note.mark) el.dataset.mark = note.mark;
|
||||
el.textContent = note.text.trim() || 'Метка без текста';
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Строка человека в списках (связи, поиск людей, списки профиля): аватар, имя, строка под
|
||||
// ним и действия справа. Вид совпадает со строками списка чатов.
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/**
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login
|
||||
* @param {string} [opts.name] – как показывать (по умолчанию логин)
|
||||
* @param {string} [opts.firstName] [opts.lastName] – для инициалов
|
||||
* @param {Object|null} [opts.avatar]
|
||||
* @param {string} [opts.sub] – строка под именем
|
||||
* @param {string} [opts.note] – личная заметка (третья строка, курсивом)
|
||||
* @param {string} [opts.markColor] – метка заметки: green/yellow/red/blue/violet, 'note' – без цвета, '' – нет
|
||||
* @param {'close'|'shining'|''} [opts.ring] – цветное кольцо вокруг аватара
|
||||
* @param {boolean} [opts.official]
|
||||
* @param {string} [opts.tag] – короткая пометка цветом в начале второй строки («ждёт ответа»)
|
||||
* @param {Function} [opts.onClick]
|
||||
* @param {Array<{icon:string,label:string,onClick:Function}>} [opts.actions]
|
||||
*/
|
||||
export function createPersonRow({
|
||||
login, name = '', firstName = '', lastName = '', avatar = null, sub = '', note = '', markColor = '',
|
||||
ring = '', official = false, tag = '', onClick = null, actions = [],
|
||||
} = {}) {
|
||||
const row = document.createElement('div');
|
||||
row.className = `person-row${ring ? ` person-row--${ring}` : ''}`;
|
||||
row.dataset.login = String(login || '');
|
||||
|
||||
const main = document.createElement('button');
|
||||
main.type = 'button';
|
||||
main.className = 'person-row__main';
|
||||
const avatarWrap = document.createElement('span');
|
||||
avatarWrap.className = 'person-row__avatar';
|
||||
// Имя и фамилию отдельно знают не все источники (поиск по сети отдаёт одно «displayName») –
|
||||
// тогда инициалы берутся из показанного имени, а не из логина.
|
||||
const nameParts = name && name !== login ? String(name).trim().split(/\s+/) : [];
|
||||
const initialsFirst = firstName || nameParts[0] || '';
|
||||
const initialsLast = lastName || (nameParts.length > 1 ? nameParts[nameParts.length - 1] : '');
|
||||
avatarWrap.append(renderUserAvatar({ login, firstName: initialsFirst, lastName: initialsLast, avatar, size: 'md', official }));
|
||||
if (markColor) {
|
||||
// Метка заметки – та же цветная точка, что на карте связей; 'note' – заметка без цвета.
|
||||
const mark = document.createElement('span');
|
||||
mark.className = 'person-row__mark';
|
||||
mark.dataset.mark = markColor;
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
avatarWrap.append(mark);
|
||||
}
|
||||
const text = document.createElement('span');
|
||||
text.className = 'person-row__text';
|
||||
const title = document.createElement('span');
|
||||
title.className = 'person-row__name';
|
||||
const titleText = document.createElement('span');
|
||||
titleText.className = 'person-row__name-text';
|
||||
titleText.textContent = name || login;
|
||||
title.append(titleText);
|
||||
text.append(title);
|
||||
if (sub || tag) {
|
||||
// Пометка («ждёт ответа») – в начале второй строки, чтобы не съедать место у имени.
|
||||
const subEl = document.createElement('span');
|
||||
subEl.className = 'person-row__sub';
|
||||
if (tag) {
|
||||
const tagEl = document.createElement('span');
|
||||
tagEl.className = 'person-row__tag';
|
||||
tagEl.textContent = tag;
|
||||
subEl.append(tagEl);
|
||||
if (sub) subEl.append(' · ');
|
||||
}
|
||||
if (sub) subEl.append(sub);
|
||||
text.append(subEl);
|
||||
}
|
||||
if (note) {
|
||||
const noteEl = document.createElement('span');
|
||||
noteEl.className = 'person-row__note';
|
||||
noteEl.textContent = note;
|
||||
text.append(noteEl);
|
||||
}
|
||||
main.append(avatarWrap, text);
|
||||
if (typeof onClick === 'function') main.addEventListener('click', onClick);
|
||||
row.append(main);
|
||||
|
||||
for (const action of actions) {
|
||||
if (!action) continue;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'icon-btn person-row__action';
|
||||
button.innerHTML = iconHtml(action.icon);
|
||||
button.setAttribute('aria-label', action.label);
|
||||
button.title = action.label;
|
||||
button.addEventListener('click', (event) => action.onClick?.(event, button));
|
||||
row.append(button);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
// Заголовок группы в списке («Друзья · 58», «А»).
|
||||
export function createListSection(text) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'person-list-section';
|
||||
el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
@@ -12,29 +12,35 @@ export function escapeProfileHtml(text) {
|
||||
|
||||
const esc = escapeProfileHtml;
|
||||
|
||||
function statusCardHtml({ kind, title, received, given }) {
|
||||
// Раздел статуса («Сияние», «Официальный»): кто подтвердил этот аккаунт и кого подтвердил он сам.
|
||||
function statusSectionHtml({ kind, title, received, given, receivedLabel, givenLabel }) {
|
||||
const receivedCount = Number(received || 0);
|
||||
const givenCount = Number(given || 0);
|
||||
const isOfficial = kind === 'primary';
|
||||
const receivedKind = isOfficial ? 'primary_received' : 'shine_received';
|
||||
const givenKind = isOfficial ? 'primary_given' : 'shine_given';
|
||||
const receivedTitle = isOfficial ? 'Кто подтвердил этот официальный аккаунт' : 'Кто подтвердил, что этот аккаунт сияющий';
|
||||
const givenTitle = isOfficial ? 'Какие официальные аккаунты подтвердил этот пользователь' : 'Кого этот пользователь подтвердил как сияющего';
|
||||
|
||||
return `
|
||||
<section class="pf-status-card pf-status-card--${esc(kind)}" aria-label="${esc(title)}">
|
||||
<div class="pf-status-card-title">${esc(title)}</div>
|
||||
<button type="button" class="pf-status-card-count" data-profile-list="${receivedKind}"
|
||||
aria-label="${esc(receivedTitle)}: ${receivedCount}" title="${esc(receivedTitle)}">
|
||||
<strong>${receivedCount}</strong><span>подтвердили</span>
|
||||
</button>
|
||||
<button type="button" class="pf-status-card-count" data-profile-list="${givenKind}"
|
||||
aria-label="${esc(givenTitle)}: ${givenCount}" title="${esc(givenTitle)}">
|
||||
<strong>${givenCount}</strong><span>подтвердил</span>
|
||||
</button>
|
||||
<section class="pf-status-section pf-status-section--${esc(kind)}" aria-label="${esc(title)}">
|
||||
<h3 class="nav-list__title">${esc(title)}</h3>
|
||||
<div class="nav-list">
|
||||
<button type="button" class="nav-row" data-profile-list="${isOfficial ? 'primary_received' : 'shine_received'}">
|
||||
<span class="nav-row__label">${esc(receivedLabel)}</span>
|
||||
<span class="nav-row__hint">${esc(peopleCount(receivedCount))}</span>
|
||||
</button>
|
||||
<button type="button" class="nav-row" data-profile-list="${isOfficial ? 'primary_given' : 'shine_given'}">
|
||||
<span class="nav-row__label">${esc(givenLabel)}</span>
|
||||
<span class="nav-row__hint">${esc(peopleCount(givenCount))}</span>
|
||||
</button>
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function peopleCount(count) {
|
||||
if (!count) return 'Пока никого';
|
||||
const mod10 = count % 10;
|
||||
const mod100 = count % 100;
|
||||
const word = mod10 === 1 && mod100 !== 11 ? 'человек' : (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) ? 'человека' : 'человек';
|
||||
return `${count} ${word}`;
|
||||
}
|
||||
|
||||
function statHtml({ kind, label, valueHtml, ariaLabel }) {
|
||||
return `
|
||||
<button type="button" class="pf-stat" data-profile-list="${esc(kind)}" aria-label="${esc(ariaLabel)}">
|
||||
@@ -91,32 +97,42 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
const friends = Number(stats.friendsCount || 0);
|
||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||
|
||||
const officialCard = official
|
||||
? statusCardHtml({
|
||||
kind: 'primary',
|
||||
title: 'Официальный',
|
||||
received: stats.primaryReceivedCount,
|
||||
given: stats.primaryGivenCount,
|
||||
})
|
||||
: '';
|
||||
const shiningCard = shining
|
||||
? statusCardHtml({
|
||||
const shineReceived = Number(stats.shineReceivedCount || 0);
|
||||
const shineGiven = Number(stats.shineGivenCount || 0);
|
||||
const primaryReceived = Number(stats.primaryReceivedCount || 0);
|
||||
const primaryGiven = Number(stats.primaryGivenCount || 0);
|
||||
// Раздел виден у сияющих и у всех, кого уже подтверждали или кто подтверждал сам.
|
||||
const shineSection = (shining || shineReceived || shineGiven)
|
||||
? statusSectionHtml({
|
||||
kind: 'shine',
|
||||
title: 'Сияющий',
|
||||
received: stats.shineReceivedCount,
|
||||
given: stats.shineGivenCount,
|
||||
title: 'Сияние',
|
||||
received: shineReceived,
|
||||
given: shineGiven,
|
||||
receivedLabel: 'Подтвердили, что сияющий',
|
||||
givenLabel: 'Подтвердил сияющими',
|
||||
})
|
||||
: '';
|
||||
const officialSection = (official || primaryReceived || primaryGiven)
|
||||
? statusSectionHtml({
|
||||
kind: 'primary',
|
||||
title: 'Официальный аккаунт',
|
||||
received: primaryReceived,
|
||||
given: primaryGiven,
|
||||
receivedLabel: 'Подтвердили, что официальный',
|
||||
givenLabel: 'Подтвердил официальными',
|
||||
})
|
||||
: '';
|
||||
const badges = [
|
||||
shining ? '<span class="pf-badge pf-badge--shine">Сияющий</span>' : '',
|
||||
official ? '<span class="pf-badge pf-badge--official">Официальный</span>' : '',
|
||||
].join('');
|
||||
|
||||
return `
|
||||
<div class="pf-hero" aria-label="Профиль ${esc(cardLogin)}">
|
||||
<div class="pf-identity">
|
||||
<div class="pf-status-card-slot pf-status-card-slot--left">${officialCard}</div>
|
||||
<div class="pf-avatar user-profile-avatar-slot"></div>
|
||||
<div class="pf-status-card-slot pf-status-card-slot--right">${shiningCard}</div>
|
||||
</div>
|
||||
<div class="pf-avatar user-profile-avatar-slot${shining ? ' is-shining' : ''}"></div>
|
||||
<h2 class="pf-name">${esc(displayName)}</h2>
|
||||
<div class="pf-login">@${esc(cardLogin)}</div>
|
||||
${badges ? `<div class="pf-badges">${badges}</div>` : ''}
|
||||
</div>
|
||||
|
||||
<div class="pf-stats">
|
||||
@@ -131,6 +147,8 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
<div class="pf-tiles user-profile-actions">${tilesHtml}</div>
|
||||
</div>` : ''}
|
||||
|
||||
${shineSection}
|
||||
${officialSection}
|
||||
${listHtml}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export function openShareSheet({ title = 'Поделиться', kicker = '', te
|
||||
} catch {
|
||||
field.focus();
|
||||
field.select();
|
||||
showToast('Выделил ссылку – скопируйте её вручную', { kind: 'error' });
|
||||
showToast('Ссылка выделена – скопируйте её вручную', { kind: 'info' });
|
||||
}
|
||||
});
|
||||
wrap.append(preview, label, copy);
|
||||
|
||||
@@ -116,3 +116,67 @@ export function createTopBar({
|
||||
|
||||
return topbar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шапка-строка поиска (поиск по переписке, по связям и т. п.): «назад» закрывает поиск,
|
||||
* крестик очищает поле, Enter – onSubmit, Escape – onClose.
|
||||
* trailing – узел справа внутри поля (например, счётчик «3 из 12»).
|
||||
*/
|
||||
export function createSearchTopBar({
|
||||
placeholder = 'Поиск',
|
||||
value = '',
|
||||
onInput = null,
|
||||
onSubmit = null,
|
||||
onClose = null,
|
||||
trailing = null,
|
||||
actions = [],
|
||||
className = '',
|
||||
} = {}) {
|
||||
const field = document.createElement('label');
|
||||
field.className = 'topbar-search';
|
||||
field.innerHTML = `
|
||||
<span class="topbar-search__icon" aria-hidden="true">${iconHtml('search')}</span>
|
||||
<input class="topbar-search__input" type="search" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="search" />
|
||||
`;
|
||||
const input = field.querySelector('input');
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute('aria-label', placeholder);
|
||||
input.value = value;
|
||||
if (trailing instanceof Node) field.append(trailing);
|
||||
const clear = document.createElement('button');
|
||||
clear.type = 'button';
|
||||
clear.className = 'topbar-search__clear';
|
||||
clear.innerHTML = iconHtml('close');
|
||||
clear.setAttribute('aria-label', 'Очистить');
|
||||
clear.title = 'Очистить';
|
||||
clear.hidden = !value;
|
||||
clear.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
input.value = '';
|
||||
clear.hidden = true;
|
||||
input.focus();
|
||||
onInput?.('');
|
||||
});
|
||||
field.append(clear);
|
||||
input.addEventListener('input', () => {
|
||||
clear.hidden = !input.value;
|
||||
onInput?.(input.value);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
onSubmit?.(input.value, event);
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose?.();
|
||||
}
|
||||
});
|
||||
const topbar = createTopBar({
|
||||
center: field,
|
||||
className: `topbar--search${className ? ` ${className}` : ''}`,
|
||||
back: { onClick: () => onClose?.(), ariaLabel: 'Закрыть поиск', title: 'Закрыть поиск' },
|
||||
actions,
|
||||
});
|
||||
topbar.searchInput = input;
|
||||
return topbar;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ const paths = {
|
||||
emoji: '<circle cx="12" cy="12" r="9"/><path d="M8.3 14.2a4.6 4.6 0 0 0 7.4 0"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/>',
|
||||
send: '<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>',
|
||||
mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>',
|
||||
image: '<rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m21 16-4.7-4.7L7 20.5"/>',
|
||||
camera: '<path d="M4.5 7.5h2.8l1.7-2.5h6l1.7 2.5h2.8A1.5 1.5 0 0 1 21 9v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18V9a1.5 1.5 0 0 1 1.5-1.5Z"/><circle cx="12" cy="13" r="3.5"/>',
|
||||
image: '<rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m21 16-4.7-4.7-8.2 8.2"/>',
|
||||
list: '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r=".9" fill="currentColor" stroke="none"/>',
|
||||
doc: '<path d="M6.5 3h7.5L19 8v11.5a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 19.5v-15A1.5 1.5 0 0 1 6.5 3Z"/><path d="M14 3v5h5M8.5 13h7M8.5 16.5h5"/>',
|
||||
close: '<path d="M6 6l12 12M18 6 6 18"/>',
|
||||
@@ -35,6 +36,10 @@ const paths = {
|
||||
check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
|
||||
open: '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
||||
chevron: '<path d="m9 6 6 6-6 6"/>',
|
||||
'chevron-up': '<path d="m6 15 6-6 6 6"/>',
|
||||
'chevron-down': '<path d="m6 9 6 6 6-6"/>',
|
||||
calendar: '<rect x="3.5" y="5" width="17" height="15.5" rx="2.5"/><path d="M3.5 10h17M8 3v4M16 3v4"/>',
|
||||
pin: '<path d="M9 3.5h6M10 3.5v6.2L6.5 14h11L14 9.7V3.5M12 14v6.5"/>',
|
||||
back: '<path d="M19 12H5M11 5l-7 7 7 7"/>',
|
||||
down: '<path d="M12 5v14M5 12l7 7 7-7"/>',
|
||||
edit: '<path d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16v4Z"/><path d="m13.5 6.5 4 4"/>',
|
||||
@@ -44,7 +49,12 @@ const paths = {
|
||||
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
||||
eye: '<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/>',
|
||||
eyeOff: '<path d="M10.2 5.7A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16.4 16.4 0 0 1-2.6 3.4M6.4 7A16.2 16.2 0 0 0 2.5 12S6 18.5 12 18.5a9 9 0 0 0 4.9-1.4"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2M3.5 3.5l17 17"/>',
|
||||
repost: '<path d="M17 2.5 20.5 6 17 9.5"/><path d="M3.5 11.5V9a3 3 0 0 1 3-3h14"/><path d="M7 21.5 3.5 18 7 14.5"/><path d="M20.5 12.5V15a3 3 0 0 1-3 3h-14"/>',
|
||||
expand: '<path d="M14 4h6v6M10 20H4v-6M20 4l-6.5 6.5M4 20l6.5-6.5"/>',
|
||||
clip: '<path d="m20.5 11.5-8.2 8.2a5 5 0 0 1-7.1-7.1l8.5-8.5a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.5a1.7 1.7 0 0 1-2.4-2.4l7.8-7.8"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
fit: '<path d="M4 9V5.5A1.5 1.5 0 0 1 5.5 4H9M15 4h3.5A1.5 1.5 0 0 1 20 5.5V9M20 15v3.5a1.5 1.5 0 0 1-1.5 1.5H15M9 20H5.5A1.5 1.5 0 0 1 4 18.5V15"/><circle cx="12" cy="12" r="2.5"/>',
|
||||
focus: '<circle cx="12" cy="12" r="7.5"/><circle cx="12" cy="12" r="2.2" fill="currentColor" stroke="none"/><path d="M12 2v2.5M12 19.5V22M2 12h2.5M19.5 12H22"/>',
|
||||
};
|
||||
|
||||
export function iconHtml(name, filled = false, className = '') {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'access-keys-view', title: 'Ключи доступа' };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({ title: 'Ключи доступа', back: { label: '←', onClick: () => navigate('settings-view') } }));
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'nav-list';
|
||||
actions.innerHTML = `
|
||||
<button type="button" class="nav-row" id="access-keys-show"><span class="nav-row__label">Показать ключи доступа</span><span class="nav-row__hint">Ключи, сохранённые на этом устройстве</span></button>
|
||||
<button type="button" class="nav-row" id="access-keys-rotate"><span class="nav-row__label">Сменить пароль</span><span class="nav-row__hint">Смена пароля также меняет ключи аккаунта и закрывает другие сеансы</span></button>
|
||||
`;
|
||||
actions.querySelector('#access-keys-show').addEventListener('click', () => navigate('show-keys-view'));
|
||||
actions.querySelector('#access-keys-rotate').addEventListener('click', () => navigate('key-rotation-view'));
|
||||
screen.append(actions);
|
||||
return screen;
|
||||
}
|
||||
@@ -97,7 +97,7 @@ function createConfirmModal() {
|
||||
}) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-confirm-modal">
|
||||
<div class="modal-card stack" style="max-width:min(94vw,34rem);">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title" id="access-servers-dialog-title"></h3>
|
||||
<p class="meta-muted" id="access-servers-dialog-text" style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<p class="meta-muted" id="access-servers-dialog-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
@@ -166,7 +166,7 @@ function createPasswordModal() {
|
||||
open({ title, text, note = '' }) {
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="access-servers-password-modal">
|
||||
<div class="modal-card stack" style="max-width:min(94vw,36rem);">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title" id="access-servers-password-title"></h3>
|
||||
<p class="meta-muted" id="access-servers-password-text" style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
<p class="meta-muted" id="access-servers-password-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||
@@ -265,7 +265,9 @@ export function render({navigate, chrome}) {
|
||||
const introCard = document.createElement('div');
|
||||
introCard.className = 'settings-intro';
|
||||
introCard.innerHTML = `
|
||||
<p class="meta-muted">Сервер доступа хранит вашу зашифрованную переписку и настройки и помогает со звонками. Публичные записи доступны через любой сервер. При смене сервера переписка сама не переносится.</p>
|
||||
<strong>Мой сервер доступа</strong>
|
||||
<p class="meta-muted">Вы работаете через сервер доступа, указанный ниже. Здесь хранится зашифрованная переписка и настройки, а также обеспечивается работа звонков.</p>
|
||||
<p class="meta-muted">В будущем можно будет одновременно подключаться к двум и более серверам доступа (RAS) для повышения стабильности. Сейчас эта возможность ещё не реализована.</p>
|
||||
`;
|
||||
|
||||
const listCard = document.createElement('div');
|
||||
@@ -292,7 +294,7 @@ export function render({navigate, chrome}) {
|
||||
addTitle.textContent = 'Сменить сервер доступа';
|
||||
const addHint = document.createElement('p');
|
||||
addHint.className = 'meta-muted';
|
||||
addHint.textContent = 'Введите логин нового сервера или несколько первых букв, затем выберите сервер из подсказок. Новый сервер заменит текущий.';
|
||||
addHint.textContent = 'Тестовая функция веб-версии. Для обычной смены сервера доступа необходимо открыть новый сервер и выполнить смену оттуда. Здесь можно указать новый сервер напрямую; переписка автоматически не переносится.';
|
||||
const addInput = document.createElement('input');
|
||||
addInput.className = 'input';
|
||||
addInput.type = 'text';
|
||||
@@ -310,6 +312,16 @@ export function render({navigate, chrome}) {
|
||||
addButton.textContent = 'Сменить сервер';
|
||||
addButton.disabled = true;
|
||||
addCard.append(addTitle, addHint, addInput, suggestEl, addStatus, addButton);
|
||||
addCard.hidden = true;
|
||||
const changeServerToggle = document.createElement('button');
|
||||
changeServerToggle.type = 'button';
|
||||
changeServerToggle.className = 'secondary-btn';
|
||||
changeServerToggle.textContent = 'Сменить сервер доступа (тестовая функция)';
|
||||
changeServerToggle.setAttribute('aria-expanded', 'false');
|
||||
changeServerToggle.addEventListener('click', () => {
|
||||
addCard.hidden = !addCard.hidden;
|
||||
changeServerToggle.setAttribute('aria-expanded', String(!addCard.hidden));
|
||||
});
|
||||
|
||||
const refreshAddButton = () => {
|
||||
addButton.disabled = operationBusy
|
||||
@@ -613,12 +625,13 @@ export function render({navigate, chrome}) {
|
||||
});
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Сервер доступа',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
title: 'Мой сервер доступа',
|
||||
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||
}));
|
||||
screen.append(
|
||||
introCard,
|
||||
listCard,
|
||||
changeServerToggle,
|
||||
addCard,
|
||||
);
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ function renderAvatarPreview(slot, avatar, title) {
|
||||
avatar,
|
||||
authorLogin: state.session.login,
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar',
|
||||
className: 'channel-profile-avatar avatar-plain',
|
||||
title: label,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// «Оформление»: тема (Авто / Светлая / Тёмная) и палитра – образцами, применяются сразу.
|
||||
// Тонкая ручная настройка цветов – прежний редактор палитры.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
import {
|
||||
PALETTE_PRESETS, getPaletteSettings, getThemeMode, resolvePalette, resolveThemeMode, setPaletteSettings, setThemeMode,
|
||||
} from '../services/theme-service.js';
|
||||
|
||||
export const pageMeta = { id: 'appearance-view', title: 'Оформление' };
|
||||
|
||||
const THEME_MODES = [
|
||||
['system', 'Авто'],
|
||||
['light', 'Светлая'],
|
||||
['dark', 'Тёмная'],
|
||||
];
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack appearance-screen';
|
||||
let closeEditor = null; // openPaletteEditor возвращает функцию закрытия
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Оформление',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
// --- тема ---
|
||||
const themeTitle = document.createElement('p');
|
||||
themeTitle.className = 'nav-list__title';
|
||||
themeTitle.textContent = 'Тема';
|
||||
const themeTabs = document.createElement('div');
|
||||
themeTabs.className = 'tabs tabs--three appearance-theme';
|
||||
themeTabs.setAttribute('role', 'radiogroup');
|
||||
themeTabs.setAttribute('aria-label', 'Тема оформления');
|
||||
const themeHint = document.createElement('p');
|
||||
themeHint.className = 'meta-muted appearance-hint';
|
||||
for (const [mode, label] of THEME_MODES) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.mode = mode;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.textContent = label;
|
||||
button.addEventListener('click', () => {
|
||||
setThemeMode(mode);
|
||||
sync();
|
||||
});
|
||||
themeTabs.append(button);
|
||||
}
|
||||
|
||||
// --- палитра ---
|
||||
const paletteTitle = document.createElement('p');
|
||||
paletteTitle.className = 'nav-list__title';
|
||||
paletteTitle.textContent = 'Цвета';
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'palette-grid';
|
||||
grid.setAttribute('role', 'radiogroup');
|
||||
grid.setAttribute('aria-label', 'Палитра');
|
||||
const swatches = new Map();
|
||||
for (const [id, preset] of Object.entries(PALETTE_PRESETS)) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'palette-swatch';
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-label', preset.label);
|
||||
button.innerHTML = `
|
||||
<span class="palette-swatch__sample" aria-hidden="true">
|
||||
<span class="palette-swatch__bar"></span>
|
||||
<span class="palette-swatch__bubble"></span>
|
||||
<span class="palette-swatch__dot"></span>
|
||||
<span class="palette-swatch__check">${iconHtml('check')}</span>
|
||||
</span>
|
||||
<span class="palette-swatch__label"></span>
|
||||
`;
|
||||
button.querySelector('.palette-swatch__label').textContent = preset.label;
|
||||
button.addEventListener('click', () => {
|
||||
// Выбор готовой палитры сбрасывает ручные правки – иначе выбор выглядел бы «не тем».
|
||||
setPaletteSettings({ preset: id, custom: { dark: {}, light: {} } });
|
||||
sync();
|
||||
});
|
||||
swatches.set(id, button);
|
||||
grid.append(button);
|
||||
}
|
||||
|
||||
const more = document.createElement('div');
|
||||
more.className = 'nav-list';
|
||||
const customRow = document.createElement('button');
|
||||
customRow.type = 'button';
|
||||
customRow.className = 'nav-row';
|
||||
customRow.innerHTML = '<span class="nav-row__label">Настроить цвета вручную</span><span class="nav-row__hint"></span>';
|
||||
customRow.addEventListener('click', () => {
|
||||
closeEditor?.();
|
||||
closeEditor = openPaletteEditor({ onClose: () => { closeEditor = null; sync(); } });
|
||||
});
|
||||
more.append(customRow);
|
||||
|
||||
function sync() {
|
||||
const mode = getThemeMode();
|
||||
const resolved = resolveThemeMode(mode);
|
||||
themeTabs.querySelectorAll('.tab-btn').forEach((button) => {
|
||||
button.setAttribute('aria-checked', String(button.dataset.mode === mode));
|
||||
});
|
||||
themeHint.textContent = mode === 'system'
|
||||
? `Как в системе устройства: сейчас ${resolved === 'light' ? 'светлая' : 'тёмная'}.`
|
||||
: 'Не зависит от настроек устройства.';
|
||||
const settings = getPaletteSettings();
|
||||
const customized = Object.keys(settings.custom.dark).length + Object.keys(settings.custom.light).length > 0;
|
||||
swatches.forEach((button, id) => {
|
||||
// Образцы показывают ту тему, что сейчас на экране.
|
||||
const colors = resolvePalette(resolved, { preset: id, custom: { dark: {}, light: {} } });
|
||||
const sample = button.querySelector('.palette-swatch__sample');
|
||||
sample.style.setProperty('--swatch-bg', colors.background);
|
||||
sample.style.setProperty('--swatch-surface', colors.surface);
|
||||
sample.style.setProperty('--swatch-accent', colors.accent);
|
||||
sample.style.setProperty('--swatch-bubble', colors['bubble-out']);
|
||||
sample.style.setProperty('--swatch-on-accent', colors['on-accent']);
|
||||
button.setAttribute('aria-checked', String(settings.preset === id && !customized));
|
||||
});
|
||||
customRow.querySelector('.nav-row__hint').textContent = customized
|
||||
? `Свои правки поверх «${PALETTE_PRESETS[settings.preset]?.label || settings.preset}»`
|
||||
: 'Каждый цвет отдельно, для светлой и тёмной темы';
|
||||
}
|
||||
|
||||
sync();
|
||||
screen.append(themeTitle, themeTabs, themeHint, paletteTitle, grid, more);
|
||||
screen.cleanup = () => {
|
||||
const close = closeEditor;
|
||||
closeEditor = null;
|
||||
close?.();
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -110,7 +110,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: 'Файлы в блокчейне',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
back: { onClick: () => navigate('my-blockchain-view') },
|
||||
actions: [
|
||||
{
|
||||
icon: 'plus',
|
||||
|
||||
@@ -125,7 +125,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
avatar: selectedAvatar?.sha256 ? { ar: String(selectedAvatar.ar || ''), sha256Hex: selectedAvatar.sha256 } : null,
|
||||
authorLogin: String(channel?.ownerLogin || state.session.login || '').trim(),
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: title || 'Канал',
|
||||
alt: 'Аватар канала',
|
||||
}));
|
||||
@@ -157,7 +157,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || '').trim();
|
||||
const description = String(root.querySelector('#channel-profile-edit-description')?.value || '').trim();
|
||||
if (Array.from(title).length > 50 || Array.from(description).length > 250) {
|
||||
if (errorEl) errorEl.textContent = 'Название — до 50 символов, описание — до 250.';
|
||||
if (errorEl) errorEl.textContent = 'Название – до 50 символов, описание – до 250.';
|
||||
return;
|
||||
}
|
||||
save.disabled = true;
|
||||
@@ -640,7 +640,7 @@ export function render({ navigate, route, chrome }) {
|
||||
avatar: String(channel?.avaAr || channel?.avaSha256 || '').trim() ? { ar: String(channel.avaAr || '').trim(), sha256Hex: String(channel?.avaSha256 || '').trim() } : null,
|
||||
authorLogin: ownerLogin,
|
||||
size: 'xl',
|
||||
className: 'channel-about-avatar channel-profile-avatar',
|
||||
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||
title: cleanName,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
@@ -648,7 +648,7 @@ export function render({ navigate, route, chrome }) {
|
||||
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
||||
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
||||
size: 'md',
|
||||
className: 'channel-about-owner-avatar-img',
|
||||
className: 'channel-about-owner-avatar-img avatar-plain',
|
||||
alt: '',
|
||||
}));
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+379
-222
@@ -1,7 +1,10 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath } from '../router.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { getPreviousTrackedPath, navigateUp, parseRouteFromPath, toPrettyPath } from '../router.js';
|
||||
import { prefetchThreadPage, threadTotalReplies } from './channel-thread-view.js';
|
||||
import { attachMessageMenu } from '../components/message-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import {
|
||||
@@ -14,12 +17,17 @@ import {
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
dayKey,
|
||||
formatDayLabel,
|
||||
formatPostStamp,
|
||||
formatRelativeTime,
|
||||
formatShortAge,
|
||||
longPressFeel,
|
||||
notifyRepostSoon,
|
||||
REPOSTS_ENABLED,
|
||||
shareOrCopyLink,
|
||||
showToast,
|
||||
softHaptic,
|
||||
@@ -41,12 +49,15 @@ import {
|
||||
extractLoginFromBlockchainName,
|
||||
makeProfileRoute,
|
||||
makeShineMessageRoute,
|
||||
makeShineChannelStreamRoute,
|
||||
makeShineChannelAboutRoute,
|
||||
makeShineChannelDonateRoute,
|
||||
} from '../services/shine-routes.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { dropPageData, readPageData, writePageData } from '../services/page-data-cache.js';
|
||||
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
|
||||
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', hideToolbar: true, shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
const CHANNEL_TYPE_STORIES = 0;
|
||||
const CHANNEL_TYPE_PERSONAL = 100;
|
||||
const MSG_SUBTYPE_TEXT_RATING = 30;
|
||||
@@ -236,13 +247,17 @@ function buildSelectorFromRoute(route, channelId) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadRoute(messageRef, selector) {
|
||||
function buildThreadRoute(post, selector) {
|
||||
const messageRef = post?.messageRef;
|
||||
if (!messageRef || !selector) return '';
|
||||
const ownerLogin = extractLoginFromBlockchainName(selector.ownerBlockchainName);
|
||||
return makeShineMessageRoute({
|
||||
ownerLogin,
|
||||
messageBlockchainName: messageRef.blockchainName,
|
||||
messageBlockNumber: messageRef.blockNumber,
|
||||
messageOrdinal: selector.publicOrdinalUrlsAllowed ? post.localNumber : '',
|
||||
channelName: selector.publicOrdinalUrlsAllowed ? selector.channelName : '',
|
||||
channelOwnerBlockchainName: selector.ownerBlockchainName,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -628,7 +643,7 @@ function createChannelAvatarElement(channel, size = 96) {
|
||||
avatar: (txId || sha256) ? { ar: txId, sha256Hex: sha256 } : null,
|
||||
authorLogin: String(channel?.ownerLogin || '').trim(),
|
||||
size: 'xl',
|
||||
className: 'channel-profile-avatar',
|
||||
className: 'channel-profile-avatar avatar-plain',
|
||||
title,
|
||||
alt: 'Аватар канала',
|
||||
});
|
||||
@@ -1483,6 +1498,9 @@ async function loadFromApi(route, channelId) {
|
||||
const ownerLogin = String(payload.channel?.ownerLogin || '').trim();
|
||||
const channelName = String(payload.channel?.channelName || '').trim();
|
||||
const channelTypeCode = Number(payload.channel?.channelTypeCode ?? 1);
|
||||
// Channel-publication URLs are only unambiguous for public channels, not merged private chats.
|
||||
selector.channelName = String(payload.channel?.channelName || selector.channelName || '').trim();
|
||||
selector.publicOrdinalUrlsAllowed = channelTypeCode !== CHANNEL_TYPE_STORIES && channelTypeCode !== CHANNEL_TYPE_PERSONAL;
|
||||
if (channelTypeCode === CHANNEL_TYPE_STORIES) {
|
||||
throw new Error('Канал stories скрыт из пользовательского интерфейса.');
|
||||
}
|
||||
@@ -1516,16 +1534,9 @@ async function loadFromApi(route, channelId) {
|
||||
}
|
||||
}
|
||||
|
||||
const posts = mergedMessages
|
||||
.map((message, index) => mapApiMessageToPost(message, selector, index + 1))
|
||||
.sort((a, b) => {
|
||||
const byTime = Number(a?.timestampMs || 0) - Number(b?.timestampMs || 0);
|
||||
if (byTime !== 0) return byTime;
|
||||
const aNum = Number(a?.messageRef?.blockNumber || 0);
|
||||
const bNum = Number(b?.messageRef?.blockNumber || 0);
|
||||
return aNum - bNum;
|
||||
})
|
||||
.map((post, index) => ({ ...post, localNumber: index + 1 }));
|
||||
const posts = sortedChannelPublications(
|
||||
mergedMessages.map((message, index) => mapApiMessageToPost(message, selector, index + 1)),
|
||||
).map((post, index) => ({ ...post, localNumber: index + 1 }));
|
||||
const isOwnChannel = ownerLogin.toLowerCase() === currentSessionLogin.toLowerCase();
|
||||
const followedRows = Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : [];
|
||||
const isSubscribed = isAuthorized && followedRows.some((row) => (
|
||||
@@ -1564,27 +1575,12 @@ async function loadFromApi(route, channelId) {
|
||||
}
|
||||
|
||||
function renderLoadError(screen, navigate, message, onRetry) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
card.innerHTML = `
|
||||
<strong>Не удалось загрузить канал</strong>
|
||||
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
|
||||
`;
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
const back = document.createElement('button');
|
||||
back.type = 'button';
|
||||
back.className = 'secondary-btn';
|
||||
back.textContent = 'Назад к каналам';
|
||||
back.addEventListener('click', () => navigate('channels-list'));
|
||||
|
||||
card.append(retry, back);
|
||||
screen.append(card);
|
||||
screen.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить канал',
|
||||
message: message || 'Проверьте подключение и повторите попытку.',
|
||||
onRetry,
|
||||
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(screen, navigate, error) {
|
||||
@@ -1715,7 +1711,7 @@ function openMessageLikesListModal({ navigate, messageRef, initialTab = 'shining
|
||||
<button type="button" class="ui-button" data-like-tab="official">Официальные <span data-like-tab-count="official"></span></button>
|
||||
<button type="button" class="ui-button" data-like-tab="all">Все <span data-like-tab-count="all"></span></button>
|
||||
</div>
|
||||
<div class="channel-likes-modal__status">Загрузка...</div>
|
||||
<div class="channel-likes-modal__status"><div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="Загрузка"></span></div></div>
|
||||
<div class="channel-likes-user-list"></div>
|
||||
</section>
|
||||
`;
|
||||
@@ -1852,7 +1848,7 @@ function openMessageLikePopup({ anchor, post, navigate, onToggleLike }) {
|
||||
close();
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1868,6 +1864,7 @@ function renderPostCard(post, {
|
||||
onRepost,
|
||||
onShare,
|
||||
onEdit,
|
||||
channel = null,
|
||||
isActive = () => true,
|
||||
}) {
|
||||
const versionsTotal = Number(post?.versionsTotal || 1);
|
||||
@@ -1961,9 +1958,19 @@ function renderPostCard(post, {
|
||||
&& !isDiarySelector(selector)
|
||||
&& !!post.messageRef?.blockchainName
|
||||
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
|
||||
// Запись владельца – как пост в Threads: аватар и название канала слева сверху, текст и действия под названием.
|
||||
const threadsLayout = isOwnerPost && Boolean(channel);
|
||||
if (isOwnerPost) {
|
||||
card.classList.add('channel-message-card--owner');
|
||||
authorTile.hidden = true;
|
||||
authorTile.hidden = !threadsLayout;
|
||||
}
|
||||
if (threadsLayout) {
|
||||
card.classList.add('channel-message-card--threads');
|
||||
const channelAvatar = createChannelAvatarElement(channel, 36);
|
||||
channelAvatar.classList.add('channel-message-avatar');
|
||||
avatar.replaceWith(channelAvatar);
|
||||
loginEl.textContent = String(channel.displayTitle || channel.displayName || channel.name || post.authorLogin).trim();
|
||||
if (post.timestampMs) timestamp.textContent = formatShortAge(post.timestampMs);
|
||||
}
|
||||
|
||||
const isDeletedMessage = String(post.body || '').trim().toLowerCase() === 'удалено';
|
||||
@@ -2024,7 +2031,7 @@ function renderPostCard(post, {
|
||||
}
|
||||
const body = document.createElement('p');
|
||||
body.className = 'channel-message-body';
|
||||
body.textContent = parsedBody.text;
|
||||
appendShineMessageLinks(body, parsedBody.text, { navigate, viewMode: 'feed' });
|
||||
card.append(body);
|
||||
}
|
||||
|
||||
@@ -2066,12 +2073,22 @@ function renderPostCard(post, {
|
||||
try {
|
||||
await onToggleLike(post.messageRef, isLiked ? 'unlike' : 'like');
|
||||
} catch (error) {
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||
} finally {
|
||||
if (likeButton.isConnected) likeButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Сервер считает только прямые ответы; полное число по всем уровням берём из обсуждения (кэш или подгрузка).
|
||||
if (Number(post.repliesCount || 0) > 0) {
|
||||
const threadRoute = buildThreadRoute(post, selector);
|
||||
if (threadRoute) {
|
||||
const threadPath = new URL(`/${toPrettyPath(threadRoute)}`, window.location.origin).pathname;
|
||||
card.dataset.threadPath = threadPath;
|
||||
const known = readPageData('thread', threadPath)?.data;
|
||||
if (known) post.repliesCount = threadTotalReplies(known);
|
||||
}
|
||||
}
|
||||
const discussionButton = document.createElement('button');
|
||||
discussionButton.type = 'button';
|
||||
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
|
||||
@@ -2083,15 +2100,33 @@ function renderPostCard(post, {
|
||||
if (post.recentRepliers.length) {
|
||||
const faces = document.createElement('span');
|
||||
faces.className = 'channel-action-faces';
|
||||
post.recentRepliers.forEach((login) => faces.append(renderUserAvatar({ login, size: 'xs', className: 'channel-action-face' })));
|
||||
post.recentRepliers.forEach((login) => faces.append(renderUserAvatar({ login, size: 'xs', className: 'channel-action-face avatar-plain' })));
|
||||
discussionButton.append(faces);
|
||||
}
|
||||
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
|
||||
// По ТЗ: «Обсуждение» открывает запись с обсуждением и сразу редактор ответа (гостю – только обсуждение).
|
||||
const openDiscussion = ({ withEditor = false } = {}) => {
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (!route) return;
|
||||
if (withEditor && state.session.isAuthorized) requestReplyEditorOnOpen(route);
|
||||
navigate(route);
|
||||
};
|
||||
discussionButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
const route = buildThreadRoute(post.messageRef, selector);
|
||||
if (route) navigate(route);
|
||||
openDiscussion({ withEditor: true });
|
||||
});
|
||||
// Нажатие на саму запись открывает её вместе с обсуждением.
|
||||
card.addEventListener('click', (event) => {
|
||||
if (event.target.closest('button, a, input, textarea, .message-attachment-carousel')) return;
|
||||
if (String(window.getSelection?.() || '').trim()) return;
|
||||
openDiscussion();
|
||||
});
|
||||
card.classList.add('is-openable');
|
||||
// Обсуждение начинаем грузить уже при касании – к моменту клика оно обычно готово.
|
||||
card.addEventListener('pointerdown', () => {
|
||||
const route = buildThreadRoute(post, selector);
|
||||
if (route) prefetchThreadPage(`/${toPrettyPath(route)}`);
|
||||
}, { passive: true });
|
||||
|
||||
const replyButton = document.createElement('button');
|
||||
replyButton.type = 'button';
|
||||
@@ -2105,6 +2140,7 @@ function renderPostCard(post, {
|
||||
replyButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
animatePress(event.currentTarget);
|
||||
if (state.session.isAuthorized) { openDiscussion({ withEditor: true }); return; }
|
||||
openReplyModal({
|
||||
onSubmit: async (text) => onReply(post.messageRef, text),
|
||||
isActive,
|
||||
@@ -2130,13 +2166,42 @@ function renderPostCard(post, {
|
||||
shareButton.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
animatePress(event.currentTarget);
|
||||
const route = buildThreadRoute(post.messageRef, selector);
|
||||
const route = buildThreadRoute(post, selector);
|
||||
await onShare(route);
|
||||
});
|
||||
|
||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
|
||||
actions.append(likeButton, shareButton, discussionButton);
|
||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа.
|
||||
// В раскладке Threads: лайк → обсуждение → поделиться, дата и «⋯» в шапке.
|
||||
const repostButton = document.createElement('button');
|
||||
repostButton.type = 'button';
|
||||
repostButton.className = 'ui-button channel-action-item channel-action-repost';
|
||||
repostButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('repost')}</span>
|
||||
<span class="channel-action-label">Репост</span>
|
||||
`;
|
||||
setActionTitle(repostButton, 'Репост');
|
||||
repostButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
|
||||
void onRepost?.(post.messageRef);
|
||||
});
|
||||
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
|
||||
if (threadsLayout) actions.append(likeButton, discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, shareButton, discussionButton);
|
||||
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
|
||||
const streamRoute = makeShineChannelStreamRoute({
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
channelName: selector?.channelName || '',
|
||||
messageOrdinal: post.localNumber,
|
||||
});
|
||||
if (streamRoute) menuItems.unshift({ label: 'Ссылка на сообщение в ленте', iconHtml: iconHtml('share'), action: () => onShare(streamRoute) });
|
||||
}
|
||||
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
|
||||
// Те же действия, что у ответов в обсуждении.
|
||||
menuItems.splice(1, 0, { label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
|
||||
try { await copyTextToClipboard(parsedBody.text); showToast('Текст скопирован'); }
|
||||
catch { showToast('Не удалось скопировать', { kind: 'error' }); }
|
||||
} });
|
||||
if (post.msgSubType === MSG_SUBTYPE_TEXT_REPOST && post.targetRef?.blockchainName && Number.isFinite(post.targetRef?.blockNumber) && post.targetRef?.blockHash) {
|
||||
const originalBtn = document.createElement('button');
|
||||
originalBtn.type = 'button';
|
||||
@@ -2210,12 +2275,12 @@ function renderPostCard(post, {
|
||||
danger: true,
|
||||
})) return;
|
||||
try { await onEdit(post.messageRef, '', { isDelete: true }); }
|
||||
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.')); }
|
||||
catch (error) { if (isActive()) showToast(toUserMessage(error, 'Не удалось удалить сообщение.'), { kind: 'error' }); }
|
||||
} });
|
||||
}
|
||||
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
|
||||
attachMessageMenu(card, headRow, menuItems);
|
||||
if (isOwnerPost) {
|
||||
if (isOwnerPost && !threadsLayout) {
|
||||
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'channel-message-meta';
|
||||
@@ -2252,7 +2317,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
const actionButton = document.createElement('button');
|
||||
actionButton.type = 'button';
|
||||
actionButton.className = 'primary-btn channel-main-action';
|
||||
actionButton.innerHTML = `${iconHtml('bell')}<span>${state.session.isAuthorized ? 'Подписаться' : 'Войти и подписаться'}</span>`;
|
||||
actionButton.innerHTML = `${iconHtml('bell')}<span>${state.session.isAuthorized ? 'Подписаться' : 'Войти / зарегистрироваться'}</span>`;
|
||||
|
||||
const addMessageButton = document.createElement('button');
|
||||
addMessageButton.type = 'button';
|
||||
@@ -2323,6 +2388,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
onRepost: handlers.onRepost,
|
||||
onShare: handlers.onShare,
|
||||
onEdit: handlers.onEdit,
|
||||
channel: channelData.channel,
|
||||
isActive: handlers.isActive,
|
||||
});
|
||||
const key = messageRefKey(item.post.messageRef);
|
||||
@@ -2368,6 +2434,13 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
screen.append(feed);
|
||||
}
|
||||
|
||||
const requestedOrdinal = Number(handlers.scrollToMessageOrdinal);
|
||||
if (Number.isSafeInteger(requestedOrdinal) && requestedOrdinal > 0) {
|
||||
const card = [...screen.querySelectorAll('.channel-message-card[data-local-number]')]
|
||||
.find((el) => Number(el.dataset.localNumber) === requestedOrdinal);
|
||||
if (card) pendingScrollByRoute.set(routeKey, card.dataset.messageKey);
|
||||
else showStatus(`Публикация №${requestedOrdinal} не найдена в канале.`);
|
||||
}
|
||||
const hasPendingScrollTarget = pendingScrollByRoute.has(routeKey);
|
||||
const restorePosition = handlers.restorePosition;
|
||||
const pendingScrollTimer = Number.isFinite(restorePosition) && !hasPendingScrollTarget ? 0 : applyPendingScroll(screen, routeKey, channelData.isOwnChannel || channelData.isDiary || unreadCount === 0);
|
||||
@@ -2432,22 +2505,73 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
||||
};
|
||||
}
|
||||
|
||||
// Полные счётчики ответов для видимых записей: обсуждения подгружаются по одному (они же потом открываются сразу).
|
||||
function watchReplyTotals(screen) {
|
||||
if (!('IntersectionObserver' in window)) return () => {};
|
||||
let stopped = false;
|
||||
const queue = [];
|
||||
let running = false;
|
||||
const setCount = (card, total) => {
|
||||
card.querySelectorAll('.channel-action-discussion .channel-action-counter, .channel-action-reply .channel-action-counter')
|
||||
.forEach((counter) => { counter.textContent = total ? String(total) : ''; });
|
||||
};
|
||||
const pump = async () => {
|
||||
if (running) return;
|
||||
running = true;
|
||||
while (!stopped && queue.length) {
|
||||
const card = queue.shift();
|
||||
try {
|
||||
const data = await prefetchThreadPage(card.dataset.threadPath);
|
||||
if (!stopped && data && card.isConnected) setCount(card, threadTotalReplies(data));
|
||||
} catch {
|
||||
// Не удалось – остаётся серверный счётчик прямых ответов.
|
||||
}
|
||||
}
|
||||
running = false;
|
||||
};
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
observer.unobserve(entry.target);
|
||||
queue.push(entry.target);
|
||||
});
|
||||
void pump();
|
||||
}, { rootMargin: '200px 0px' });
|
||||
screen.querySelectorAll('.channel-message-card[data-thread-path]').forEach((card) => observer.observe(card));
|
||||
return () => {
|
||||
stopped = true;
|
||||
observer.disconnect();
|
||||
};
|
||||
}
|
||||
|
||||
// Фоновая подгрузка канала в кэш, чтобы он открывался сразу (вызывается из обхода ленты каналов).
|
||||
export async function prefetchChannelPage(path) {
|
||||
const pathname = new URL(path, window.location.origin).pathname;
|
||||
const route = parseRouteFromPath(pathname);
|
||||
if (route.pageId !== 'channel-view') return false;
|
||||
const data = await loadFromApi(route, route.params.channelId || '');
|
||||
writePageData('channel', pathname, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Место под заглушку занимаем сразу, а сами строки рисуем, только если загрузка затянулась.
|
||||
function renderSkeleton(screen) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'stack';
|
||||
wrap.append(createSkeletonCard(), createSkeletonCard(), createSkeletonCard());
|
||||
screen.append(wrap);
|
||||
window.setTimeout(() => { if (wrap.isConnected) wrap.append(createSkeletonRows('post', 3)); }, SKELETON_DELAY_MS);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const channelId = route.params.channelId || '';
|
||||
const scrollToMessageOrdinal = route.params.scrollToMessageOrdinal || '';
|
||||
const routeSelector = buildSelectorFromRoute(route, channelId);
|
||||
const routeKey = `${routeSelector?.ownerBlockchainName || ''}:${routeSelector?.channelRootBlockNumber || ''}:${routeSelector?.channelRootBlockHash || ''}`;
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack channels-screen channels-screen--channel';
|
||||
const positionKey = `${state.session.login}:channel:${routeKey}`;
|
||||
// A deep link must take precedence over a saved scroll position.
|
||||
|
||||
let disposed = false;
|
||||
let refreshSeq = 0;
|
||||
@@ -2480,16 +2604,16 @@ export function render({ navigate, route, chrome }) {
|
||||
const channelHeaderButton = document.createElement('button');
|
||||
channelHeaderButton.type = 'button';
|
||||
channelHeaderButton.className = 'topbar-identity channel-header-route-btn';
|
||||
channelHeaderButton.innerHTML = '<span class="topbar-identity__text"><span class="topbar-identity__title">Канал</span><span class="topbar-identity__sub">Загрузка…</span></span>';
|
||||
channelHeaderButton.innerHTML = '<span class="topbar-identity__text"><span class="topbar-identity__title">Канал</span><span class="topbar-identity__sub"> </span></span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
|
||||
const header = createTopBar({
|
||||
center: channelHeaderButton,
|
||||
back: { onClick: () => navigate('channels-list') },
|
||||
back: state.session.isAuthorized ? { onClick: () => navigateUp((route) => route?.pageId === 'channels-list', 'channels-list') } : null,
|
||||
className: 'channel-view-topbar topbar--identity',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Действия канала',
|
||||
ariaLabel: 'Открыть меню канала',
|
||||
className: 'channel-header-more-btn',
|
||||
@@ -2515,7 +2639,7 @@ export function render({ navigate, route, chrome }) {
|
||||
iconHtml: iconHtml('list'),
|
||||
action: () => {
|
||||
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
|
||||
else showToast('В этом канале пока нет оглавления');
|
||||
else showToast('В этом канале пока нет оглавления', { kind: 'info' });
|
||||
},
|
||||
});
|
||||
if (!apiData?.isOwnChannel) {
|
||||
@@ -2889,6 +3013,168 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
// Рисует канал по готовым данным: и из кэша при возврате, и после загрузки с сервера.
|
||||
const paint = (apiData, restorePosition) => {
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте', { kind: 'error' });
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление', { kind: 'error' });
|
||||
}
|
||||
};
|
||||
}
|
||||
clearContent();
|
||||
const stopSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
scrollToMessageOrdinal,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
const stopReplyTotals = watchReplyTotals(screen);
|
||||
cleanupSeenTracking = () => {
|
||||
if (typeof stopSeenTracking === 'function') stopSeenTracking();
|
||||
stopReplyTotals();
|
||||
};
|
||||
};
|
||||
|
||||
refresh = async () => {
|
||||
if (disposed) return;
|
||||
const seq = ++refreshSeq;
|
||||
@@ -2901,181 +3187,52 @@ export function render({ navigate, route, chrome }) {
|
||||
? getChannelScrollRoot()?.scrollTop
|
||||
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||
if (!hadContent) clearContent();
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
showStatus('');
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
const cacheKey = window.location.pathname;
|
||||
// При возврате на канал сразу показываем прошлую загрузку, без заглушки и пустого кадра.
|
||||
const cached = hadContent ? null : readPageData('channel', cacheKey);
|
||||
let shown = hadContent;
|
||||
if (cached) {
|
||||
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
|
||||
await Promise.resolve();
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
try {
|
||||
paint(cached.data, restorePosition);
|
||||
shown = true;
|
||||
} catch (error) {
|
||||
dropPageData('channel', cacheKey);
|
||||
clearContent();
|
||||
}
|
||||
}
|
||||
|
||||
const skeleton = hadContent ? null : renderSkeleton(screen);
|
||||
if (!shown) {
|
||||
activeChannelData = null;
|
||||
activeOpenEntrypointHistory = null;
|
||||
activeSelector = null;
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner"> </span>';
|
||||
channelHeaderButton.disabled = true;
|
||||
channelHeaderButton.onclick = null;
|
||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
||||
if (channelEntrypointButton) {
|
||||
channelEntrypointButton.disabled = true;
|
||||
channelEntrypointButton.hidden = true;
|
||||
channelEntrypointButton.onclick = null;
|
||||
}
|
||||
}
|
||||
const skeleton = shown ? null : renderSkeleton(screen);
|
||||
|
||||
try {
|
||||
const apiData = await loadFromApi(route, channelId);
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
activeSelector = apiData?.selector || null;
|
||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
||||
const openEntrypointHistory = () => {
|
||||
openEntrypointHistoryModal({
|
||||
channelTitle: titleLabel,
|
||||
posts: apiData?.posts,
|
||||
onSelect: (post) => {
|
||||
if (!flashAndScrollToMessage(post?.messageRef)) {
|
||||
showToast('Не удалось найти запись оглавления в ленте');
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
activeOpenEntrypointHistory = openEntrypointHistory;
|
||||
if (channelHeaderButton) {
|
||||
// Короткий адрес канала и число подписчиков; владелец и полный путь — в «О канале»
|
||||
const slug = String(apiData?.channel?.name || '').trim();
|
||||
const subs = Number(apiData?.channel?.subscribersCount || 0);
|
||||
channelHeaderButton.replaceChildren();
|
||||
const text = document.createElement('span');
|
||||
text.className = 'topbar-identity__text';
|
||||
const titleNode = document.createElement('span');
|
||||
titleNode.className = 'topbar-identity__title';
|
||||
titleNode.textContent = titleLabel;
|
||||
const subNode = document.createElement('span');
|
||||
subNode.className = 'topbar-identity__sub';
|
||||
subNode.textContent = apiData?.isDiary ? 'Только вам' : [slug ? `@${slug}` : '', subs ? String(subs) : ''].filter(Boolean).join(' · ');
|
||||
text.append(titleNode, subNode);
|
||||
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
|
||||
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
|
||||
channelHeaderButton.disabled = false;
|
||||
channelHeaderButton.onclick = (event) => {
|
||||
animatePress(event.currentTarget);
|
||||
const aboutRoute = makeShineChannelAboutRoute({
|
||||
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
|
||||
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
|
||||
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
|
||||
});
|
||||
if (aboutRoute) navigate(aboutRoute);
|
||||
};
|
||||
}
|
||||
activeChannelData = apiData;
|
||||
if (channelMoreButton) {
|
||||
channelMoreButton.disabled = false;
|
||||
}
|
||||
if (channelEntrypointButton) {
|
||||
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
|
||||
channelEntrypointButton.hidden = !canShowEntrypointButton;
|
||||
channelEntrypointButton.disabled = !canShowEntrypointButton;
|
||||
channelEntrypointButton.onclick = () => {
|
||||
const latestEntrypoint = entrypointPosts[0];
|
||||
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
|
||||
showToast('Не удалось найти актуальное оглавление');
|
||||
}
|
||||
};
|
||||
}
|
||||
const signature = writePageData('channel', cacheKey, apiData);
|
||||
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
|
||||
if (cached && cached.signature === signature) return;
|
||||
skeleton?.remove();
|
||||
clearContent();
|
||||
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
|
||||
chrome,
|
||||
restorePosition,
|
||||
showStatus,
|
||||
isActive: () => !disposed,
|
||||
onAddMessage: activeAddMessage = async () => {
|
||||
if (apiData?.channel?.deleted) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Восстановить канал?',
|
||||
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
|
||||
confirmLabel: 'Восстановить и написать',
|
||||
});
|
||||
if (!confirmed || disposed) return;
|
||||
}
|
||||
openAddMessageModal({
|
||||
channelName: apiData?.channel?.name || '',
|
||||
channelTitle: apiData?.channel?.displayTitle || '',
|
||||
navigate,
|
||||
isActive: () => !disposed,
|
||||
onSubmit: async ({ text: bodyText, msgSubType }) => {
|
||||
try {
|
||||
await onAddPost(bodyText, msgSubType);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
onToggleLike: async (messageRef, action) => {
|
||||
try {
|
||||
await onToggleLike(messageRef, action);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
|
||||
}
|
||||
},
|
||||
onReply: async (messageRef, text) => {
|
||||
try {
|
||||
await onReply(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
|
||||
}
|
||||
},
|
||||
onRating: async (messageRef, text) => {
|
||||
try {
|
||||
await onRating(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
|
||||
}
|
||||
},
|
||||
onStatusAction: async (post) => {
|
||||
try {
|
||||
await onStatusAction(post);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
|
||||
}
|
||||
},
|
||||
onOpenEntrypointMenu: () => {
|
||||
openEntrypointMenuModal({
|
||||
onShowHistory: openEntrypointHistory,
|
||||
});
|
||||
},
|
||||
onRepost: async (messageRef) => {
|
||||
try {
|
||||
await onRepost(messageRef);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
|
||||
}
|
||||
},
|
||||
onAddPost: async (bodyText) => {
|
||||
try {
|
||||
await onAddPost(bodyText);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
|
||||
}
|
||||
},
|
||||
onShare: onShare,
|
||||
onEdit: async (messageRef, text) => {
|
||||
try {
|
||||
await onEditPost(messageRef, text);
|
||||
showStatus('');
|
||||
} catch (error) {
|
||||
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
|
||||
}
|
||||
},
|
||||
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
|
||||
});
|
||||
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
|
||||
} catch (error) {
|
||||
if (disposed || seq !== refreshSeq) return;
|
||||
skeleton?.remove();
|
||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
|
||||
if (isChannelsDemoMode()) {
|
||||
renderDemoFallback(screen, navigate, error);
|
||||
return;
|
||||
|
||||
@@ -5,7 +5,9 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||
import {
|
||||
animatePress,
|
||||
createSkeletonCard,
|
||||
createLoadErrorCard,
|
||||
createSkeletonRows,
|
||||
SKELETON_DELAY_MS,
|
||||
formatListTime,
|
||||
readChannelNotificationsState,
|
||||
showToast,
|
||||
@@ -20,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { pageDataAge } from '../services/page-data-cache.js';
|
||||
import { toPrettyPath } from '../router.js';
|
||||
import { prefetchChannelPage } from './channel-view.js';
|
||||
|
||||
export const pageMeta = { id: 'channels-list', title: 'Каналы', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
|
||||
|
||||
@@ -502,187 +507,6 @@ function openSimpleSubscribeModal({ kind, kindLabel, submitLabel, unfollow = fal
|
||||
if (inputEl) inputEl.focus();
|
||||
}
|
||||
|
||||
function openChannelFinderModal({ navigate }) {
|
||||
const root = document.getElementById('modal-root');
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="channels-find-modal">
|
||||
<div class="modal-card stack" style="max-width: min(96vw, 760px); width: min(96vw, 760px);">
|
||||
<h3 class="modal-title">Поиск каналов</h3>
|
||||
<p class="meta-muted">Введите логин (или начало логина), затем выберите пользователя и канал.</p>
|
||||
<input id="channels-find-input" class="input" placeholder="Например: aidar" autocomplete="off" />
|
||||
<div id="channels-find-suggest" class="channels-search-suggest" style="display:none"></div>
|
||||
<div id="channels-find-list" class="channels-search-suggest" style="display:none"></div>
|
||||
<div id="channels-find-error" class="meta-muted inline-error"></div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="primary-btn" id="channels-find-run" type="button">Найти</button>
|
||||
<button class="secondary-btn" id="channels-find-close" type="button">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const inputEl = root.querySelector('#channels-find-input');
|
||||
const suggestEl = root.querySelector('#channels-find-suggest');
|
||||
const channelsEl = root.querySelector('#channels-find-list');
|
||||
const errorEl = root.querySelector('#channels-find-error');
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
|
||||
const renderButtons = (container, values, onPick) => {
|
||||
container.innerHTML = '';
|
||||
if (!values.length) {
|
||||
container.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
container.style.display = '';
|
||||
values.forEach((value) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'ui-button channel-search-item';
|
||||
btn.textContent = value.label;
|
||||
btn.addEventListener('click', () => onPick(value));
|
||||
container.append(btn);
|
||||
});
|
||||
};
|
||||
|
||||
const renderChannelRows = (values) => {
|
||||
channelsEl.innerHTML = '';
|
||||
if (!values.length) {
|
||||
channelsEl.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
channelsEl.style.display = '';
|
||||
values.forEach((item) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'channel-search-item';
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.textContent = item.label;
|
||||
|
||||
const openBtn = document.createElement('button');
|
||||
openBtn.type = 'button';
|
||||
openBtn.className = 'secondary-btn small-btn';
|
||||
openBtn.textContent = 'Просмотреть';
|
||||
openBtn.addEventListener('click', () => {
|
||||
close();
|
||||
const route = makeShineChannelRoute({
|
||||
ownerLogin: String(item.ownerLogin || '').trim(),
|
||||
ownerBlockchainName: String(item.ownerBlockchainName || '').trim(),
|
||||
channelName: String(item.channelName || '').trim(),
|
||||
});
|
||||
if (route) navigate(route);
|
||||
});
|
||||
|
||||
row.style.display = 'flex';
|
||||
row.style.alignItems = 'center';
|
||||
row.style.justifyContent = 'space-between';
|
||||
row.style.gap = '8px';
|
||||
row.append(label, openBtn);
|
||||
channelsEl.append(row);
|
||||
});
|
||||
};
|
||||
|
||||
const loadChannelsForLogin = async (login, filterChannel = '') => {
|
||||
const ownerLogin = normalizeLoginInput(login);
|
||||
if (!ownerLogin) return;
|
||||
const feed = await authService.listSubscriptionsFeed(ownerLogin, 1000);
|
||||
const rows = Array.isArray(feed?.ownedChannels) ? feed.ownedChannels.filter(isVisibleChannelSummary) : [];
|
||||
const needle = String(filterChannel || '').trim().toLowerCase();
|
||||
const channels = rows
|
||||
.map((item) => ({
|
||||
ownerBlockchainName: String(item?.channel?.ownerBlockchainName || '').trim(),
|
||||
channelName: String(item?.channel?.channelName || '').trim(),
|
||||
}))
|
||||
.filter((item) => !!item.channelName)
|
||||
.filter((item) => !needle || item.channelName.toLowerCase().includes(needle))
|
||||
.slice(0, 200)
|
||||
.map((item) => ({
|
||||
label: `${ownerLogin} / ${item.channelName}`,
|
||||
ownerLogin,
|
||||
ownerBlockchainName: item.ownerBlockchainName,
|
||||
channelName: item.channelName,
|
||||
}));
|
||||
renderChannelRows(channels);
|
||||
if (!channels.length) {
|
||||
errorEl.textContent = filterChannel
|
||||
? 'Каналы с таким фильтром не найдены.'
|
||||
: `У пользователя "${ownerLogin}" пока нет доступных каналов.`;
|
||||
} else {
|
||||
errorEl.textContent = '';
|
||||
}
|
||||
};
|
||||
|
||||
const runSearch = async () => {
|
||||
const raw = String(inputEl?.value || '').trim();
|
||||
errorEl.textContent = '';
|
||||
if (!raw) {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
channelsEl.style.display = 'none';
|
||||
channelsEl.innerHTML = '';
|
||||
errorEl.textContent = 'Введите логин или начало логина.';
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = raw.split('/');
|
||||
const loginPrefix = normalizeLoginInput(parts[0] || '');
|
||||
const channelFilter = String(parts[1] || '').trim();
|
||||
|
||||
try {
|
||||
if (raw.includes('/')) {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
await loadChannelsForLogin(loginPrefix, channelFilter);
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginPrefix.length < 1) {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
channelsEl.style.display = 'none';
|
||||
channelsEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const logins = await authService.searchUsers(loginPrefix);
|
||||
const rows = Array.isArray(logins) ? logins : [];
|
||||
if (!rows.length) {
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
channelsEl.style.display = 'none';
|
||||
channelsEl.innerHTML = '';
|
||||
errorEl.textContent = `Логины, начинающиеся на "${loginPrefix}", не найдены.`;
|
||||
return;
|
||||
}
|
||||
const items = (Array.isArray(logins) ? logins : []).slice(0, 15).map((login) => ({
|
||||
label: login,
|
||||
login,
|
||||
}));
|
||||
errorEl.textContent = '';
|
||||
renderButtons(suggestEl, items, async (item) => {
|
||||
inputEl.value = `${item.login}/`;
|
||||
suggestEl.style.display = 'none';
|
||||
suggestEl.innerHTML = '';
|
||||
await loadChannelsForLogin(item.login, '');
|
||||
});
|
||||
} catch (error) {
|
||||
errorEl.textContent = toUserMessage(error, 'Не удалось выполнить поиск.');
|
||||
}
|
||||
};
|
||||
|
||||
const refresh = createDebounced(runSearch, 220);
|
||||
|
||||
root.querySelector('#channels-find-close')?.addEventListener('click', close);
|
||||
root.querySelector('#channels-find-run')?.addEventListener('click', () => {
|
||||
void runSearch();
|
||||
});
|
||||
inputEl?.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
void runSearch();
|
||||
});
|
||||
inputEl?.addEventListener('input', refresh);
|
||||
if (inputEl) inputEl.focus();
|
||||
}
|
||||
|
||||
function mapMockGroups() {
|
||||
const mapRow = (channel) => ({
|
||||
@@ -891,6 +715,35 @@ function mapApiFeed(feed, notificationsState, diaryPayload = null) {
|
||||
return { ownChannels, followedUserChannels, subscribedChannels, index };
|
||||
}
|
||||
|
||||
const PREFETCH_CHANNELS = 6;
|
||||
const PREFETCH_FRESH_MS = 50_000;
|
||||
|
||||
// Фоновое обновление ленты каналов и самых активных каналов: экран «Каналы» и сами каналы
|
||||
// открываются сразу из памяти. Запросы идут по одному, чтобы не нагружать сервер.
|
||||
export async function refreshChannelsInBackground({ isCurrent = () => true } = {}) {
|
||||
if (!state.session.isAuthorized || state.session.isLocalDemo) return;
|
||||
const login = state.session.login;
|
||||
const feed = await authService.listSubscriptionsFeed(login, 200);
|
||||
if (!isCurrent() || state.session.login !== login) return;
|
||||
const groups = mapApiFeed(feed, {}, null);
|
||||
setChannelsFeed(feed, groups.index);
|
||||
const routes = toListModel(groups)
|
||||
.filter((row) => row.route)
|
||||
.sort((a, b) => Number(b.lastMessageAt || 0) - Number(a.lastMessageAt || 0))
|
||||
.slice(0, PREFETCH_CHANNELS)
|
||||
.map((row) => `/${toPrettyPath(row.route)}`);
|
||||
for (const route of routes) {
|
||||
if (!isCurrent() || state.session.login !== login) return;
|
||||
const pathname = new URL(route, window.location.origin).pathname;
|
||||
if (pathname === window.location.pathname || pageDataAge('channel', pathname) < PREFETCH_FRESH_MS) continue;
|
||||
try {
|
||||
await prefetchChannelPage(pathname);
|
||||
} catch {
|
||||
// Фоновая подгрузка не должна мешать: канал загрузится обычным путём при открытии.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toListModel(groups) {
|
||||
return [
|
||||
...(groups.ownChannels || []),
|
||||
@@ -906,46 +759,27 @@ function renderEmptyState(listState, navigate) {
|
||||
heading.textContent = listState.query ? 'Ничего не найдено' : listState.viewMode === CHANNELS_VIEW_DELETED ? 'Удалённых каналов нет' : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? 'Пока нет подписок' : listState.viewMode === CHANNELS_VIEW_OWNED ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? 'Здесь появятся только ваши каналы, помеченные как удалённые.' : state.session.isAuthorized ? 'Найдите канал по имени автора или создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
text.textContent = listState.viewMode === CHANNELS_VIEW_DELETED ? 'Здесь появятся только ваши каналы, помеченные как удалённые.' : state.session.isAuthorized ? 'Найдите канал по названию, адресу или автору – либо создайте свой.' : 'Войдите, чтобы видеть свои каналы и подписки.';
|
||||
const action = document.createElement('button');
|
||||
action.type = 'button';
|
||||
action.className = 'primary-btn';
|
||||
action.textContent = state.session.isAuthorized ? 'Найти по @автору' : 'Войти';
|
||||
action.addEventListener('click', () => state.session.isAuthorized ? openChannelFinderModal({ navigate }) : navigate('login-view'));
|
||||
action.textContent = 'Найти каналы';
|
||||
action.addEventListener('click', () => navigate('search-view'));
|
||||
wrap.append(heading, text, action);
|
||||
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function renderSkeletonList(container, count = 4) {
|
||||
container.innerHTML = '';
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack';
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
list.append(createSkeletonCard());
|
||||
}
|
||||
container.append(list);
|
||||
container.replaceChildren(createSkeletonRows('list', count));
|
||||
}
|
||||
|
||||
function renderErrorState(container, error, onRetry) {
|
||||
const errCard = document.createElement('div');
|
||||
errCard.className = 'card stack channels-status';
|
||||
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = 'Не удалось загрузить каналы';
|
||||
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
details.textContent = toUserMessage(error, 'Проверьте подключение к серверу и повторите попытку.');
|
||||
|
||||
const retry = document.createElement('button');
|
||||
retry.className = 'primary-btn';
|
||||
retry.type = 'button';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
|
||||
errCard.append(title, details, retry);
|
||||
container.append(errCard);
|
||||
container.append(createLoadErrorCard({
|
||||
title: 'Не удалось загрузить каналы',
|
||||
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||
onRetry,
|
||||
}));
|
||||
}
|
||||
|
||||
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
||||
@@ -1069,7 +903,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack channels-groups channels-list-body-fade';
|
||||
list.className = 'stack channels-groups';
|
||||
|
||||
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
|
||||
|
||||
@@ -1115,7 +949,24 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
||||
async function loadFeedAndRender({ screen, listState, contentEl, navigate, silent = false }) {
|
||||
if (listState.disposed) return;
|
||||
const seq = ++listState.loadSeq;
|
||||
if (!silent) renderSkeletonList(contentEl, 5);
|
||||
// Уже загруженный список показываем сразу и тихо обновляем; заглушка – только при долгой первой загрузке.
|
||||
if (!silent && state.session.isAuthorized && state.channelsFeed && listState.viewMode !== CHANNELS_VIEW_DELETED) {
|
||||
listState.channels = toListModel(mapApiFeed(state.channelsFeed, listState.notificationsState, null));
|
||||
renderListContent({
|
||||
screen,
|
||||
container: contentEl,
|
||||
listState,
|
||||
navigate,
|
||||
refreshFeed: async () => loadFeedAndRender({ screen, listState, contentEl, navigate }),
|
||||
});
|
||||
silent = true;
|
||||
}
|
||||
if (!silent) {
|
||||
window.setTimeout(() => {
|
||||
if (!listState.disposed && seq === listState.loadSeq && !contentEl.hasChildNodes()) renderSkeletonList(contentEl, 5);
|
||||
}, SKELETON_DELAY_MS);
|
||||
contentEl.replaceChildren();
|
||||
}
|
||||
|
||||
if (!state.session.isAuthorized) {
|
||||
setChannelsFeed(null, {});
|
||||
@@ -1226,7 +1077,7 @@ export function render({ navigate, route, chrome }) {
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'moreVertical',
|
||||
iconNode: createOverflowDots(),
|
||||
title: 'Меню каналов',
|
||||
ariaLabel: 'Открыть меню каналов',
|
||||
className: 'channels-menu-btn',
|
||||
@@ -1258,8 +1109,8 @@ export function render({ navigate, route, chrome }) {
|
||||
const serverSearchButton = document.createElement('button');
|
||||
serverSearchButton.type = 'button';
|
||||
serverSearchButton.className = 'text-btn channels-server-search';
|
||||
serverSearchButton.textContent = 'По @автору';
|
||||
serverSearchButton.addEventListener('click', () => openChannelFinderModal({ navigate }));
|
||||
serverSearchButton.textContent = 'Поиск в SHiNE';
|
||||
serverSearchButton.addEventListener('click', () => navigate('search-view'));
|
||||
searchWrap.append(searchInput, serverSearchButton);
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// «Медиа и файлы» личной переписки: сетка фото и видео и список документов по месяцам.
|
||||
// История догружается с сервера целиком; превью расшифровываются, только когда плитка видна.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { openMediaViewer } from '../components/media-viewer.js';
|
||||
import { createDmFileAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js';
|
||||
import { getAttachmentKind } from '../services/attachment-format.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { loadFullDmHistory, resolveMessageTimeMs } from '../services/dm-history.js';
|
||||
import { formatClockTime, formatDayLabel } from '../services/channels-ux.js';
|
||||
import { getChatMessages, getRememberedDmPeer, normalizeDmChatId } from '../state.js';
|
||||
import { navigateUp } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'chat-media-view', title: 'Медиа и файлы' };
|
||||
|
||||
const monthTitle = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' });
|
||||
|
||||
// Все вложения переписки, от новых к старым.
|
||||
function collectAttachments(chatId) {
|
||||
const media = [];
|
||||
const files = [];
|
||||
for (const msg of getChatMessages(chatId)) {
|
||||
if (msg?.deleted) continue;
|
||||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||||
const list = Array.isArray(parsed.fileAttachments) ? parsed.fileAttachments : (parsed.fileAttachment ? [parsed.fileAttachment] : []);
|
||||
for (const attachment of list) {
|
||||
if (attachment?.kind === 'voice') continue;
|
||||
const entry = { attachment, timeMs: resolveMessageTimeMs(msg), from: msg?.from };
|
||||
(isDmInlineMedia(attachment) ? media : files).push(entry);
|
||||
}
|
||||
}
|
||||
const newestFirst = (a, b) => b.timeMs - a.timeMs;
|
||||
return { media: media.sort(newestFirst), files: files.sort(newestFirst) };
|
||||
}
|
||||
|
||||
function groupByMonth(entries) {
|
||||
const groups = [];
|
||||
for (const entry of entries) {
|
||||
const raw = entry.timeMs ? monthTitle.format(new Date(entry.timeMs)) : 'Без даты';
|
||||
const label = raw.charAt(0).toUpperCase() + raw.slice(1);
|
||||
const last = groups[groups.length - 1];
|
||||
if (last?.label === label) last.items.push(entry);
|
||||
else groups.push({ label, items: [entry] });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const chatId = normalizeDmChatId(route?.params?.chatId);
|
||||
const peer = getRememberedDmPeer(chatId);
|
||||
const peerName = [peer?.firstName, peer?.lastName].map((x) => String(x || '').trim()).filter(Boolean).join(' ') || chatId;
|
||||
const chatPath = `chat/${encodeURIComponent(chatId)}`;
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack chat-media-screen';
|
||||
let disposed = false;
|
||||
let activeTab = 'media';
|
||||
let loading = true;
|
||||
let loadFailed = false;
|
||||
const objectUrls = new Set();
|
||||
const tileUrls = new Map(); // id файла → url для просмотрщика
|
||||
const fileKey = (attachment) => String(attachment?.id || attachment?.url || '');
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Медиа и файлы',
|
||||
back: {
|
||||
onClick: () => navigateUp((r) => r.pageId === 'chat-view' && normalizeDmChatId(r.params?.chatId) === chatId, chatPath),
|
||||
},
|
||||
}));
|
||||
|
||||
const subtitle = document.createElement('p');
|
||||
subtitle.className = 'meta-muted chat-media-peer';
|
||||
subtitle.textContent = `Переписка с ${peerName}`;
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--auto tabs--dense chat-media-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Что показать');
|
||||
const tabButtons = new Map();
|
||||
for (const [value, label] of [['media', 'Медиа'], ['files', 'Файлы']]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.tab = value;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.addEventListener('click', () => {
|
||||
if (activeTab === value) return;
|
||||
activeTab = value;
|
||||
renderBody();
|
||||
});
|
||||
tabButtons.set(value, { button, label });
|
||||
tabs.append(button);
|
||||
}
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'chat-media-status';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack chat-media-body';
|
||||
screen.append(subtitle, tabs, status, body);
|
||||
|
||||
const thumbObserver = typeof IntersectionObserver === 'function'
|
||||
? new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isIntersecting) continue;
|
||||
thumbObserver.unobserve(entry.target);
|
||||
entry.target.__loadThumb?.();
|
||||
}
|
||||
}, { rootMargin: '300px 0px' })
|
||||
: null;
|
||||
|
||||
const createTile = (entry, openAt) => {
|
||||
const { attachment } = entry;
|
||||
const kind = getAttachmentKind(attachment);
|
||||
const tile = document.createElement('button');
|
||||
tile.type = 'button';
|
||||
tile.className = `chat-media-tile is-loading${kind === 'video' ? ' chat-media-tile--video' : ''}`;
|
||||
tile.setAttribute('aria-label', `${kind === 'video' ? 'Видео' : 'Фото'} ${attachment.name || ''}, ${formatDayLabel(entry.timeMs)}`);
|
||||
tile.__loadThumb = () => {
|
||||
resolveDmMediaUrl(attachment).then(({ url }) => {
|
||||
objectUrls.add(url);
|
||||
if (disposed) return;
|
||||
tileUrls.set(fileKey(attachment), url);
|
||||
const media = document.createElement(kind === 'video' ? 'video' : 'img');
|
||||
media.className = 'chat-media-tile__media';
|
||||
if (kind === 'video') {
|
||||
media.muted = true;
|
||||
media.preload = 'metadata';
|
||||
media.playsInline = true;
|
||||
// Кадр чуть позже начала: первый часто чёрный.
|
||||
media.src = `${url}#t=0.1`;
|
||||
} else {
|
||||
media.alt = '';
|
||||
media.decoding = 'async';
|
||||
media.src = url;
|
||||
}
|
||||
tile.prepend(media);
|
||||
tile.classList.remove('is-loading');
|
||||
}).catch(() => {
|
||||
if (!disposed) tile.classList.replace('is-loading', 'is-failed');
|
||||
});
|
||||
};
|
||||
if (kind === 'video') {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'chat-media-tile__badge';
|
||||
badge.innerHTML = iconHtml('video');
|
||||
tile.append(badge);
|
||||
}
|
||||
tile.addEventListener('click', () => openAt(attachment));
|
||||
if (thumbObserver) thumbObserver.observe(tile);
|
||||
else tile.__loadThumb();
|
||||
return tile;
|
||||
};
|
||||
|
||||
const openViewerAt = async (allMedia, attachment) => {
|
||||
if (!tileUrls.has(fileKey(attachment))) {
|
||||
try {
|
||||
const { url } = await resolveDmMediaUrl(attachment);
|
||||
objectUrls.add(url);
|
||||
tileUrls.set(fileKey(attachment), url);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (disposed) return;
|
||||
// В просмотрщик – уже расшифрованные: остальные догрузятся, когда до них долистают в сетке.
|
||||
const entries = allMedia
|
||||
.filter((entry) => tileUrls.has(fileKey(entry.attachment)))
|
||||
.map((entry) => ({ kind: getAttachmentKind(entry.attachment), url: tileUrls.get(fileKey(entry.attachment)), name: entry.attachment.name, attachment: entry.attachment }));
|
||||
openMediaViewer(entries, Math.max(0, entries.findIndex((entry) => fileKey(entry.attachment) === fileKey(attachment))));
|
||||
};
|
||||
|
||||
const renderEmpty = (text) => {
|
||||
const empty = document.createElement('p');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = text;
|
||||
body.append(empty);
|
||||
};
|
||||
|
||||
function renderBody() {
|
||||
if (disposed) return;
|
||||
const { media, files } = collectAttachments(chatId);
|
||||
for (const [value, { button, label }] of tabButtons) {
|
||||
const count = value === 'media' ? media.length : files.length;
|
||||
button.textContent = count ? `${label} · ${count}` : label;
|
||||
button.setAttribute('aria-checked', String(value === activeTab));
|
||||
}
|
||||
status.hidden = !loading && !loadFailed;
|
||||
status.classList.toggle('is-error', loadFailed);
|
||||
status.innerHTML = loadFailed
|
||||
? 'Не удалось загрузить всю историю – показано то, что уже есть на устройстве.'
|
||||
: '<span class="dm-history-loader__spinner" aria-hidden="true"></span><span>Загружаю историю переписки…</span>';
|
||||
thumbObserver?.disconnect();
|
||||
body.replaceChildren();
|
||||
|
||||
const entries = activeTab === 'media' ? media : files;
|
||||
if (!entries.length) {
|
||||
if (!loading) renderEmpty(activeTab === 'media' ? 'В этой переписке пока нет фото и видео.' : 'В этой переписке пока нет файлов.');
|
||||
return;
|
||||
}
|
||||
for (const group of groupByMonth(entries)) {
|
||||
const heading = document.createElement('h2');
|
||||
heading.className = 'chat-media-month';
|
||||
heading.textContent = group.label;
|
||||
body.append(heading);
|
||||
if (activeTab === 'media') {
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'chat-media-grid';
|
||||
group.items.forEach((entry) => grid.append(createTile(entry, (attachment) => void openViewerAt(media, attachment))));
|
||||
body.append(grid);
|
||||
} else {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack chat-media-files';
|
||||
for (const entry of group.items) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'chat-media-file';
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'meta-muted chat-media-file__meta';
|
||||
meta.textContent = `${entry.from === 'out' ? 'Вы' : peerName} · ${formatDayLabel(entry.timeMs)}, ${formatClockTime(entry.timeMs)}`;
|
||||
row.append(createDmFileAttachmentCard(entry.attachment), meta);
|
||||
list.append(row);
|
||||
}
|
||||
body.append(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renderBody();
|
||||
loadFullDmHistory(chatId)
|
||||
.catch(() => { loadFailed = true; })
|
||||
.finally(() => {
|
||||
loading = false;
|
||||
renderBody();
|
||||
});
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
thumbObserver?.disconnect();
|
||||
// Просмотрщик мог остаться открытым поверх: его картинки живут, пока он не закрыт.
|
||||
window.setTimeout(() => objectUrls.forEach((url) => URL.revokeObjectURL(url)), 60000);
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
+589
-218
File diff suppressed because it is too large
Load Diff
@@ -1,192 +1,183 @@
|
||||
// «Новый чат»: выбрать, кому написать. Пока поле пустое – свои близкие и друзья; при вводе –
|
||||
// сначала свои (мгновенно, на устройстве), затем вся сеть (по имени и логину). Нажатие
|
||||
// открывает переписку, профиль – кнопкой справа.
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { authService } from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { createListSection, createPersonRow } from '../components/person-row.js';
|
||||
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { authService, normalizeDmChatId } from '../state.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'contact-search-view', title: 'Поиск контактов' };
|
||||
const searchAvatarSnapshotCache = new Map();
|
||||
const searchAvatarPendingByLogin = new Map();
|
||||
export const pageMeta = { id: 'contact-search-view', title: 'Новый чат' };
|
||||
|
||||
async function loadSearchAvatarSnapshot(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
if (!cleanLogin) return null;
|
||||
const key = cleanLogin.toLowerCase();
|
||||
if (searchAvatarSnapshotCache.has(key)) return searchAvatarSnapshotCache.get(key);
|
||||
if (searchAvatarPendingByLogin.has(key)) return searchAvatarPendingByLogin.get(key);
|
||||
const pending = loadProfileSnapshot(cleanLogin)
|
||||
.then((snapshot) => {
|
||||
searchAvatarSnapshotCache.set(key, snapshot || null);
|
||||
searchAvatarPendingByLogin.delete(key);
|
||||
return snapshot || null;
|
||||
})
|
||||
.catch(() => {
|
||||
searchAvatarSnapshotCache.set(key, null);
|
||||
searchAvatarPendingByLogin.delete(key);
|
||||
return null;
|
||||
});
|
||||
searchAvatarPendingByLogin.set(key, pending);
|
||||
return pending;
|
||||
const RELATION_TEXT = { close_friend: 'близкий друг', friend: 'друг', contact: 'контакт' };
|
||||
const RELATION_ORDER = { close_friend: 0, friend: 1, contact: 2 };
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
function createSearchAvatar(login) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
||||
const avatarEl = renderUserAvatar({
|
||||
login: cleanLogin || 'unknown',
|
||||
size: 'md',
|
||||
className: 'avatar',
|
||||
title,
|
||||
});
|
||||
if (!cleanLogin) return avatarEl;
|
||||
void loadSearchAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
if (!avatarEl.isConnected) return;
|
||||
const upgraded = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
avatar: snapshot?.avatar?.source
|
||||
? {
|
||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||
sha256Hex: String(snapshot?.avatar?.sha256Hex || '').trim().toLowerCase(),
|
||||
}
|
||||
: null,
|
||||
size: 'md',
|
||||
className: 'avatar',
|
||||
title,
|
||||
});
|
||||
avatarEl.replaceWith(upgraded);
|
||||
});
|
||||
return avatarEl;
|
||||
function displayName(person) {
|
||||
const full = [person.firstName, person.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
return full || String(person.displayName || '').trim() || person.login;
|
||||
}
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-search-screen';
|
||||
let disposed = false;
|
||||
let searchTimer = 0;
|
||||
let searchSeq = 0;
|
||||
let mine = []; // свои связи из списка чатов
|
||||
let remote = { query: '', items: [], loading: false, error: null };
|
||||
|
||||
const field = document.createElement('label');
|
||||
field.className = 'search-field contact-search-field';
|
||||
field.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
const input = document.createElement('input');
|
||||
input.className = 'search-field__input contact-search-input';
|
||||
input.type = 'text';
|
||||
input.name = 'contact';
|
||||
input.placeholder = 'Логин или его начало';
|
||||
input.setAttribute('aria-label', 'Логин для поиска');
|
||||
input.type = 'search';
|
||||
input.placeholder = 'Имя или логин';
|
||||
input.setAttribute('aria-label', 'Кому написать');
|
||||
input.enterKeyHint = 'search';
|
||||
input.autocomplete = 'off';
|
||||
input.maxLength = 80;
|
||||
field.append(input);
|
||||
|
||||
const resultsCard = document.createElement('section');
|
||||
resultsCard.className = 'stack contact-search-results';
|
||||
resultsCard.hidden = true;
|
||||
const results = document.createElement('div');
|
||||
results.className = 'contact-search-results';
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'contact-search-results-title';
|
||||
const openChat = (login) => navigate(`chat/${encodeURIComponent(normalizeDmChatId(login))}`);
|
||||
|
||||
const resultsList = document.createElement('div');
|
||||
resultsList.className = 'stack dm-list';
|
||||
|
||||
const renderResults = (matches, query) => {
|
||||
resultsList.innerHTML = '';
|
||||
|
||||
if (!query.trim()) {
|
||||
status.textContent = '';
|
||||
resultsCard.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
resultsCard.hidden = false;
|
||||
|
||||
if (!matches.length) {
|
||||
status.textContent = 'Найдено пользователей: 0';
|
||||
return;
|
||||
}
|
||||
|
||||
status.textContent = `Найдено пользователей: ${matches.length}`;
|
||||
|
||||
matches.forEach((login) => {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
const avatarEl = createSearchAvatar(login);
|
||||
row.innerHTML = `
|
||||
<div class="contact-search-result-main">
|
||||
<strong class="dm-row-title">${login}</strong>
|
||||
</div>
|
||||
<span class="dm-chevron" aria-hidden="true">›</span>
|
||||
`;
|
||||
row.prepend(avatarEl);
|
||||
row.addEventListener('click', () => {
|
||||
navigate(makeProfileRoute(login));
|
||||
});
|
||||
resultsList.append(row);
|
||||
function personRow(person, sub) {
|
||||
return createPersonRow({
|
||||
login: person.login,
|
||||
name: displayName(person),
|
||||
firstName: person.firstName,
|
||||
lastName: person.lastName,
|
||||
avatar: person.avatar || (person.avatarAr ? { ar: person.avatarAr } : null),
|
||||
ring: person.relationFlag === 'close_friend' ? 'close' : '',
|
||||
sub,
|
||||
onClick: () => openChat(person.login),
|
||||
actions: [{ icon: 'profile', label: 'Профиль', onClick: () => navigate(makeProfileRoute(person.login)) }],
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const runSearch = async () => {
|
||||
const query = input.value.trim();
|
||||
function renderResults() {
|
||||
if (disposed) return;
|
||||
const query = searchText(input.value).replace(/^@/, '');
|
||||
results.replaceChildren();
|
||||
const frag = document.createDocumentFragment();
|
||||
const ownMatches = mine.filter((person) => !query
|
||||
|| searchText(`${displayName(person)} ${person.login}`).includes(query));
|
||||
const ownShown = query ? ownMatches : ownMatches.filter((person) => person.relationFlag !== 'contact');
|
||||
if (ownShown.length) {
|
||||
frag.append(createListSection(query ? `Ваши связи · ${ownShown.length}` : 'Близкие и друзья'));
|
||||
ownShown.slice(0, query ? 50 : 40).forEach((person) => {
|
||||
const sub = [displayName(person) !== person.login ? `@${person.login}` : '', RELATION_TEXT[person.relationFlag] || ''].filter(Boolean).join(' · ');
|
||||
frag.append(personRow(person, sub));
|
||||
});
|
||||
}
|
||||
if (query.length >= 2) {
|
||||
const own = new Set(ownMatches.map((person) => person.login.toLowerCase()));
|
||||
const others = remote.items.filter((user) => !own.has(String(user.login || '').toLowerCase()));
|
||||
if (remote.loading || remote.error || others.length) frag.append(createListSection('Во всей сети'));
|
||||
if (remote.loading) frag.append(createLoadingState({ label: 'Ищу', delayMs: 150 }));
|
||||
else if (remote.error) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'empty-note';
|
||||
note.textContent = toUserMessage(remote.error, 'Поиск по сети сейчас недоступен.');
|
||||
frag.append(note);
|
||||
} else {
|
||||
others.forEach((user) => {
|
||||
const person = { login: String(user.login || ''), displayName: user.displayName, avatarAr: user.avatarAr };
|
||||
frag.append(personRow(person, displayName(person) !== person.login ? `@${person.login}` : ''));
|
||||
});
|
||||
}
|
||||
if (!ownShown.length && !remote.loading && !remote.error && !others.length) {
|
||||
frag.append(createStateMessage({ icon: 'search', title: 'Никого не нашлось', text: 'Проверьте имя или логин.' }));
|
||||
}
|
||||
} else if (!ownShown.length) {
|
||||
frag.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: query ? 'Никого не нашлось' : 'Кому написать?',
|
||||
text: 'Начните вводить имя или логин – поищем среди ваших связей и во всей сети.',
|
||||
}));
|
||||
}
|
||||
results.append(frag);
|
||||
}
|
||||
|
||||
async function runRemote() {
|
||||
const query = searchText(input.value).replace(/^@/, '');
|
||||
const seq = ++searchSeq;
|
||||
if (!query) {
|
||||
renderResults([], '');
|
||||
if (query.length < 2) {
|
||||
remote = { query: '', items: [], loading: false, error: null };
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
|
||||
remote = { query, items: [], loading: true, error: null };
|
||||
renderResults();
|
||||
try {
|
||||
const logins = await authService.searchUsers(query);
|
||||
if (seq !== searchSeq) return;
|
||||
renderResults((logins || []).slice(0, 5), query);
|
||||
} catch (e) {
|
||||
if (seq !== searchSeq) return;
|
||||
status.textContent = `Ошибка поиска: ${e.message || 'unknown'}`;
|
||||
resultsCard.hidden = false;
|
||||
resultsList.innerHTML = '';
|
||||
const users = await authService.searchPeople(query, { limit: 20 });
|
||||
if (disposed || seq !== searchSeq) return;
|
||||
remote = { query, items: Array.isArray(users) ? users : [], loading: false, error: null };
|
||||
} catch (error) {
|
||||
if (disposed || seq !== searchSeq) return;
|
||||
remote = { query, items: [], loading: false, error };
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleSearch = () => {
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
searchTimer = window.setTimeout(() => {
|
||||
searchTimer = 0;
|
||||
void runSearch();
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const searchButton = document.createElement('button');
|
||||
searchButton.className = 'search-field__action';
|
||||
searchButton.type = 'button';
|
||||
searchButton.textContent = 'Найти';
|
||||
searchButton.addEventListener('click', async () => {
|
||||
if (searchTimer) {
|
||||
window.clearTimeout(searchTimer);
|
||||
searchTimer = 0;
|
||||
}
|
||||
await runSearch();
|
||||
});
|
||||
renderResults();
|
||||
}
|
||||
|
||||
input.addEventListener('input', () => {
|
||||
scheduleSearch();
|
||||
renderResults();
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
searchTimer = window.setTimeout(() => { searchTimer = 0; void runRemote(); }, 300);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
searchButton.click();
|
||||
results.querySelector('.person-row__main')?.click();
|
||||
});
|
||||
|
||||
const formCard = document.createElement('label');
|
||||
formCard.className = 'search-field contact-search-field';
|
||||
formCard.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
formCard.append(input, searchButton);
|
||||
|
||||
resultsCard.append(status, resultsList);
|
||||
// Свои связи – из того же ответа, что и список чатов.
|
||||
async function loadMine() {
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed) return;
|
||||
const byLogin = new Map();
|
||||
for (const dialog of Array.isArray(payload?.dialogs) ? payload.dialogs : []) {
|
||||
const login = String(dialog?.peerLogin || '').trim();
|
||||
const relationFlag = String(dialog?.relationFlag || '').trim().toLowerCase();
|
||||
if (!login || !RELATION_TEXT[relationFlag] || byLogin.has(login.toLowerCase())) continue;
|
||||
byLogin.set(login.toLowerCase(), {
|
||||
login,
|
||||
relationFlag,
|
||||
firstName: String(dialog?.firstName || '').trim(),
|
||||
lastName: String(dialog?.lastName || '').trim(),
|
||||
avatar: dialog?.avatar && typeof dialog.avatar === 'object' ? dialog.avatar : null,
|
||||
});
|
||||
}
|
||||
mine = [...byLogin.values()].sort((a, b) => (RELATION_ORDER[a.relationFlag] - RELATION_ORDER[b.relationFlag])
|
||||
|| displayName(a).localeCompare(displayName(b), 'ru'));
|
||||
} catch {
|
||||
mine = [];
|
||||
}
|
||||
renderResults();
|
||||
}
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Найти человека',
|
||||
back: { label: '←', onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(
|
||||
formCard,
|
||||
resultsCard,
|
||||
);
|
||||
title: 'Новый чат',
|
||||
back: { onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(field, results);
|
||||
results.append(createLoadingState({ label: 'Загружаю связи' }));
|
||||
void loadMine();
|
||||
window.requestAnimationFrame(() => { if (!disposed) input.focus(); });
|
||||
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
searchSeq += 1;
|
||||
if (searchTimer) window.clearTimeout(searchTimer);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
import { resolveThemeMode } from '../services/theme-service.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, state } from '../state.js';
|
||||
import {
|
||||
@@ -258,6 +260,7 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list settings-developer-card';
|
||||
card.innerHTML = `
|
||||
<button class="nav-row" type="button" id="settings-theme-editor"><span class="nav-row__label">Настроить цвета</span></button>
|
||||
<button class="nav-row" type="button" id="settings-force-ui-update"><span class="nav-row__label">Принудительно обновить UI</span></button>
|
||||
<button class="nav-row" type="button" id="settings-force-update-help"><span class="nav-row__label">Клиент не обновляется?</span></button>
|
||||
<button class="nav-row" type="button" id="settings-ui-error-reporting"><span class="nav-row__label">Отправлять ошибки на сервер</span></button>
|
||||
@@ -269,6 +272,7 @@ export function render({navigate, chrome}) {
|
||||
<button class="nav-row" type="button" id="settings-upload-avatar"><span class="nav-row__label">Загрузить аватар</span></button>
|
||||
`;
|
||||
|
||||
card.querySelector('#settings-theme-editor').addEventListener('click', () => openPaletteEditor({ theme: resolveThemeMode() }));
|
||||
const appLogBtn = card.querySelector('#settings-app-log');
|
||||
const diagnosticsBtn = card.querySelector('#settings-pwa-diagnostics');
|
||||
const pwaInstallBtn = card.querySelector('#settings-pwa-install');
|
||||
|
||||
@@ -618,7 +618,7 @@ export function render({navigate, chrome}) {
|
||||
await reloadRequests({ silent: true });
|
||||
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
|
||||
if (disposed) return;
|
||||
showToast('Пришла новая заявка на вход через доверенное устройство');
|
||||
showToast('Пришла новая заявка на вход через доверенное устройство', { kind: 'info' });
|
||||
void reloadRequests({ silent: true });
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authService,
|
||||
isSessionInvalidError,
|
||||
@@ -90,7 +92,7 @@ export function render({navigate, route, chrome}) {
|
||||
} catch (error) {
|
||||
if (!isSessionInvalidError(error)) {
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Не удалось завершить сеанс.'), { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (isCurrentSession) {
|
||||
@@ -112,7 +114,7 @@ export function render({navigate, route, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -81,11 +81,9 @@ export function render({navigate, chrome}) {
|
||||
actions.className = 'nav-list';
|
||||
actions.innerHTML = `
|
||||
<button class="nav-row" type="button" id="pair-by-code-btn"><span class="nav-row__label">Подключить другое устройство</span><span class="nav-row__hint">Подтвердить вход на новом устройстве</span></button>
|
||||
<button class="nav-row" type="button" id="show-keys-btn"><span class="nav-row__label">Ключи этого устройства</span></button>
|
||||
`;
|
||||
|
||||
actions.querySelector('#pair-by-code-btn').addEventListener('click', () => navigate('device-pairing-view'));
|
||||
actions.querySelector('#show-keys-btn').addEventListener('click', () => navigate('show-keys-view'));
|
||||
|
||||
const sessionsBlock = document.createElement('div');
|
||||
sessionsBlock.className = 'stack device-sessions';
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
authorizeLocalDemoSession,
|
||||
isLocalDemoAvailable,
|
||||
@@ -180,7 +182,7 @@ export function render({ navigate }) {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('start-view');
|
||||
} catch (error) {
|
||||
window.alert(error?.message || 'Не удалось сохранить настройки входа.');
|
||||
showToast(toUserMessage(error, 'Не удалось сохранить настройки входа.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ function input(label,type='password'){const wrap=document.createElement('label')
|
||||
|
||||
export function render({navigate,chrome}){
|
||||
const screen=document.createElement('section');screen.className='stack';
|
||||
chrome?.setTopbar(createTopBar({title:'Смена ключей',back:{label:'←',onClick:()=>navigate('my-blockchain-view')}}));
|
||||
chrome?.setTopbar(createTopBar({title:'Смена ключей',back:{label:'←',onClick:()=>navigate('access-keys-view')}}));
|
||||
const root=document.createElement('div');root.className='stack';screen.append(root);
|
||||
const client=new KeyRotationClient(authService);let disposed=false;let timer=null;let cachedOldBundle=null;let cachedNewBundle=null;
|
||||
const login=String(state.session.login||'').trim(); const storagePwd=String(state.session.storagePwdInMemory||'').trim();
|
||||
@@ -119,12 +119,12 @@ export function render({navigate,chrome}){
|
||||
}catch(e){err.textContent=e?.message||String(e);transfer.disabled=false;skip.disabled=false;}finally{refreshBalance.disabled=false;}});
|
||||
continueButton.addEventListener('click',async()=>{continueButton.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||
const next=await client.continueRotation({walletMigrationStatus:'COMPLETE'});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('access-keys-view');return;}
|
||||
await refresh();
|
||||
}catch(e){err.textContent=e?.message||String(e);continueButton.disabled=false;refreshBalance.disabled=false;}});
|
||||
skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||
const next=await client.continueRotation({walletMigrationStatus:'SKIPPED'});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('access-keys-view');return;}
|
||||
await refresh();
|
||||
}catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;refreshBalance.disabled=false;}});
|
||||
|
||||
@@ -172,14 +172,14 @@ export function render({navigate,chrome}){
|
||||
}
|
||||
}
|
||||
const next=await client.continueRotation({});
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}
|
||||
if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('access-keys-view');return;}
|
||||
await refresh();
|
||||
};
|
||||
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
|
||||
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, — новый. На сервер собеседника повторная отправка не выполняется.'),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
|
||||
const nodes=[statusCard(s),note('Локальные входящие и исходящие копии будут приведены к новому client key. Клиент сначала пробует старый ключ, а для сообщений, уже пришедших после смены PDA, – новый. На сервер собеседника повторная отправка не выполняется.'),progress];if(oldP)nodes.push(oldP.wrap);if(newP)nodes.push(newP.wrap);nodes.push(go,err);setRoot(...nodes);
|
||||
if(cachedOldBundle&&cachedNewBundle)void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;});
|
||||
}
|
||||
|
||||
async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){await renderMessageMigration(s);return;}if(st==='FINALIZING'){const next=await client.continueRotation({});if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('my-blockchain-view');return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note('Смена ключей завершена.'));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}`));}}
|
||||
async function refresh(){if(disposed)return;if(timer){clearTimeout(timer);timer=null;}try{const s=await client.status();const st=String(s.rotationStatus||'NONE');if(st==='NONE'){await renderNone();return;}if(st==='COPYING_CHAIN'){if(cachedNewBundle)await runCopy(s);else await askNewPasswordAndCopy(s);return;}if(st==='CHAIN_READY'){await renderChainReady(s);return;}if(['ROTATING_PDA','PDA_ROTATED','REBUILDING_SERVER'].includes(st)){pollView(s);return;}if(st==='WALLET_MIGRATION'){await renderWalletMigration(s);return;}if(st==='MESSAGE_MIGRATION'){await renderMessageMigration(s);return;}if(st==='FINALIZING'){const next=await client.continueRotation({});if(String(next?.rotationStatus||'')==='COMPLETE'){navigate('access-keys-view');return;}await refresh();return;}if(st==='COMPLETE'){setRoot(note('Смена ключей завершена.'));return;}setRoot(note(`Неизвестное состояние ротации: ${st}`));}catch(e){setRoot(note(`Не удалось прочитать состояние смены ключей: ${e?.message||e}`));}}
|
||||
void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen;
|
||||
}
|
||||
|
||||
@@ -3,15 +3,28 @@ import {
|
||||
getChatMessages,
|
||||
isSessionInvalidError,
|
||||
normalizeDmChatId,
|
||||
rememberDmPeer,
|
||||
setContacts,
|
||||
state,
|
||||
terminateCurrentSession,
|
||||
} from '../state.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
|
||||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||||
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT,
|
||||
getPinnedDmChats,
|
||||
isDmChatMuted,
|
||||
setDmChatPinned,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
|
||||
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
||||
const PREVIEW_MAX_LEN = 200;
|
||||
@@ -48,7 +61,9 @@ async function loadDmAvatarSnapshot(login) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
function createDmAvatar(login, { className = '', avatar = null, firstName = '', lastName = '' } = {}) {
|
||||
// whenVisible(fn) – отложить запрос профиля до появления строки на экране: в списке на сотни
|
||||
// контактов иначе уходят сотни запросов сразу.
|
||||
function createDmAvatar(login, { className = '', avatar = null, firstName = '', lastName = '', whenVisible = null } = {}) {
|
||||
const cleanLogin = String(login || '').trim();
|
||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
||||
const avatarEl = renderUserAvatar({
|
||||
@@ -61,10 +76,13 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
||||
className,
|
||||
});
|
||||
if (!cleanLogin || avatar?.ar || avatar?.sha256Hex) return avatarEl;
|
||||
void loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
if (!avatarEl.isConnected) return;
|
||||
const upgrade = () => loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||
// Фото нет – оставляем инициалы имени как есть (раньше подменялись на букву логина).
|
||||
if (!avatarEl.isConnected || !snapshot?.avatar?.source) return;
|
||||
const upgraded = renderUserAvatar({
|
||||
login: cleanLogin,
|
||||
firstName: String(firstName || '').trim(),
|
||||
lastName: String(lastName || '').trim(),
|
||||
avatar: snapshot?.avatar?.source
|
||||
? {
|
||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||
@@ -78,6 +96,8 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
||||
upgraded.classList.add('avatar');
|
||||
avatarEl.replaceWith(upgraded);
|
||||
});
|
||||
if (typeof whenVisible === 'function') whenVisible(avatarEl, upgrade);
|
||||
else void upgrade();
|
||||
return avatarEl;
|
||||
}
|
||||
|
||||
@@ -112,12 +132,13 @@ function clipPreviewText(text, maxLen = PREVIEW_MAX_LEN) {
|
||||
}
|
||||
|
||||
const DM_PREVIEW_ENCRYPTED = 'Зашифрованное сообщение';
|
||||
const DM_PREVIEW_EMPTY = 'Нет сообщений';
|
||||
|
||||
async function resolveDialogPreview(dialog) {
|
||||
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
||||
if (localText) return localText;
|
||||
const blobB64 = String(dialog?.lastMessageBlobB64 || '').trim();
|
||||
if (!blobB64) return 'Диалог пока пуст.';
|
||||
if (!blobB64) return DM_PREVIEW_EMPTY;
|
||||
|
||||
const cacheKey = [
|
||||
blobB64,
|
||||
@@ -181,6 +202,10 @@ function latestLocalDialogMessage(peerLogin) {
|
||||
return { text, timeMs: resolveLocalMessageTimeMs(latest) };
|
||||
}
|
||||
|
||||
// Последний загруженный список чатов (в памяти вкладки): при возврате на «Чаты» он рисуется
|
||||
// сразу, без пустого кадра, и тихо обновляется с сервера.
|
||||
let lastChatList = null; // { login, items }
|
||||
|
||||
function formatChatRowTime(ts) {
|
||||
return formatListTime(ts);
|
||||
}
|
||||
@@ -198,6 +223,7 @@ export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-list-screen';
|
||||
let disposed = false;
|
||||
let currentChatFilter = 'all';
|
||||
const CHAT_FILTERS = [
|
||||
['all', 'Все'],
|
||||
@@ -237,23 +263,122 @@ export function render({ navigate, chrome }) {
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
|
||||
let chatQuery = '';
|
||||
let chatSearch = null;
|
||||
const head = createTopBar({
|
||||
title: 'Чаты',
|
||||
className: 'topbar--root',
|
||||
actions: [
|
||||
{
|
||||
icon: 'search',
|
||||
title: 'Найти человека',
|
||||
ariaLabel: 'Найти человека',
|
||||
title: 'Поиск по чатам',
|
||||
ariaLabel: 'Поиск по чатам',
|
||||
className: 'messages-search-btn',
|
||||
onClick: () => openChatsSearch(),
|
||||
},
|
||||
{
|
||||
icon: 'compose',
|
||||
title: 'Новый чат',
|
||||
ariaLabel: 'Новый чат',
|
||||
className: 'messages-compose-btn',
|
||||
onClick: () => navigate('contact-search-view'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function openChatsSearch() {
|
||||
if (chatSearch) return;
|
||||
const bar = createSearchTopBar({
|
||||
placeholder: 'Имя или логин',
|
||||
onInput: (value) => {
|
||||
chatQuery = String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
renderList();
|
||||
},
|
||||
onSubmit: () => list.querySelector('.dm-dialog-card')?.click(),
|
||||
onClose: () => closeChatsSearch(),
|
||||
});
|
||||
chatSearch = { bar, layer: openHistoryLayer(() => closeChatsSearch({ fromHistory: true })) };
|
||||
chrome?.setTopbar(bar);
|
||||
bar.searchInput?.focus();
|
||||
filterRow.hidden = true;
|
||||
}
|
||||
|
||||
function closeChatsSearch({ fromHistory = false } = {}) {
|
||||
if (!chatSearch) return;
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
chatQuery = '';
|
||||
if (!fromHistory) layer?.close();
|
||||
filterRow.hidden = false;
|
||||
if (!disposed) {
|
||||
chrome?.setTopbar(head);
|
||||
renderList();
|
||||
}
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack dm-list';
|
||||
|
||||
// Меню чата по долгому нажатию (или правой кнопкой): закрепить и выключить звук.
|
||||
// Одно меню на весь список; якорь ставится у строки, на которой его открыли.
|
||||
const rowMenuAnchor = document.createElement('span');
|
||||
rowMenuAnchor.className = 'dm-row-menu-anchor';
|
||||
rowMenuAnchor.setAttribute('aria-hidden', 'true');
|
||||
let rowMenuItem = null;
|
||||
let rowMenuOpenedAt = 0;
|
||||
const rowMenu = createDropdownMenu({
|
||||
anchorEl: rowMenuAnchor,
|
||||
minWidth: 200,
|
||||
transparent: true,
|
||||
items: () => {
|
||||
if (!rowMenuItem) return [];
|
||||
const id = normalizeDmChatId(rowMenuItem.peerLogin);
|
||||
return [
|
||||
{
|
||||
label: rowMenuItem.pinned ? 'Открепить' : 'Закрепить',
|
||||
iconHtml: iconHtml('pin'),
|
||||
action: () => setDmChatPinned(id, !rowMenuItem.pinned),
|
||||
},
|
||||
createDmMuteMenuItem(id),
|
||||
];
|
||||
},
|
||||
});
|
||||
const openRowMenu = (row, item) => {
|
||||
if (Date.now() - rowMenuOpenedAt < 700) return;
|
||||
rowMenuItem = item;
|
||||
rowMenuOpenedAt = Date.now();
|
||||
const rect = row.getBoundingClientRect();
|
||||
const listRect = screen.getBoundingClientRect();
|
||||
rowMenuAnchor.style.top = `${rect.top - listRect.top + rect.height / 2}px`;
|
||||
rowMenuAnchor.style.left = `${rect.right - listRect.left - 24}px`;
|
||||
rowMenu.open();
|
||||
try { navigator.vibrate?.(12); } catch { /* вибрация не обязательна */ }
|
||||
};
|
||||
function bindRowMenu(row, item) {
|
||||
let pressTimer = 0;
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
const cancel = () => { window.clearTimeout(pressTimer); pressTimer = 0; };
|
||||
row.addEventListener('pointerdown', (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
startX = event.clientX;
|
||||
startY = event.clientY;
|
||||
cancel();
|
||||
pressTimer = window.setTimeout(() => openRowMenu(row, item), 500);
|
||||
});
|
||||
row.addEventListener('pointermove', (event) => {
|
||||
if (pressTimer && Math.hypot(event.clientX - startX, event.clientY - startY) > 8) cancel();
|
||||
});
|
||||
row.addEventListener('pointerup', cancel);
|
||||
row.addEventListener('pointercancel', cancel);
|
||||
row.addEventListener('contextmenu', (event) => {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
openRowMenu(row, item);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRow(item) {
|
||||
const row = document.createElement('article');
|
||||
row.className = 'list-item dm-dialog-card';
|
||||
@@ -263,6 +388,7 @@ function renderRow(item) {
|
||||
avatar: item.avatar,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
whenVisible,
|
||||
});
|
||||
avatarEl.classList.add('avatar');
|
||||
const avatarWrap = document.createElement('div');
|
||||
@@ -273,6 +399,7 @@ function renderRow(item) {
|
||||
<div class="dm-row-main">
|
||||
<div class="dm-row-titleline dm-row-titlewrap">
|
||||
<strong class="dm-row-title"></strong>
|
||||
${item.muted ? `<span class="dm-row-muted" title="Без звука">${iconHtml('bell-off')}</span>` : ''}
|
||||
${relationBadge ? `<span class="dm-contact-note dm-contact-note--${relationFlag}">${relationBadge}</span>` : ''}
|
||||
</div>
|
||||
<p class="dm-row-last-message"></p>
|
||||
@@ -281,7 +408,11 @@ function renderRow(item) {
|
||||
<div class="dm-row-meta-line">
|
||||
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
||||
</div>
|
||||
${item.unreadCount ? `<span class="dm-unread-badge">${item.unreadCount > 99 ? '99+' : item.unreadCount}</span>` : '<span class="dm-row-meta-spacer" aria-hidden="true"></span>'}
|
||||
${item.unreadCount
|
||||
? `<span class="dm-unread-badge${item.muted ? ' dm-unread-badge--muted' : ''}">${item.unreadCount > 99 ? '99+' : item.unreadCount}</span>`
|
||||
: (item.pinned
|
||||
? `<span class="dm-row-pin" title="Закреплён">${iconHtml('pin')}</span>`
|
||||
: '<span class="dm-row-meta-spacer" aria-hidden="true"></span>')}
|
||||
</div>
|
||||
`;
|
||||
const titleEl = row.querySelector('.dm-row-title');
|
||||
@@ -291,18 +422,147 @@ function renderRow(item) {
|
||||
const fullName = [String(item.firstName || '').trim(), String(item.lastName || '').trim()].filter(Boolean).join(' ');
|
||||
titleEl.textContent = fullName || String(item.peerLogin || '');
|
||||
}
|
||||
if (previewEl) previewEl.textContent = 'Загрузка…';
|
||||
if (timeEl) timeEl.textContent = formatChatRowTime(item.lastMessageTimeMs);
|
||||
row.prepend(avatarWrap);
|
||||
void resolveDialogPreview(item).then((text) => {
|
||||
if (!previewEl?.isConnected) return;
|
||||
previewEl.textContent = String(text || '').trim() || 'Диалог пока пуст.';
|
||||
// Текст превью ставится сразу, если известен; иначе строка пустая до расшифровки –
|
||||
// без мелькающего «Загрузка…».
|
||||
const showPreview = (text) => {
|
||||
if (!previewEl) return;
|
||||
previewEl.textContent = String(text || '').trim() || DM_PREVIEW_EMPTY;
|
||||
previewEl.classList.toggle('is-encrypted', text === DM_PREVIEW_ENCRYPTED);
|
||||
previewEl.classList.toggle('is-empty', previewEl.textContent === DM_PREVIEW_EMPTY);
|
||||
};
|
||||
const knownText = clipPreviewText(String(item.lastMessageText || '').trim());
|
||||
if (knownText || !item.lastMessageBlobB64) showPreview(knownText);
|
||||
else {
|
||||
if (previewEl) previewEl.textContent = '\u00a0';
|
||||
void resolveDialogPreview(item).then((text) => {
|
||||
if (previewEl?.isConnected) showPreview(text);
|
||||
});
|
||||
}
|
||||
if (item.pinned) row.classList.add('is-pinned');
|
||||
row.addEventListener('click', (event) => {
|
||||
// Долгое нажатие уже открыло меню чата – отпускание пальца не должно открывать сам чат.
|
||||
if (Date.now() - rowMenuOpenedAt < 700) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`);
|
||||
});
|
||||
row.addEventListener('click', () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(item.peerLogin))}`));
|
||||
bindRowMenu(row, item);
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профили для аватаров – только у строк, которые видны (или вот-вот будут видны).
|
||||
const visibleWaiters = new Map();
|
||||
const avatarObserver = typeof IntersectionObserver === 'function'
|
||||
? new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
const fn = visibleWaiters.get(entry.target);
|
||||
visibleWaiters.delete(entry.target);
|
||||
avatarObserver.unobserve(entry.target);
|
||||
fn?.();
|
||||
});
|
||||
}, { rootMargin: '200px 0px' })
|
||||
: null;
|
||||
function whenVisible(el, fn) {
|
||||
if (!avatarObserver) { fn(); return; }
|
||||
visibleWaiters.set(el, fn);
|
||||
avatarObserver.observe(el);
|
||||
}
|
||||
|
||||
// Последний ответ сервера, уже разобранный: фильтр перерисовывает без запроса.
|
||||
let lastItems = lastChatList?.login === login ? lastChatList.items : null;
|
||||
let startExpanded = false;
|
||||
const START_PREVIEW = 5;
|
||||
|
||||
function hasConversation(item) {
|
||||
return Boolean(item.hasDialog || item.lastMessageTimeMs > 0 || item.unreadCount > 0 || item.pinned);
|
||||
}
|
||||
|
||||
function matchesChatQuery(item) {
|
||||
const hay = `${item.firstName || ''} ${item.lastName || ''} ${item.peerLogin || ''}`.toLowerCase().replaceAll('ё', 'е');
|
||||
return hay.includes(chatQuery);
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
if (!lastItems) return;
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
// В поиске – по всем чатам и контактам сразу, без фильтра по типу связи.
|
||||
const filtered = chatQuery
|
||||
? lastItems.filter(matchesChatQuery)
|
||||
: lastItems.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter);
|
||||
// Переписки – по свежести, закреплённые выше всех (последний закреплённый – первым).
|
||||
const chats = filtered.filter(hasConversation).sort((a, b) => {
|
||||
const pinA = a.pinned ? pinnedOrder.indexOf(normalizeDmChatId(a.peerLogin)) : -1;
|
||||
const pinB = b.pinned ? pinnedOrder.indexOf(normalizeDmChatId(b.peerLogin)) : -1;
|
||||
if (pinA >= 0 || pinB >= 0) {
|
||||
if (pinA < 0) return 1;
|
||||
if (pinB < 0) return -1;
|
||||
return pinA - pinB;
|
||||
}
|
||||
return compareChatRows(a, b);
|
||||
});
|
||||
// Без переписки: во «Всех» – только близкие и друзья (контактов могут быть сотни),
|
||||
// в фильтре по типу связи – все этого типа.
|
||||
const byName = (a, b) => (relationOrder(a.relationFlag) - relationOrder(b.relationFlag))
|
||||
|| String(a.firstName || a.peerLogin).localeCompare(String(b.firstName || b.peerLogin), 'ru');
|
||||
const silent = filtered
|
||||
.filter((item) => !hasConversation(item) && normalizeRelationFlag(item.relationFlag) !== 'none')
|
||||
.filter((item) => chatQuery || currentChatFilter !== 'all' || ['close_friend', 'friend'].includes(normalizeRelationFlag(item.relationFlag)))
|
||||
.sort(byName);
|
||||
|
||||
list.replaceChildren();
|
||||
if (!chats.length && !silent.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
if (chatQuery) {
|
||||
empty.textContent = 'Среди ваших чатов и контактов никого не нашлось.';
|
||||
const wide = document.createElement('button');
|
||||
wide.type = 'button';
|
||||
wide.className = 'secondary-btn dm-search-wide';
|
||||
wide.textContent = 'Искать во всей сети';
|
||||
wide.addEventListener('click', () => navigate('contact-search-view'));
|
||||
list.append(empty, wide);
|
||||
return;
|
||||
}
|
||||
if (currentChatFilter === 'all') {
|
||||
list.append(createStateMessage({
|
||||
icon: 'message',
|
||||
title: 'Пока нет переписок',
|
||||
text: 'Напишите кому-нибудь из друзей или найдите человека по имени.',
|
||||
actionLabel: 'Новый чат',
|
||||
onAction: () => navigate('contact-search-view'),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
empty.textContent = 'Здесь пока никого.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
chats.forEach((item) => frag.append(renderRow(item)));
|
||||
if (silent.length) {
|
||||
const divider = document.createElement('div');
|
||||
divider.className = 'dm-divider';
|
||||
divider.textContent = chats.length ? `Начать переписку · ${silent.length}` : `Без переписки · ${silent.length}`;
|
||||
frag.append(divider);
|
||||
const collapsed = !chatQuery && !startExpanded && silent.length > START_PREVIEW + 1 && chats.length > 0;
|
||||
(collapsed ? silent.slice(0, START_PREVIEW) : silent).forEach((item) => frag.append(renderRow(item)));
|
||||
if (collapsed) {
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
more.className = 'list-more';
|
||||
more.innerHTML = `${iconHtml('chevron-down')}<span>Показать всех · ${silent.length}</span>`;
|
||||
more.addEventListener('click', () => { startExpanded = true; renderList(); });
|
||||
frag.append(more);
|
||||
}
|
||||
}
|
||||
list.append(frag);
|
||||
}
|
||||
|
||||
let loadSeq = 0;
|
||||
async function loadList() {
|
||||
if (state.session.isLocalDemo) {
|
||||
const empty = document.createElement('div');
|
||||
@@ -311,16 +571,19 @@ function renderRow(item) {
|
||||
list.replaceChildren(empty);
|
||||
return;
|
||||
}
|
||||
const seq = ++loadSeq;
|
||||
// Первый показ – спиннер, но только если ждать заметно (без мелькания).
|
||||
if (!lastItems && !list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю чаты' }));
|
||||
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
||||
const contacts = dialogs
|
||||
.filter((dialog) => normalizeRelationFlag(dialog?.relationFlag) !== 'none')
|
||||
.map((dialog) => String(dialog?.peerLogin || '').trim())
|
||||
.filter(Boolean);
|
||||
setContacts(contacts);
|
||||
list.innerHTML = '';
|
||||
|
||||
const byPeer = new Map();
|
||||
dialogs.forEach((dialog) => {
|
||||
@@ -361,33 +624,34 @@ function renderRow(item) {
|
||||
byPeer.set(key, newest);
|
||||
});
|
||||
|
||||
const rows = Array.from(byPeer.values())
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог.
|
||||
// Пустые друзья/контакты остаются, а пользователь без связи исчезает после очистки.
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog))
|
||||
.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter)
|
||||
.sort((a, b) => {
|
||||
const orderA = relationOrder(a.relationFlag);
|
||||
const orderB = relationOrder(b.relationFlag);
|
||||
if (orderA !== orderB) return orderA - orderB;
|
||||
return compareChatRows(a, b);
|
||||
});
|
||||
byPeer.forEach((item) => rememberDmPeer({
|
||||
login: item.peerLogin,
|
||||
relationType: item.relationFlag,
|
||||
firstName: item.firstName,
|
||||
lastName: item.lastName,
|
||||
avatar: item.avatar,
|
||||
shineStatus: item.shineStatus,
|
||||
}));
|
||||
|
||||
if (!rows.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'empty-note';
|
||||
empty.textContent = 'Пока нет переписок. Найдите человека через поиск вверху.';
|
||||
list.append(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
rows.forEach((item) => {
|
||||
list.append(renderRow(item));
|
||||
const pinnedOrder = getPinnedDmChats();
|
||||
byPeer.forEach((item) => {
|
||||
const id = normalizeDmChatId(item.peerLogin);
|
||||
item.pinned = pinnedOrder.includes(id);
|
||||
item.muted = isDmChatMuted(id);
|
||||
});
|
||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог:
|
||||
// пользователь без связи исчезает после очистки.
|
||||
const nextItems = Array.from(byPeer.values())
|
||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog));
|
||||
// Ничего не изменилось – не перерисовываем (иначе мигают аватары и превью).
|
||||
const unchanged = lastItems && JSON.stringify(nextItems) === JSON.stringify(lastItems) && list.childElementCount;
|
||||
lastItems = nextItems;
|
||||
lastChatList = { login, items: nextItems };
|
||||
if (!unchanged) renderList();
|
||||
} catch (error) {
|
||||
if (disposed || seq !== loadSeq) return;
|
||||
if (isSessionInvalidError(error)) {
|
||||
list.innerHTML = '';
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
@@ -413,22 +677,45 @@ function renderRow(item) {
|
||||
list.append(card);
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = '';
|
||||
const fail = document.createElement('div');
|
||||
fail.className = 'card meta-muted';
|
||||
fail.textContent = `Не удалось загрузить сообщения: ${error.message || 'unknown'}`;
|
||||
list.append(fail);
|
||||
// Уже показанный список не стираем из-за неудачного обновления.
|
||||
if (lastItems) return;
|
||||
list.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить чаты',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { list.replaceChildren(); void loadList(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
reloadForFilter = () => { void loadList(); };
|
||||
// Фильтр перерисовывает уже загруженный список мгновенно и тихо обновляет его с сервера.
|
||||
reloadForFilter = () => {
|
||||
startExpanded = false;
|
||||
renderList();
|
||||
void loadList();
|
||||
};
|
||||
|
||||
chrome?.setTopbar(head);
|
||||
screen.append(filterRow, list);
|
||||
screen.append(filterRow, list, rowMenuAnchor);
|
||||
if (lastItems) renderList();
|
||||
loadList();
|
||||
|
||||
screen.cleanup = () => {};
|
||||
// Закрепили или выключили звук (здесь же или в чате) – список перестраивается из кэша сервера.
|
||||
const handlePrefsUpdated = () => { void loadList(); };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, handlePrefsUpdated);
|
||||
avatarObserver?.disconnect();
|
||||
visibleWaiters.clear();
|
||||
rowMenu.destroy();
|
||||
if (chatSearch) {
|
||||
const { layer } = chatSearch;
|
||||
chatSearch = null;
|
||||
layer?.close();
|
||||
}
|
||||
};
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { render as renderBlockchain } from './my-blockchain-view.js';
|
||||
|
||||
export const pageMeta = { id: 'my-blockchain-history-view', title: 'История моего блокчейна' };
|
||||
export function render(context) {
|
||||
return renderBlockchain(context, { historyOnly: true });
|
||||
}
|
||||
@@ -481,24 +481,40 @@ function createEntryCard({ item, inspection, parseError, channelNames, blockchai
|
||||
return card;
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
export function render({ navigate, chrome }, { historyOnly = false } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack my-blockchain-screen';
|
||||
chrome?.setTopbar(createTopBar({ title: 'Мой блокчейн', back: { label: '←', onClick: () => navigate('settings-view') } }));
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: historyOnly ? 'История моего блокчейна' : 'Мой блокчейн',
|
||||
back: { label: '←', onClick: () => navigate(historyOnly ? 'my-blockchain-view' : 'settings-view') },
|
||||
}));
|
||||
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'card stack';
|
||||
intro.innerHTML = '<strong>История ваших действий</strong><span class="meta-muted">Это текущая активная версия вашего блокчейна. Хэши записей сохраняют логическую идентичность при fork.</span>';
|
||||
const rotate = document.createElement('button');
|
||||
rotate.type = 'button';
|
||||
rotate.className = 'primary-btn';
|
||||
rotate.textContent = 'Сменить пароль / ключи';
|
||||
rotate.addEventListener('click', () => navigate('key-rotation-view'));
|
||||
intro.append(rotate);
|
||||
screen.append(intro);
|
||||
if (!historyOnly) {
|
||||
const intro = document.createElement('div');
|
||||
intro.className = 'card stack';
|
||||
const historyButton = document.createElement('button');
|
||||
historyButton.type = 'button';
|
||||
historyButton.className = 'nav-row';
|
||||
historyButton.textContent = 'Показать историю моего блокчейна';
|
||||
historyButton.addEventListener('click', () => navigate('my-blockchain-history-view'));
|
||||
const filesButton = document.createElement('button');
|
||||
filesButton.type = 'button';
|
||||
filesButton.className = 'nav-row';
|
||||
filesButton.textContent = 'Файлы в блокчейне';
|
||||
filesButton.addEventListener('click', () => navigate('arweave-uploads-view'));
|
||||
const remoteButton = document.createElement('button');
|
||||
remoteButton.type = 'button';
|
||||
remoteButton.className = 'nav-row';
|
||||
remoteButton.textContent = 'Использовать ключ блокчейна с внешнего устройства';
|
||||
remoteButton.addEventListener('click', () => navigate('remote-addblock-session-view'));
|
||||
intro.append(historyButton, filesButton, remoteButton);
|
||||
screen.append(intro);
|
||||
return screen;
|
||||
}
|
||||
|
||||
const list = document.createElement('div');
|
||||
list.className = 'stack my-blockchain-list';
|
||||
list.hidden = false;
|
||||
screen.append(list);
|
||||
const more = document.createElement('button');
|
||||
more.type = 'button';
|
||||
|
||||
+1169
-1120
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,17 @@
|
||||
// Адаптер реальных данных → нейтральная модель движка force-графа.
|
||||
//
|
||||
// Источник — результат buildGraphModel() из network-view.js (он уже нормализует ответ
|
||||
// authService.getUserConnectionsGraph в роли/направления/метки). Здесь только конвертация
|
||||
// в форму, которую понимает движок ({ focusId, nodes[] }). Сервер не трогаем — это чтение.
|
||||
// Ответ сервера (после buildGraphModel в network-view.js) → люди и нити для карты связей.
|
||||
// Сервер не трогаем – только чтение.
|
||||
|
||||
function normLogin(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function normKey(value) {
|
||||
return normLogin(value).toLowerCase();
|
||||
}
|
||||
|
||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||
|
||||
function relationTypeFromRelation(relation) {
|
||||
export function relationTypeFromRelation(relation) {
|
||||
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
|
||||
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
|
||||
const role = relation?.role;
|
||||
@@ -19,60 +20,43 @@ function relationTypeFromRelation(relation) {
|
||||
return 'contact';
|
||||
}
|
||||
|
||||
// Сила связи (0..1) → радиус орбиты в движке. Реальный API пока не отдаёт численную силу,
|
||||
// поэтому выводим её эвристически из роли и направления связи:
|
||||
// - родственники держим ближе всего, контакты — дальше всего;
|
||||
// - взаимные дружеские связи ближе односторонних.
|
||||
function deriveStrength(relation) {
|
||||
if (relation.isRelative) return 0.9;
|
||||
if (relation?.mark?.relationType === 'close_friend') return 0.9;
|
||||
if (relation.role === 'contact') return 0.4;
|
||||
if (relation.forward && relation.backward) return 0.8;
|
||||
return 0.55;
|
||||
function personFromMark(login, mark) {
|
||||
return {
|
||||
id: normKey(login),
|
||||
login,
|
||||
name: mark?.displayName || login,
|
||||
firstName: mark?.firstName || '',
|
||||
lastName: mark?.lastName || '',
|
||||
avatar: mark?.avatar || null,
|
||||
shining: Boolean(mark?.shine),
|
||||
official: Boolean(mark?.official),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{centerLogin:string, centerMark:object|null, relations:Array}} graphModel
|
||||
* @returns {{focusId:string, nodes:Array}}
|
||||
* @returns {{ center: object, peers: Array<{ person: object, relationType: string, mutual: boolean, direction: string }> }}
|
||||
*/
|
||||
export function engineModelFromGraphModel(graphModel) {
|
||||
const focusLogin = normLogin(graphModel?.centerLogin);
|
||||
const centerMark = graphModel?.centerMark || null;
|
||||
|
||||
const focusNode = {
|
||||
id: focusLogin,
|
||||
login: focusLogin,
|
||||
name: centerMark?.displayName || centerMark?.login || focusLogin,
|
||||
avatar: centerMark?.avatar || null,
|
||||
relationType: 'self',
|
||||
strength: 1,
|
||||
shining: Boolean(centerMark?.shine),
|
||||
official: Boolean(centerMark?.official),
|
||||
tier: 1,
|
||||
};
|
||||
|
||||
const relations = Array.isArray(graphModel?.relations) ? graphModel.relations : [];
|
||||
const seen = new Set();
|
||||
const nodes = relations
|
||||
.map((r) => {
|
||||
const login = normLogin(r?.login);
|
||||
const key = login.toLowerCase();
|
||||
// исключаем сам фокус (не должно быть линии на собственный ник) и дубли
|
||||
if (!login || key === focusLogin.toLowerCase() || seen.has(key)) return null;
|
||||
seen.add(key);
|
||||
return {
|
||||
id: login,
|
||||
login,
|
||||
name: r?.mark?.displayName || login,
|
||||
avatar: r?.mark?.avatar || null,
|
||||
relationType: relationTypeFromRelation(r),
|
||||
strength: deriveStrength(r || {}),
|
||||
shining: Boolean(r?.mark?.shine),
|
||||
official: Boolean(r?.mark?.official),
|
||||
tier: 1,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return { focusId: focusLogin, nodes: [focusNode, ...nodes] };
|
||||
export function peopleFromGraphModel(graphModel) {
|
||||
const centerLogin = normLogin(graphModel?.centerLogin);
|
||||
const center = personFromMark(centerLogin, graphModel?.centerMark || null);
|
||||
const seen = new Set([center.id]);
|
||||
const peers = [];
|
||||
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
|
||||
const login = normLogin(relation?.login);
|
||||
const key = normKey(login);
|
||||
if (!login || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
const forward = Boolean(relation?.forward);
|
||||
const backward = Boolean(relation?.backward);
|
||||
peers.push({
|
||||
person: personFromMark(login, relation?.mark || null),
|
||||
relationType: relationTypeFromRelation(relation),
|
||||
// Пунктир на карте – связь только с одной стороны.
|
||||
mutual: forward && backward,
|
||||
// Со стороны центра: взаимно, только центр (out) или только этот человек (in – «ждёт ответа»).
|
||||
direction: forward && backward ? 'mutual' : (forward ? 'out' : 'in'),
|
||||
});
|
||||
}
|
||||
return { center, peers };
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,92 @@
|
||||
// Ручная раскладка карты связей и выбранный режим – на этом устройстве, отдельно для аккаунта.
|
||||
// Координаты хранятся относительно человека в центре карты: у каждой карты своя раскладка.
|
||||
import { state } from '../../state.js';
|
||||
|
||||
const LAYOUT_PREFIX = 'shine-network-layout-v1:';
|
||||
const VIEW_PREFIX = 'shine-network-view-v1:';
|
||||
const MAX_MAPS = 40; // старые раскладки вытесняются, чтобы хранилище не росло бесконечно
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function readJson(key) {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) || '{}');
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeJson(key, value) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// Нет места или приватный режим – раскладка проживёт до закрытия экрана.
|
||||
}
|
||||
}
|
||||
|
||||
export function getManualLayout(centerKey) {
|
||||
const owner = ownerLogin();
|
||||
const out = new Map();
|
||||
if (!owner || !centerKey) return out;
|
||||
const map = readJson(LAYOUT_PREFIX + owner)[centerKey]?.points || {};
|
||||
for (const [id, point] of Object.entries(map)) {
|
||||
if (Array.isArray(point) && Number.isFinite(point[0]) && Number.isFinite(point[1])) out.set(id, { x: point[0], y: point[1] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function setManualPoint(centerKey, id, point) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey || !id) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
const entry = all[centerKey] || { points: {} };
|
||||
entry.points[id] = [Math.round(point.x), Math.round(point.y)];
|
||||
entry.updatedAt = Date.now();
|
||||
all[centerKey] = entry;
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > MAX_MAPS) {
|
||||
keys.sort((a, b) => (all[a].updatedAt || 0) - (all[b].updatedAt || 0))
|
||||
.slice(0, keys.length - MAX_MAPS)
|
||||
.forEach((key) => { delete all[key]; });
|
||||
}
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
}
|
||||
|
||||
export function clearManualLayout(centerKey) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner || !centerKey) return;
|
||||
const all = readJson(LAYOUT_PREFIX + owner);
|
||||
delete all[centerKey];
|
||||
writeJson(LAYOUT_PREFIX + owner, all);
|
||||
}
|
||||
|
||||
export function getLayoutMode() {
|
||||
const owner = ownerLogin();
|
||||
return readJson(VIEW_PREFIX + owner).mode === 'groups' ? 'groups' : 'rings';
|
||||
}
|
||||
|
||||
export function setLayoutMode(mode) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view.mode = mode === 'groups' ? 'groups' : 'rings';
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
|
||||
// Прочие настройки экрана на этом устройстве: карта или список, порядок списка.
|
||||
export function getViewSetting(key, fallback) {
|
||||
const owner = ownerLogin();
|
||||
const value = readJson(VIEW_PREFIX + owner)[key];
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setViewSetting(key, value) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
const view = readJson(VIEW_PREFIX + owner);
|
||||
view[key] = value;
|
||||
writeJson(VIEW_PREFIX + owner, view);
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// Общее контекстное меню узла (долгое нажатие) для карты связей.
|
||||
// Рендерится в #modal-root (вне масштабируемого холста), позиционируется по экранному rect узла.
|
||||
// Используется и реальным путём (network-view.js), и лабораторией (lab.js).
|
||||
|
||||
const REL_RU = {
|
||||
family: 'Семья',
|
||||
friend: 'Друг',
|
||||
business: 'Бизнес',
|
||||
contact: 'Контакт',
|
||||
self: 'Вы',
|
||||
};
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
export function relationLabelRu(relationType) {
|
||||
return REL_RU[relationType] || 'Контакт';
|
||||
}
|
||||
|
||||
/**
|
||||
* Открывает контекстное меню узла.
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login - логин/идентификатор для заголовка
|
||||
* @param {string} opts.relationType - тип связи (для подписи)
|
||||
* @param {{x:number,y:number,rect?:DOMRect}} opts.point - экранная точка/rect узла
|
||||
* @param {Array<{label:string, onClick:Function, disabled?:boolean}>} opts.actions - пункты меню
|
||||
*/
|
||||
export function openNodeMenu({ login, displayName = '', relationType, point, actions = [] } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!(root instanceof HTMLElement)) return;
|
||||
|
||||
const itemsHtml = actions
|
||||
.map((a, i) => `<button class="ui-button fg-menu-item${a.disabled ? ' is-stub' : ''}" type="button" data-i="${i}" role="menuitem"${a.disabled ? ' disabled' : ''}>${escapeHtml(a.label)}</button>`)
|
||||
.join('');
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="fg-menu-overlay" id="fg-menu-overlay">
|
||||
<div class="fg-menu" id="fg-menu" role="menu">
|
||||
<div class="fg-menu-head">
|
||||
<span class="fg-menu-login">${escapeHtml(displayName || login)}</span>${displayName && displayName !== login ? `<small class="fg-menu-secondary-login">${escapeHtml(login)}</small>` : ''}
|
||||
<span class="fg-menu-rel">${escapeHtml(relationLabelRu(relationType))}</span>
|
||||
</div>
|
||||
${itemsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const overlay = root.querySelector('#fg-menu-overlay');
|
||||
const menu = root.querySelector('#fg-menu');
|
||||
if (!(overlay instanceof HTMLElement) || !(menu instanceof HTMLElement)) { root.innerHTML = ''; return; }
|
||||
|
||||
// позиционируем рядом с узлом по его экранному rect (синхронно, без rAF — он может троттлиться)
|
||||
const rect = point?.rect;
|
||||
const px = point?.x ?? (rect ? rect.left + rect.width / 2 : window.innerWidth / 2);
|
||||
const belowY = rect ? rect.bottom + 8 : (point?.y ?? 80);
|
||||
const mw = menu.offsetWidth;
|
||||
const mh = menu.offsetHeight;
|
||||
let left = px - mw / 2;
|
||||
left = Math.max(8, Math.min(left, window.innerWidth - mw - 8));
|
||||
let top = belowY;
|
||||
if (top + mh > window.innerHeight - 8) top = Math.max(8, (rect ? rect.top : belowY) - mh - 8);
|
||||
menu.style.left = `${left}px`;
|
||||
menu.style.top = `${top}px`;
|
||||
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
|
||||
menu.addEventListener('click', (e) => {
|
||||
const btn = e.target instanceof HTMLElement ? e.target.closest('[data-i]') : null;
|
||||
if (!(btn instanceof HTMLElement)) return;
|
||||
const idx = Number(btn.dataset.i);
|
||||
const action = actions[idx];
|
||||
if (!action || action.disabled) return;
|
||||
close();
|
||||
if (typeof action.onClick === 'function') action.onClick();
|
||||
});
|
||||
|
||||
return close;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// «Уведомления» в настройках: звук сообщений, разрешение системных уведомлений и чаты
|
||||
// «без звука». Всё – настройки этого устройства, сервер про них не знает.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { authService, getRememberedDmPeer, normalizeDmChatId, rememberDmPeer } from '../state.js';
|
||||
import {
|
||||
DM_CHAT_PREFS_EVENT, formatDmMuteUntil, getMutedDmChats, setDmChatMuted,
|
||||
} from '../services/dm-chat-prefs.js';
|
||||
import { DEVICE_PREFS_EVENT, getDevicePref, setDevicePref } from '../services/device-prefs.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
|
||||
export const pageMeta = { id: 'notification-settings-view', title: 'Уведомления' };
|
||||
|
||||
function permissionState() {
|
||||
if (typeof Notification === 'undefined') return 'unsupported';
|
||||
return Notification.permission; // granted | denied | default
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notification-settings-screen';
|
||||
let disposed = false;
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Уведомления',
|
||||
back: { onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
|
||||
const soundTitle = document.createElement('p');
|
||||
soundTitle.className = 'nav-list__title';
|
||||
soundTitle.textContent = 'Сообщения';
|
||||
const soundList = document.createElement('div');
|
||||
soundList.className = 'nav-list';
|
||||
const soundRow = document.createElement('label');
|
||||
soundRow.className = 'nav-row nav-row--switch';
|
||||
soundRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label">Звук в открытом приложении</span>
|
||||
<span class="nav-row__hint">Короткий сигнал о новом сообщении</span>
|
||||
</span>
|
||||
<input class="switch" type="checkbox" />
|
||||
`;
|
||||
const soundSwitch = soundRow.querySelector('input');
|
||||
soundSwitch.checked = getDevicePref('dmSound', true) !== false;
|
||||
soundSwitch.addEventListener('change', () => setDevicePref('dmSound', soundSwitch.checked));
|
||||
soundList.append(soundRow);
|
||||
|
||||
// Системные уведомления – когда приложение свёрнуто или закрыто.
|
||||
const systemList = document.createElement('div');
|
||||
systemList.className = 'nav-list';
|
||||
const systemRow = document.createElement('div');
|
||||
systemRow.className = 'nav-row nav-row--action';
|
||||
systemList.append(systemRow);
|
||||
|
||||
function renderSystemRow() {
|
||||
const permission = permissionState();
|
||||
const texts = {
|
||||
granted: ['Уведомления на устройстве', 'Разрешены: придут, даже когда приложение свёрнуто'],
|
||||
denied: ['Уведомления на устройстве', 'Запрещены. Разрешите их для этого сайта в настройках браузера'],
|
||||
default: ['Уведомления на устройстве', 'Пока не разрешены – без них не узнать о сообщении, когда приложение свёрнуто'],
|
||||
unsupported: ['Уведомления на устройстве', 'Этот браузер их не поддерживает'],
|
||||
};
|
||||
const [label, hint] = texts[permission] || texts.unsupported;
|
||||
systemRow.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label"></span>
|
||||
<span class="nav-row__hint"></span>
|
||||
</span>
|
||||
`;
|
||||
systemRow.querySelector('.nav-row__label').textContent = label;
|
||||
systemRow.querySelector('.nav-row__hint').textContent = hint;
|
||||
if (permission === 'default') {
|
||||
const allow = document.createElement('button');
|
||||
allow.type = 'button';
|
||||
allow.className = 'primary-btn nav-row__button';
|
||||
allow.textContent = 'Разрешить';
|
||||
allow.addEventListener('click', async () => {
|
||||
allow.disabled = true;
|
||||
try {
|
||||
const result = await Notification.requestPermission();
|
||||
if (result === 'granted') showToast('Уведомления разрешены');
|
||||
} catch {
|
||||
showToast('Не удалось запросить разрешение', { kind: 'error' });
|
||||
}
|
||||
if (!disposed) renderSystemRow();
|
||||
});
|
||||
systemRow.append(allow);
|
||||
}
|
||||
}
|
||||
renderSystemRow();
|
||||
|
||||
// Чаты «без звука»: кто и до какого времени; звук возвращается кнопкой в строке.
|
||||
const mutedTitle = document.createElement('p');
|
||||
mutedTitle.className = 'nav-list__title';
|
||||
const mutedList = document.createElement('div');
|
||||
mutedList.className = 'notification-settings-muted';
|
||||
const mutedEmpty = document.createElement('p');
|
||||
mutedEmpty.className = 'meta-muted appearance-hint';
|
||||
mutedEmpty.textContent = 'Нет. Выключить звук чата можно в его меню «•••» или долгим нажатием в списке чатов.';
|
||||
let peersRequested = false;
|
||||
|
||||
function mutedRow({ chatId, until }) {
|
||||
const peer = getRememberedDmPeer(chatId) || {};
|
||||
const fullName = [peer.firstName, peer.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
const login = peer.login || chatId;
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: fullName || login,
|
||||
firstName: peer.firstName,
|
||||
lastName: peer.lastName,
|
||||
avatar: peer.avatar || null,
|
||||
sub: [fullName ? `@${login}` : '', until ? formatDmMuteUntil(until) : 'навсегда'].filter(Boolean).join(' · '),
|
||||
onClick: () => navigate(`chat/${encodeURIComponent(normalizeDmChatId(chatId))}`),
|
||||
actions: [{ icon: 'bell', label: 'Включить звук', onClick: () => setDmChatMuted(chatId, false) }],
|
||||
});
|
||||
}
|
||||
|
||||
// Имена и аватары – из списка чатов; если его в этот раз не открывали, спрашиваем сервер один раз.
|
||||
async function loadPeers() {
|
||||
peersRequested = true;
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
if (disposed) return;
|
||||
(Array.isArray(payload?.dialogs) ? payload.dialogs : []).forEach((dialog) => rememberDmPeer({
|
||||
login: dialog?.peerLogin,
|
||||
firstName: dialog?.firstName,
|
||||
lastName: dialog?.lastName,
|
||||
avatar: dialog?.avatar,
|
||||
}));
|
||||
renderMuted();
|
||||
} catch {
|
||||
// Без имён строки остаются с логинами – этого достаточно.
|
||||
}
|
||||
}
|
||||
|
||||
function renderMuted() {
|
||||
const muted = getMutedDmChats();
|
||||
mutedTitle.textContent = muted.length ? `Чаты без звука · ${muted.length}` : 'Чаты без звука';
|
||||
mutedList.hidden = !muted.length;
|
||||
mutedEmpty.hidden = Boolean(muted.length);
|
||||
mutedList.replaceChildren(...muted.map(mutedRow));
|
||||
if (!peersRequested && muted.some(({ chatId }) => !getRememberedDmPeer(chatId))) void loadPeers();
|
||||
}
|
||||
renderMuted();
|
||||
|
||||
const onPrefs = () => { if (!disposed) renderMuted(); };
|
||||
const onDevicePrefs = () => { if (!disposed) soundSwitch.checked = getDevicePref('dmSound', true) !== false; };
|
||||
window.addEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.addEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
|
||||
screen.append(soundTitle, soundList, systemList, mutedTitle, mutedList, mutedEmpty);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, onPrefs);
|
||||
window.removeEventListener(DEVICE_PREFS_EVENT, onDevicePrefs);
|
||||
};
|
||||
return screen;
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||
import { formatListTime } from '../services/channels-ux.js';
|
||||
import { formatListTime, showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
|
||||
const CONNECTION_CLOSE_FRIEND = 10;
|
||||
@@ -137,15 +139,15 @@ async function enrichItem(item, activeTab) {
|
||||
}
|
||||
|
||||
function renderEmpty(activeTab) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'stack notification-empty-state';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
||||
const text = document.createElement('p');
|
||||
text.className = 'meta-muted';
|
||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.';
|
||||
card.append(title, text);
|
||||
return card;
|
||||
return createStateMessage({
|
||||
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||||
title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
|
||||
text: activeTab === 'events'
|
||||
? 'Подписки и отписки от ваших каналов появятся здесь.'
|
||||
: activeTab === 'connections'
|
||||
? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
|
||||
: 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
|
||||
});
|
||||
}
|
||||
|
||||
function renderAvatar(item) {
|
||||
@@ -280,6 +282,21 @@ function renderItem(item, activeTab, navigate) {
|
||||
return row;
|
||||
}
|
||||
|
||||
// Профиль и счётчики пришли позже – обновляем строку на месте (наблюдение «прочитано» не теряется).
|
||||
function refreshItemRow(row, item, activeTab) {
|
||||
if (!row?.isConnected) return;
|
||||
row.querySelector('.notification-avatar')?.replaceWith(renderAvatar(item));
|
||||
const name = row.querySelector('.notification-card__name');
|
||||
if (name) name.textContent = renderHead(item).querySelector('.notification-card__name').textContent;
|
||||
if (activeTab === 'replies' && item.engagement && !row.querySelector('.notification-engagement')) {
|
||||
const engagement = renderEngagement(item.engagement);
|
||||
if (engagement) row.querySelector('.notification-card__body')?.append(engagement);
|
||||
}
|
||||
}
|
||||
|
||||
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
|
||||
let lastNotifications = null;
|
||||
|
||||
export function render({ navigate, chrome } = {}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack notifications-screen';
|
||||
@@ -289,10 +306,20 @@ export function render({ navigate, chrome } = {}) {
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||
chrome?.setTopbar(createTopBar({
|
||||
const topbar = createTopBar({
|
||||
title: 'Уведомления',
|
||||
className: 'topbar--root notifications-topbar',
|
||||
}));
|
||||
actions: [{
|
||||
icon: 'check-double',
|
||||
title: 'Прочитать все',
|
||||
ariaLabel: 'Отметить все уведомления прочитанными',
|
||||
className: 'notifications-read-all',
|
||||
onClick: () => { void markAllRead(); },
|
||||
}],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
const readAllBtn = topbar.querySelector('.notifications-read-all');
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
screen.append(tabs);
|
||||
|
||||
const list = document.createElement('div');
|
||||
@@ -314,6 +341,7 @@ export function render({ navigate, chrome } = {}) {
|
||||
function updateToolbarBadge(payload) {
|
||||
const c = countsFromPayload(payload);
|
||||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||||
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
|
||||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||||
if (!btn) return;
|
||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||
@@ -363,32 +391,148 @@ export function render({ navigate, chrome } = {}) {
|
||||
}, 350);
|
||||
}
|
||||
|
||||
let renderSeq = 0;
|
||||
async function renderCurrent() {
|
||||
const seq = ++renderSeq;
|
||||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
||||
const tab=state.notificationsTab; const {items:raw,seenAt}=categoryData(payloadCache || {},tab); localSeen[tab]=Math.max(localSeen[tab]||0,seenAt);
|
||||
const base=raw.map(normalizeItem); if(!base.length){list.replaceChildren(renderEmpty(tab));return;}
|
||||
const items=await Promise.all(base.map(x=>enrichItem(x,tab)));
|
||||
// Список рисуется сразу – с профилями из кэша; остальное догружается в фоне и
|
||||
// обновляет строки на месте (раньше экран ждал загрузки профиля каждого автора).
|
||||
const items=base.map((x)=>({ ...x, profile: profileSnapshotCache.get(String(x.sourceLogin || '').toLowerCase()) || null }));
|
||||
const rowByItem = new Map();
|
||||
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||||
const nodes=[];
|
||||
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
|
||||
if(unread.length) nodes.push(groupTitle(`Новые · ${unread.length}`));
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);nodes.push(n);});
|
||||
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);rowByItem.set(x,n);nodes.push(n);});
|
||||
if(unread.length && old.length) nodes.push(groupTitle('Ранее'));
|
||||
old.forEach(x=>nodes.push(renderItem(x,tab,navigate))); list.replaceChildren(...nodes);
|
||||
old.forEach(x=>{const n=renderItem(x,tab,navigate);rowByItem.set(x,n);nodes.push(n);}); list.replaceChildren(...nodes);
|
||||
void enrichInBackground(items, tab, rowByItem, seq);
|
||||
if (tab === 'connections') void offerFriendBack(items, rowByItem, seq);
|
||||
if(unread.length && 'IntersectionObserver' in window){
|
||||
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
|
||||
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
|
||||
}
|
||||
}
|
||||
|
||||
// «Добавил(а) вас в друзья», а вы ещё нет – кнопка «Дружить в ответ» прямо в уведомлении.
|
||||
// Кто у вас уже в друзьях – из одного запроса своего графа связей.
|
||||
async function offerFriendBack(items, rowByItem, seq) {
|
||||
const self = String(state.session.login || '').trim();
|
||||
const candidates = items.filter((x) => [CONNECTION_FRIEND, CONNECTION_CLOSE_FRIEND].includes(Number(x.connectionTypeCode ?? x.sourceMsgSubType)));
|
||||
if (!self || !candidates.length) return;
|
||||
let graph;
|
||||
try { graph = await authService.getUserConnectionsGraph(self); } catch { return; }
|
||||
if (seq !== renderSeq) return;
|
||||
const mine = new Set([...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])].map((login) => String(login).toLowerCase()));
|
||||
const offered = new Set();
|
||||
for (const item of candidates) {
|
||||
const login = String(item.sourceLogin || '').trim();
|
||||
const key = login.toLowerCase();
|
||||
// Одна кнопка на человека – у самого свежего уведомления.
|
||||
if (!login || mine.has(key) || offered.has(key)) continue;
|
||||
offered.add(key);
|
||||
const row = rowByItem.get(item);
|
||||
const body = row?.querySelector('.notification-card__body');
|
||||
if (!body) continue;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'secondary-btn notification-card__answer';
|
||||
button.textContent = 'Дружить в ответ';
|
||||
button.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
button.disabled = true;
|
||||
button.textContent = 'Сохраняю…';
|
||||
try {
|
||||
await authService.setUserRelation({ login: self, toLogin: login, kind: 'friend', enabled: true, storagePwd: state.session.storagePwdInMemory });
|
||||
const done = document.createElement('span');
|
||||
done.className = 'notification-card__answered';
|
||||
done.innerHTML = `${iconHtml('check')}<span>Вы друзья</span>`;
|
||||
button.replaceWith(done);
|
||||
showToast('Теперь вы друзья');
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
button.textContent = 'Дружить в ответ';
|
||||
showToast(toUserMessage(error, 'Не удалось добавить в друзья.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
body.append(button);
|
||||
}
|
||||
}
|
||||
|
||||
async function enrichInBackground(items, tab, rowByItem, seq) {
|
||||
let cursor = 0;
|
||||
const worker = async () => {
|
||||
while (cursor < items.length) {
|
||||
const item = items[cursor++];
|
||||
const needProfile = !item.profile;
|
||||
if (!needProfile && tab !== 'replies') continue;
|
||||
const enriched = await enrichItem(item, tab);
|
||||
if (seq !== renderSeq) return;
|
||||
refreshItemRow(rowByItem.get(item), enriched, tab);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: 6 }, worker));
|
||||
}
|
||||
|
||||
async function markAllRead() {
|
||||
if (!payloadCache) return;
|
||||
const jobs = ['replies', 'connections', 'events'].map((category) => {
|
||||
const { items, seenAt } = categoryData(payloadCache, category);
|
||||
const maxTs = items.reduce((max, x) => Math.max(max, Number(x?.createdAtMs || 0)), 0);
|
||||
return { category, maxTs, seenAt };
|
||||
}).filter((job) => job.maxTs > job.seenAt);
|
||||
if (!jobs.length) return;
|
||||
if (readAllBtn) readAllBtn.disabled = true;
|
||||
try {
|
||||
for (const job of jobs) {
|
||||
await authService.setNotificationSeen({ login: state.session.login, category: job.category, seenAtMs: job.maxTs, storagePwd: state.session.storagePwdInMemory });
|
||||
const seenKey = job.category === 'connections' ? 'connectionsSeenAtMs' : job.category === 'events' ? 'eventsSeenAtMs' : 'repliesSeenAtMs';
|
||||
const countKey = job.category === 'connections' ? 'connectionsUnseenCount' : job.category === 'events' ? 'eventsUnseenCount' : 'repliesUnseenCount';
|
||||
payloadCache[seenKey] = job.maxTs;
|
||||
payloadCache[countKey] = 0;
|
||||
localSeen[job.category] = Math.max(localSeen[job.category] || 0, job.maxTs);
|
||||
}
|
||||
if (lastNotifications?.payload) lastNotifications = { ...lastNotifications, payload: structuredClone(payloadCache), signature: '' };
|
||||
updateToolbarBadge(payloadCache);
|
||||
await renderCurrent();
|
||||
showToast('Все уведомления прочитаны');
|
||||
} catch (error) {
|
||||
updateToolbarBadge(payloadCache);
|
||||
showToast(toUserMessage(error, 'Не удалось отметить уведомления прочитанными.'), { kind: 'error' });
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
||||
catch(error){ if(seq!==requestSeq)return; const card=document.createElement('article');card.className='card stack';card.innerHTML='<strong>Не удалось загрузить уведомления</strong>';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);}
|
||||
const seq=++requestSeq;
|
||||
const login = state.session.login;
|
||||
const cached = lastNotifications?.login === login ? lastNotifications : null;
|
||||
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
|
||||
else { renderTabs({}); if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю уведомления' })); }
|
||||
try {
|
||||
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
|
||||
const signature = JSON.stringify(fresh);
|
||||
lastNotifications = { login, payload: structuredClone(fresh), signature };
|
||||
updateToolbarBadge(fresh);
|
||||
if (cached?.signature === signature) return;
|
||||
payloadCache=fresh; await renderCurrent();
|
||||
}
|
||||
catch(error){
|
||||
if(seq!==requestSeq)return;
|
||||
if (payloadCache) { showToast(toUserMessage(error, 'Не удалось обновить уведомления.'), { kind: 'error' }); return; }
|
||||
list.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить уведомления',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { list.replaceChildren(); void load(); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||||
screen.cleanup = () => {
|
||||
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
|
||||
requestSeq += 1;
|
||||
observer?.disconnect();
|
||||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||||
};
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { profile } from '../mock-data.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import {
|
||||
@@ -34,10 +36,10 @@ function shineStatusLabel(value) {
|
||||
return 'Не указано';
|
||||
}
|
||||
|
||||
// Ошибка – понятным сообщением внизу экрана, а не окном со стеком вызовов
|
||||
// (подробности остаются в журнале приложения).
|
||||
function showLocalErrorAlert(prefix, error) {
|
||||
const message = error?.message || 'Неизвестная ошибка';
|
||||
const stack = error?.stack ? `\n\nStack:\n${error.stack}` : '';
|
||||
window.alert(`${prefix}: ${message}${stack}`);
|
||||
showToast(`${prefix}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`, { kind: 'error' });
|
||||
}
|
||||
|
||||
function genderLabel(value) {
|
||||
@@ -241,7 +243,8 @@ export function render({ navigate, chrome }) {
|
||||
? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), sha256Hex: String(currentAvatar?.sha256Hex || '').trim().toLowerCase() }
|
||||
: null,
|
||||
size: 'xl',
|
||||
className: 'profile-avatar',
|
||||
// Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана.
|
||||
className: 'profile-avatar avatar-plain',
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -627,7 +630,7 @@ export function render({ navigate, chrome }) {
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось загрузить параметры: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка загрузки параметров профиля', error);
|
||||
showLocalErrorAlert('Не удалось загрузить профиль', error);
|
||||
} finally {
|
||||
reloadBtn.disabled = false;
|
||||
accountRoleBtn.disabled = false;
|
||||
@@ -691,8 +694,9 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить ${statusKey}: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert(`Ошибка изменения ${statusKey}`, error);
|
||||
const what = isAccountRole ? 'тип аккаунта' : 'сияние';
|
||||
status.textContent = `Не удалось изменить ${what}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert(`Не удалось изменить ${what}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -709,7 +713,7 @@ export function render({ navigate, chrome }) {
|
||||
});
|
||||
if (entered === null) return;
|
||||
if (String(entered).length > Number(field.maxLength || 300)) {
|
||||
window.alert(`Максимальная длина поля «${field.label}» – ${Number(field.maxLength || 300)} символов.`);
|
||||
showToast(`В поле «${field.label}» – не больше ${Number(field.maxLength || 300)} символов.`, { kind: 'info' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -721,8 +725,8 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить ${field.key}: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert(`Ошибка изменения ${field.key}`, error);
|
||||
status.textContent = `Не удалось изменить поле «${field.label}». ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert(`Не удалось изменить поле «${field.label}»`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -738,15 +742,15 @@ export function render({ navigate, chrome }) {
|
||||
await refreshProfileSnapshot();
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось изменить пол: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка изменения пола', error);
|
||||
status.textContent = `Не удалось изменить пол. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||
showLocalErrorAlert('Не удалось изменить пол', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function onAddRelativeClick() {
|
||||
const sessionLogin = String(login || '').trim();
|
||||
if (!sessionLogin) {
|
||||
window.alert('Для добавления связи нужен активный логин.');
|
||||
showToast('Для добавления связи нужен вход в аккаунт.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -786,7 +790,7 @@ export function render({ navigate, chrome }) {
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Пользователь не найден: ${error.message || 'unknown'}`;
|
||||
showLocalErrorAlert('Ошибка выбора пользователя', error);
|
||||
showLocalErrorAlert('Не удалось выбрать пользователя', error);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -817,7 +821,7 @@ export function render({ navigate, chrome }) {
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Не удалось добавить связь: ${error.message || 'ошибка сети'}`;
|
||||
showLocalErrorAlert('Ошибка добавления связи', error);
|
||||
showLocalErrorAlert('Не удалось добавить связь', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,30 +4,47 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { openShareSheet } from '../components/share-sheet.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
||||
|
||||
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
||||
const cardCache = new Map();
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const login = String(state.session.login || profile.login || '').trim();
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack user-profile-screen';
|
||||
|
||||
// Ссылка на свой профиль – самое частое «поделиться» в соцсети.
|
||||
const shareProfile = () => {
|
||||
const url = new URL(window.location.href);
|
||||
url.pathname = `/${makeProfileRoute(login)}`;
|
||||
url.search = '';
|
||||
url.hash = '';
|
||||
const name = [card?.firstName, card?.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||
openShareSheet({ title: 'Поделиться профилем', kicker: name ? `${name} · @${login}` : `@${login}`, text: 'Профиль в Сиянии', url: url.toString() });
|
||||
};
|
||||
const topbar = createTopBar({
|
||||
title: 'Профиль',
|
||||
className: 'topbar--root user-profile-header',
|
||||
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
|
||||
});
|
||||
chrome?.setTopbar(topbar);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line user-profile-status';
|
||||
status.textContent = 'Загрузка профиля...';
|
||||
status.className = 'user-profile-status';
|
||||
let card = cardCache.get(login.toLowerCase()) || null;
|
||||
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
||||
if (!card) status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let card = null;
|
||||
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
body.innerHTML = profileCardHtml({
|
||||
@@ -51,9 +68,10 @@ export function render({ navigate, chrome }) {
|
||||
avatar: card.avatar,
|
||||
size: 'xl',
|
||||
className: 'user-profile-hero-avatar',
|
||||
official: card.accountRole === 'primary',
|
||||
}));
|
||||
|
||||
status.textContent = '';
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
@@ -83,14 +101,29 @@ export function render({ navigate, chrome }) {
|
||||
status.textContent = 'Локальный тестовый режим.';
|
||||
return;
|
||||
}
|
||||
card = await loadUserProfileCard(login);
|
||||
const fresh = await loadUserProfileCard(login);
|
||||
if (!screen.isConnected && card) return;
|
||||
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
||||
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
||||
card = fresh;
|
||||
cardCache.set(login.toLowerCase(), card);
|
||||
renderProfile();
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line user-profile-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
||||
});
|
||||
renderProfile();
|
||||
|
||||
const showLoadError = (error) => {
|
||||
if (card) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить профиль',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
||||
'Ключ восстановления (Recovery key) нужен для восстановления и самых критичных операций с учётной записью. Его приватная часть никогда не сохраняется на устройстве и при необходимости временно вычисляется из пароля.',
|
||||
'Ключ блокчейна постоянно хранится на авторизованном устройстве. Он подписывает записи и действия в блокчейне Сияния и является исходным ключом для штатных пользовательских кошельков.',
|
||||
'Ключ доступа (client key) также постоянно хранится на устройстве. Он используется для входа на сервер, работы устройства и защищённых личных сообщений.',
|
||||
'Сейчас после обычного входа оба рабочих ключа — ключ блокчейна и ключ доступа — сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
||||
'Сейчас после обычного входа оба рабочих ключа – ключ блокчейна и ключ доступа – сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import {
|
||||
isSessionInvalidError,
|
||||
refreshSessions,
|
||||
@@ -35,7 +37,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'AddBlock через homeserver',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
back: { label: '←', onClick: () => navigate('my-blockchain-view') },
|
||||
}));
|
||||
|
||||
const actions = document.createElement('div');
|
||||
@@ -95,7 +97,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
listCard.append(item);
|
||||
@@ -115,7 +117,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -135,7 +137,7 @@ export function render({navigate, chrome}) {
|
||||
return;
|
||||
}
|
||||
setAuthError(error.message);
|
||||
window.alert(error.message);
|
||||
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import { authService } from '../state.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderAvatar } from '../components/avatar-image.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { makeShineChannelRoute, makeProfileRoute } from '../services/shine-routes.js';
|
||||
|
||||
export const pageMeta = {
|
||||
id: 'search-view',
|
||||
title: 'Поиск SHiNE',
|
||||
shellMode: { contentWidth: 'wide', topFade: false },
|
||||
};
|
||||
|
||||
const SEARCH_DELAY_MS = 280;
|
||||
|
||||
function channelRow(item, navigate) {
|
||||
const row = document.createElement('button');
|
||||
row.type = 'button';
|
||||
row.className = 'shine-search-result';
|
||||
const displayName = String(item.displayName || item.slug || 'Канал').trim();
|
||||
const ownerLogin = String(item.ownerLogin || '').trim();
|
||||
const slug = String(item.slug || '').trim();
|
||||
row.append(renderAvatar({
|
||||
initials: Array.from(displayName)[0] || '#',
|
||||
avatar: item.avatarAr || item.avatarSha256
|
||||
? { ar: item.avatarAr || '', sha256Hex: item.avatarSha256 || '' }
|
||||
: null,
|
||||
authorLogin: ownerLogin,
|
||||
size: 'lg',
|
||||
className: 'avatar-plain',
|
||||
title: displayName,
|
||||
alt: 'Аватар канала',
|
||||
}));
|
||||
const text = document.createElement('span');
|
||||
text.className = 'shine-search-result__text';
|
||||
const title = document.createElement('strong');
|
||||
title.className = 'shine-search-result__title';
|
||||
title.textContent = displayName;
|
||||
const address = document.createElement('span');
|
||||
address.className = 'shine-search-result__address';
|
||||
address.textContent = `@${ownerLogin}/${slug} · ${Number(item.subscribersCount || 0)} подписчиков`;
|
||||
text.append(title, address);
|
||||
const description = String(item.description || '').trim();
|
||||
if (description) {
|
||||
const desc = document.createElement('span');
|
||||
desc.className = 'shine-search-result__description';
|
||||
desc.textContent = description;
|
||||
text.append(desc);
|
||||
}
|
||||
row.append(text);
|
||||
row.addEventListener('click', () => {
|
||||
const route = makeShineChannelRoute({
|
||||
ownerLogin,
|
||||
ownerBlockchainName: String(item.ownerBlockchainName || '').trim(),
|
||||
channelName: slug,
|
||||
});
|
||||
if (route) navigate(route);
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
// Человек в результатах – той же строкой, что в Связях и чатах; «Написать» – сразу отсюда.
|
||||
function personRow(person, navigate) {
|
||||
const login = String(person?.login || '').trim();
|
||||
const displayName = String(person?.displayName || '').trim();
|
||||
return createPersonRow({
|
||||
login,
|
||||
name: displayName || login,
|
||||
avatar: person.avatarAr ? { ar: person.avatarAr } : null,
|
||||
sub: displayName && displayName !== login ? `@${login}` : '',
|
||||
onClick: () => navigate(makeProfileRoute(login)),
|
||||
actions: [{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack shine-search-screen';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Поиск SHiNE',
|
||||
back: { label: '←', onClick: () => navigate('channels-list') },
|
||||
}));
|
||||
|
||||
const search = document.createElement('input');
|
||||
search.type = 'search';
|
||||
search.className = 'search-field__input shine-search-input';
|
||||
search.placeholder = 'Название канала, @автор или автор/канал';
|
||||
search.maxLength = 120;
|
||||
search.autocomplete = 'off';
|
||||
search.enterKeyHint = 'search';
|
||||
search.setAttribute('aria-label', 'Поиск по всей сети SHiNE');
|
||||
const initialQuery = new URLSearchParams(window.location.search).get('q') || '';
|
||||
search.value = initialQuery;
|
||||
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs tabs--three shine-search-tabs';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
const buttons = [['all', 'Все'], ['channels', 'Каналы'], ['people', 'Люди']].map(([id, label]) => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'tab-btn shine-search-tab';
|
||||
btn.textContent = label;
|
||||
btn.dataset.tab = id;
|
||||
btn.setAttribute('role', 'radio');
|
||||
btn.setAttribute('aria-checked', String(id === 'all'));
|
||||
tabs.append(btn);
|
||||
return btn;
|
||||
});
|
||||
|
||||
// Подсказка и итог – одной строкой; загрузка и «ничего не найдено» – общим видом в списке.
|
||||
const status = document.createElement('p');
|
||||
status.className = 'shine-search-status';
|
||||
status.setAttribute('role', 'status');
|
||||
status.textContent = 'Введите имя канала, его адрес или логин пользователя.';
|
||||
const field = document.createElement('label');
|
||||
field.className = 'search-field shine-search-field';
|
||||
field.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
||||
const list = document.createElement('div');
|
||||
list.className = 'shine-search-results';
|
||||
|
||||
let selectedTab = 'all';
|
||||
let channels = [];
|
||||
let people = [];
|
||||
let error = '';
|
||||
let timer = null;
|
||||
let seq = 0;
|
||||
let disposed = false;
|
||||
|
||||
const appendSection = (title, items, factory) => {
|
||||
if (!items.length) return;
|
||||
const header = document.createElement('h3');
|
||||
header.className = 'shine-search-section-heading';
|
||||
header.textContent = `${title} · ${items.length}`;
|
||||
list.append(header);
|
||||
items.forEach((item) => list.append(factory(item, navigate)));
|
||||
};
|
||||
|
||||
const renderResults = () => {
|
||||
buttons.forEach((button) => {
|
||||
button.setAttribute('aria-checked', String(button.dataset.tab === selectedTab));
|
||||
});
|
||||
list.replaceChildren();
|
||||
const query = search.value.trim();
|
||||
if (!query) {
|
||||
status.textContent = 'Введите имя канала, его адрес или логин пользователя.';
|
||||
return;
|
||||
}
|
||||
if (selectedTab !== 'people') appendSection('Каналы', channels, channelRow);
|
||||
if (selectedTab !== 'channels') appendSection('Люди', people, personRow);
|
||||
const shown = (selectedTab === 'people' ? people.length
|
||||
: selectedTab === 'channels' ? channels.length : channels.length + people.length);
|
||||
status.textContent = '';
|
||||
if (error && !shown) {
|
||||
list.append(createStateMessage({ kind: 'error', icon: 'alert', title: 'Поиск не удался', text: error }));
|
||||
} else if (!shown) {
|
||||
list.append(createStateMessage({ icon: 'search', title: 'Ничего не найдено', text: 'Попробуйте другое название или логин.' }));
|
||||
}
|
||||
};
|
||||
|
||||
const runSearch = async () => {
|
||||
const query = search.value.trim();
|
||||
const currentSeq = ++seq;
|
||||
if (!query) {
|
||||
channels = []; people = []; error = '';
|
||||
renderResults();
|
||||
return;
|
||||
}
|
||||
status.textContent = '';
|
||||
if (!list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Ищу' }));
|
||||
const userQuery = query.replace(/^@/, '').trim();
|
||||
const requests = [authService.searchChannels(query, { limit: 10 })];
|
||||
if (userQuery && !userQuery.includes('/')) requests.push(authService.searchPeople(userQuery, { limit: 10 }));
|
||||
const results = await Promise.allSettled(requests);
|
||||
if (disposed || currentSeq !== seq) return;
|
||||
channels = results[0].status === 'fulfilled' ? results[0].value : [];
|
||||
people = results[1]?.status === 'fulfilled' ? results[1].value : [];
|
||||
error = results.every((result) => result.status === 'rejected')
|
||||
? 'Не удалось выполнить поиск. Проверьте подключение к серверу.'
|
||||
: '';
|
||||
renderResults();
|
||||
};
|
||||
|
||||
const rememberQueryInAddress = () => {
|
||||
const url = new URL(window.location.href);
|
||||
if (search.value.trim()) url.searchParams.set('q', search.value.trim());
|
||||
else url.searchParams.delete('q');
|
||||
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
};
|
||||
const scheduleSearch = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
++seq; // Устаревший ответ не должен подменить новый ввод.
|
||||
channels = []; people = []; error = '';
|
||||
// Прежние результаты остаются до прихода новых – без мелькания на каждую букву.
|
||||
if (!search.value.trim()) list.replaceChildren();
|
||||
status.textContent = search.value.trim() ? '' : 'Введите название или адрес.';
|
||||
rememberQueryInAddress();
|
||||
timer = setTimeout(() => { timer = null; void runSearch(); }, SEARCH_DELAY_MS);
|
||||
};
|
||||
search.addEventListener('input', scheduleSearch);
|
||||
search.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
void runSearch();
|
||||
}
|
||||
});
|
||||
buttons.forEach((btn) => btn.addEventListener('click', () => {
|
||||
selectedTab = btn.dataset.tab;
|
||||
renderResults();
|
||||
}));
|
||||
field.append(search);
|
||||
screen.append(field, tabs, status, list);
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
++seq;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
if (initialQuery.trim()) void runSearch();
|
||||
return screen;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { saveEntrySettings, state } from '../state.js';
|
||||
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
||||
|
||||
@@ -163,7 +165,7 @@ export function render({navigate, chrome}) {
|
||||
cancelButton.className = 'ghost-btn';
|
||||
cancelButton.type = 'button';
|
||||
cancelButton.textContent = 'Отмена';
|
||||
cancelButton.addEventListener('click', () => navigate('settings-view'));
|
||||
cancelButton.addEventListener('click', () => navigate('settings-servers-view'));
|
||||
|
||||
const saveButton = document.createElement('button');
|
||||
saveButton.className = 'primary-btn';
|
||||
@@ -172,9 +174,9 @@ export function render({navigate, chrome}) {
|
||||
saveButton.addEventListener('click', async () => {
|
||||
try {
|
||||
await saveEntrySettings(draft);
|
||||
navigate('settings-view');
|
||||
navigate('settings-servers-view');
|
||||
} catch (error) {
|
||||
window.alert(error?.message || 'Не удалось сохранить настройки серверов блокчейнов.');
|
||||
showToast(toUserMessage(error, 'Не удалось сохранить настройки серверов блокчейнов.'), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -192,7 +194,7 @@ export function render({navigate, chrome}) {
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Серверы блокчейнов',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||
}));
|
||||
screen.append(
|
||||
introCard,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
|
||||
export const pageMeta = { id: 'settings-servers-view', title: 'Настройки серверов' };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Настройки серверов',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
const list = document.createElement('div');
|
||||
list.className = 'nav-list';
|
||||
const entries = [
|
||||
['Мой сервер доступа', 'access-servers-view'],
|
||||
['Серверы блокчейнов', 'server-settings-view'],
|
||||
];
|
||||
for (const [label, pageId] of entries) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'nav-row';
|
||||
button.innerHTML = `<span class="nav-row__label">${label}</span>`;
|
||||
button.addEventListener('click', () => navigate(pageId));
|
||||
list.append(button);
|
||||
}
|
||||
screen.append(list);
|
||||
return screen;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||
import { isDeveloperToolsEnabled } from '../services/feature-settings.js';
|
||||
import { getThemeMode, resolveThemeMode, setThemeMode } from '../services/theme-service.js';
|
||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
||||
import { openSheet } from '../components/sheet.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { PALETTE_PRESETS, getPaletteSettings, getThemeMode } from '../services/theme-service.js';
|
||||
import {
|
||||
canInstallPwa,
|
||||
isStandalonePwaMode,
|
||||
@@ -13,32 +13,90 @@ import {
|
||||
|
||||
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
||||
|
||||
// Номер сборки вида 20261013040000 – это дата и время: показываем «13.10.2026, 04:00».
|
||||
function formatBuildStamp(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!/^\d{14}$/.test(value)) return value;
|
||||
const yyyy = value.slice(0, 4);
|
||||
const mm = value.slice(4, 6);
|
||||
const dd = value.slice(6, 8);
|
||||
const hh = value.slice(8, 10);
|
||||
const min = value.slice(10, 12);
|
||||
const ss = value.slice(12, 14);
|
||||
return `${yyyy}-${mm}-${dd}/${hh}:${min}__${ss}`;
|
||||
return `${value.slice(6, 8)}.${value.slice(4, 6)}.${value.slice(0, 4)}, ${value.slice(8, 10)}:${value.slice(10, 12)}`;
|
||||
}
|
||||
|
||||
function formatVersionForUi(rawValue) {
|
||||
const value = String(rawValue || '').trim();
|
||||
if (!value) return 'n/a';
|
||||
const formatted = formatBuildStamp(value);
|
||||
if (formatted && formatted !== value) {
|
||||
return `${formatted} (${value})`;
|
||||
}
|
||||
if (formatted && formatted !== value) return formatted;
|
||||
return value;
|
||||
}
|
||||
|
||||
// Сервер отвечает версией на Ping (или GetServerInfo у старых серверов).
|
||||
async function loadServerVersion() {
|
||||
try {
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
const value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
|
||||
if (value) return value;
|
||||
} catch {
|
||||
// ниже – запасной запрос
|
||||
}
|
||||
const infoResp = await authService.ws.request('GetServerInfo', {});
|
||||
return String(infoResp?.payload?.version || '').trim();
|
||||
}
|
||||
|
||||
// «О приложении»: версии клиента, сборки и сервера – и кнопка скопировать их для поддержки.
|
||||
function openAboutSheet() {
|
||||
let disposed = false;
|
||||
return openSheet({
|
||||
title: 'О приложении',
|
||||
className: 'about-sheet',
|
||||
onClose: () => { disposed = true; },
|
||||
content: () => {
|
||||
const list = document.createElement('div');
|
||||
list.className = 'nav-list';
|
||||
const rows = [
|
||||
['Версия приложения', formatVersionForUi(window.__SHINE_CLIENT_VERSION__)],
|
||||
['Сборка', formatVersionForUi(window.__SHINE_BUILD_HASH__)],
|
||||
['Сервер', 'Узнаю…'],
|
||||
['Сервер доступа', String(state.entrySettings?.shineServerLogin || '').trim() || '—'],
|
||||
];
|
||||
const values = rows.map(([label, value]) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'nav-row nav-row--static';
|
||||
row.innerHTML = '<span class="nav-row__hint"></span><span class="nav-row__label"></span>';
|
||||
row.querySelector('.nav-row__hint').textContent = label;
|
||||
row.querySelector('.nav-row__label').textContent = value;
|
||||
list.append(row);
|
||||
return row.querySelector('.nav-row__label');
|
||||
});
|
||||
void loadServerVersion()
|
||||
.then((value) => { if (!disposed) values[2].textContent = formatVersionForUi(value) || '—'; })
|
||||
.catch(() => { if (!disposed) values[2].textContent = 'Нет связи с сервером'; });
|
||||
const copy = document.createElement('button');
|
||||
copy.type = 'button';
|
||||
copy.className = 'secondary-btn about-sheet__copy';
|
||||
copy.textContent = 'Скопировать сведения';
|
||||
copy.addEventListener('click', async () => {
|
||||
const text = rows.map(([label], index) => `${label}: ${values[index].textContent}`).join('\n');
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast('Сведения скопированы');
|
||||
} catch {
|
||||
showToast('Не удалось скопировать', { kind: 'error' });
|
||||
}
|
||||
});
|
||||
const box = document.createElement('div');
|
||||
box.className = 'stack';
|
||||
box.append(list, copy);
|
||||
return box;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const THEME_LABELS = { system: 'авто', light: 'светлая', dark: 'тёмная' };
|
||||
|
||||
export function render({navigate, chrome}) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
let isDisposed = false;
|
||||
let aboutSheet = null;
|
||||
|
||||
const topbar = createTopBar({
|
||||
title: 'Настройки',
|
||||
@@ -61,57 +119,41 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'stack settings-sections';
|
||||
const row = (id, label, hint) => `<button class="nav-row" type="button" id="${id}"><span class="nav-row__label">${label}</span>${hint ? `<span class="nav-row__hint">${hint}</span>` : ''}</button>`;
|
||||
const palette = PALETTE_PRESETS[getPaletteSettings().preset]?.label || '';
|
||||
const appearanceHint = `Тема: ${THEME_LABELS[getThemeMode()] || 'авто'}${palette ? ` · цвета «${palette}»` : ''}`;
|
||||
card.innerHTML = `
|
||||
<div class="card stack settings-theme-card">
|
||||
<strong id="settings-theme-label">Оформление</strong>
|
||||
<div class="tabs tabs--auto" id="settings-theme" role="radiogroup" aria-labelledby="settings-theme-label">
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="system">Авто</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="light">День</button>
|
||||
<button type="button" class="tab-btn" role="radio" data-mode="dark">Ночь</button>
|
||||
</div>
|
||||
<span class="meta-muted">«Авто» – как на устройстве.</span>
|
||||
<button type="button" class="secondary-btn settings-theme-editor" id="settings-theme-editor">Настроить цвета</button>
|
||||
<div class="nav-list">
|
||||
${row('settings-appearance', 'Оформление', appearanceHint)}
|
||||
${row('settings-notifications', 'Уведомления', 'Звук, разрешение, чаты без звука')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
${row('settings-device', 'Устройства', 'Сеансы, подключение устройств, ключи')}
|
||||
${row('settings-my-blockchain', 'Мой блокчейн', 'Все ваши подписанные события и смена ключей')}
|
||||
${row('settings-access-servers', 'Сервер доступа', 'Личная переписка, звонки и зашифрованные данные')}
|
||||
${row('settings-blockchain-servers', 'Серверы блокчейнов', 'Solana, Сияние и Arweave для публичных данных')}
|
||||
${row('settings-arweave-uploads', 'Файлы в блокчейне', 'Заранее загрузить файл и выбрать его потом')}
|
||||
${row('settings-remote-addblock', 'Публикация через домашний сервер', 'Когда ключа публикаций нет на этом устройстве')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
${row('settings-device', 'Устройства', 'Сеансы и подключение устройств')}
|
||||
${row('settings-my-blockchain', 'Мой блокчейн', 'История записей, файлы и внешнее устройство')}
|
||||
${row('settings-servers', 'Настройки серверов', 'Сервер доступа и серверы блокчейнов')}
|
||||
${row('settings-access-keys', 'Ключи и пароли', 'Просмотр ключей и смена пароля')}
|
||||
</div>
|
||||
<div class="nav-list" id="settings-install-list" hidden></div>
|
||||
<div class="nav-list">
|
||||
<button class="nav-row nav-row--danger" type="button" id="settings-signout"><span class="nav-row__label">Выйти из аккаунта на этом устройстве</span></button>
|
||||
${row('settings-about', 'О приложении', `Версия ${window.__SHINE_CLIENT_VERSION__ || '—'}`)}
|
||||
${row('settings-developer', 'Настройки разработчика', 'Инструменты и журнал приложения')}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
<button class="nav-row nav-row--danger" type="button" id="settings-signout"><span class="nav-row__label">Выйти из аккаунта</span></button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const themeSwitch = card.querySelector('#settings-theme');
|
||||
const syncThemeSwitch = () => {
|
||||
const mode = getThemeMode();
|
||||
themeSwitch.querySelectorAll('[data-mode]').forEach((btn) => {
|
||||
btn.setAttribute('aria-checked', String(btn.dataset.mode === mode));
|
||||
});
|
||||
};
|
||||
syncThemeSwitch();
|
||||
|
||||
themeSwitch.addEventListener('click', (event) => {
|
||||
const mode = event.target.closest('[data-mode]')?.dataset.mode;
|
||||
if (!mode) return;
|
||||
setThemeMode(mode);
|
||||
syncThemeSwitch();
|
||||
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||
aboutSheet?.close();
|
||||
aboutSheet = openAboutSheet();
|
||||
});
|
||||
card.querySelector('#settings-theme-editor').addEventListener('click', () => {
|
||||
openPaletteEditor({ theme: resolveThemeMode() });
|
||||
});
|
||||
|
||||
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
||||
card.querySelector('#settings-my-blockchain').addEventListener('click', () => navigate('my-blockchain-view'));
|
||||
card.querySelector('#settings-remote-addblock').addEventListener('click', () => navigate('remote-addblock-session-view'));
|
||||
card.querySelector('#settings-access-servers').addEventListener('click', () => navigate('access-servers-view'));
|
||||
card.querySelector('#settings-blockchain-servers').addEventListener('click', () => navigate('server-settings-view'));
|
||||
card.querySelector('#settings-arweave-uploads').addEventListener('click', () => navigate('arweave-uploads-view'));
|
||||
card.querySelector('#settings-servers').addEventListener('click', () => navigate('settings-servers-view'));
|
||||
card.querySelector('#settings-access-keys').addEventListener('click', () => navigate('access-keys-view'));
|
||||
card.querySelector('#settings-developer').addEventListener('click', () => navigate('developer-settings-view'));
|
||||
card.querySelector('#settings-language').addEventListener('click', () => {
|
||||
sessionStorage.setItem('shine-language-return-page', 'settings-view');
|
||||
navigate('language-view');
|
||||
@@ -171,62 +213,10 @@ export function render({navigate, chrome}) {
|
||||
|
||||
screen.append(card);
|
||||
|
||||
if (isDeveloperToolsEnabled()) {
|
||||
const versionCard = document.createElement('div');
|
||||
versionCard.className = 'card stack';
|
||||
|
||||
const title = document.createElement('p');
|
||||
title.className = 'field-label';
|
||||
title.textContent = 'Версии';
|
||||
|
||||
const clientVersion = document.createElement('p');
|
||||
clientVersion.className = 'meta-muted';
|
||||
clientVersion.textContent = `Клиент: ${formatVersionForUi(window.__SHINE_CLIENT_VERSION__)}`;
|
||||
|
||||
const uiBuild = document.createElement('p');
|
||||
uiBuild.className = 'meta-muted';
|
||||
uiBuild.textContent = `Сборка UI: ${formatVersionForUi(window.__SHINE_BUILD_HASH__)}`;
|
||||
|
||||
const serverVersion = document.createElement('p');
|
||||
serverVersion.className = 'meta-muted';
|
||||
serverVersion.textContent = 'Сервер: загружается...';
|
||||
|
||||
versionCard.append(title, clientVersion, uiBuild, serverVersion);
|
||||
|
||||
const developerCard = document.createElement('div');
|
||||
developerCard.className = 'card stack';
|
||||
developerCard.innerHTML = `
|
||||
<button class="shine-btn shine-btn--settings" type="button" id="settings-developer">Настройки разработчика</button>
|
||||
`;
|
||||
developerCard.querySelector('#settings-developer').addEventListener('click', () => navigate('developer-settings-view'));
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
let value = '';
|
||||
try {
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
value = String(pingResp?.payload?.serverVersion || pingResp?.serverVersion || '').trim();
|
||||
} catch {
|
||||
// fallback below
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
const infoResp = await authService.ws.request('GetServerInfo', {});
|
||||
value = String(infoResp?.payload?.version || '').trim();
|
||||
}
|
||||
if (!isDisposed) serverVersion.textContent = `Сервер: ${formatVersionForUi(value)}`;
|
||||
} catch {
|
||||
if (!isDisposed) {
|
||||
serverVersion.textContent = 'Сервер: недоступно';
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
screen.append(versionCard, developerCard);
|
||||
}
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (isDisposed) return;
|
||||
isDisposed = true;
|
||||
aboutSheet?.close();
|
||||
unsubscribeInstallAvailability();
|
||||
};
|
||||
return screen;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { state } from '../state.js';
|
||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||
@@ -16,12 +17,12 @@ export function render({navigate, chrome}) {
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Ключи этого устройства',
|
||||
back: { label: '←', onClick: () => navigate('device-view') },
|
||||
back: { label: '←', onClick: () => navigate('access-keys-view') },
|
||||
}));
|
||||
|
||||
const status = document.createElement('p');
|
||||
const status = document.createElement('div');
|
||||
status.className = 'meta-muted';
|
||||
status.textContent = 'Загружаем сохранённые ключи...';
|
||||
status.append(createLoadingState({ label: 'Загружаю ключи' }));
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'nav-list key-list';
|
||||
|
||||
@@ -23,20 +23,14 @@ export function render({ navigate }) {
|
||||
logoWrap.append(logo);
|
||||
|
||||
const brandBlock = document.createElement('div');
|
||||
brandBlock.className = 'stack';
|
||||
brandBlock.style.alignItems = 'center';
|
||||
brandBlock.style.gap = '22px';
|
||||
brandBlock.className = 'stack auth-brand-block';
|
||||
|
||||
const title = document.createElement('h1');
|
||||
title.className = 'auth-brand';
|
||||
title.append(createShineWordmark());
|
||||
|
||||
const siteName = document.createElement('p');
|
||||
siteName.className = 'meta-muted';
|
||||
siteName.style.margin = '0';
|
||||
siteName.style.fontSize = '18px';
|
||||
siteName.style.letterSpacing = '0.045em';
|
||||
siteName.style.lineHeight = '1.25';
|
||||
siteName.className = 'meta-muted auth-site-name';
|
||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||
|
||||
brandBlock.append(title, siteName);
|
||||
@@ -73,5 +67,23 @@ export function render({ navigate }) {
|
||||
|
||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||
screen.append(logoWrap, brandBlock, actions);
|
||||
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||
return screen;
|
||||
}
|
||||
|
||||
// Заставка рисует тот же знак: продолжаем её сияние с той же фазы, чтобы при смене не было скачка.
|
||||
function continueSplashAnimations(logoWrap) {
|
||||
const splashWrap = document.querySelector('#initial-splash .auth-logo-wrap');
|
||||
if (!splashWrap || !logoWrap.isConnected) return;
|
||||
const keyOf = (animation) => {
|
||||
const target = animation.effect?.target;
|
||||
const part = target?.classList?.contains('auth-logo') ? 'logo' : 'wrap';
|
||||
return `${part}${animation.effect?.pseudoElement || ''}|${animation.animationName || ''}`;
|
||||
};
|
||||
const source = new Map(splashWrap.getAnimations({ subtree: true }).map((animation) => [keyOf(animation), animation]));
|
||||
logoWrap.getAnimations({ subtree: true }).forEach((animation) => {
|
||||
const match = source.get(keyOf(animation));
|
||||
if (match && match.currentTime != null) animation.currentTime = match.currentTime;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { state } from '../state.js';
|
||||
import {
|
||||
createSolanaWalletFromPrivateBase58,
|
||||
@@ -59,7 +60,7 @@ export function render({ navigate }) {
|
||||
copyButton.textContent = 'Скопировать';
|
||||
}, 1500);
|
||||
} catch {
|
||||
window.alert('Не удалось скопировать номер кошелька.');
|
||||
showToast('Не удалось скопировать номер кошелька – выделите его и скопируйте вручную.', { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -88,7 +89,7 @@ export function render({ navigate }) {
|
||||
testButton.addEventListener('click', async () => {
|
||||
const address = String(walletValue.value || '').trim();
|
||||
if (!address) {
|
||||
window.alert('Адрес кошелька не найден.');
|
||||
showToast('Адрес кошелька не найден.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
if (!senderKeypair) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// UNUSED FOR NOW: настройка дополнительного пароля для подключения другого устройства
|
||||
// сохранена в коде, но не показывается в активном UI. Текущий UX всегда без пароля.
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createLoadingState } from '../components/feedback.js';
|
||||
import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
||||
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
@@ -27,9 +28,9 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const summary = document.createElement('p');
|
||||
const summary = document.createElement('div');
|
||||
summary.className = 'auth-copy';
|
||||
summary.textContent = 'Загружаем текущие настройки...';
|
||||
summary.append(createLoadingState({ label: 'Загружаю настройки' }));
|
||||
|
||||
const hint = document.createElement('p');
|
||||
hint.className = 'meta-muted';
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||
import { createPersonRow } from '../components/person-row.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { authService } from '../state.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { userDisplayName } from '../services/user-display.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
||||
|
||||
export const pageMeta = { id: 'user-profile-list-view', title: 'Список' };
|
||||
@@ -17,12 +21,22 @@ const TITLES = {
|
||||
channels_owned: 'Каналы', channels_following: 'Подписки на каналы',
|
||||
};
|
||||
|
||||
function friendTabsHtml(activeKind) {
|
||||
return `
|
||||
<div class="profile-list-tabs" role="tablist" aria-label="Тип друзей">
|
||||
<button type="button" class="profile-list-tab${activeKind === 'friends' ? ' is-active' : ''}" data-friend-kind="friends" role="tab" aria-selected="${activeKind === 'friends'}">Друзья</button>
|
||||
<button type="button" class="profile-list-tab${activeKind === 'close_friends' ? ' is-active' : ''}" data-friend-kind="close_friends" role="tab" aria-selected="${activeKind === 'close_friends'}">Близкие друзья</button>
|
||||
</div>`;
|
||||
const EMPTY_TEXT = {
|
||||
friends: 'Друзей пока нет.',
|
||||
close_friends: 'Близких друзей пока нет.',
|
||||
primary_received: 'Пока никто не подтвердил.',
|
||||
primary_given: 'Пока никого не подтвердили.',
|
||||
shine_received: 'Пока никто не подтвердил.',
|
||||
shine_given: 'Пока никого не подтвердили.',
|
||||
channels_owned: 'Каналов пока нет.',
|
||||
channels_following: 'Подписок пока нет.',
|
||||
};
|
||||
|
||||
const RELATION_TEXT = { contact: 'контакт', friend: 'друг', close_friend: 'близкий друг' };
|
||||
const SEARCH_FROM = 12; // с какого размера списка появляется поиск по нему
|
||||
|
||||
function searchText(value) {
|
||||
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||
}
|
||||
|
||||
export function render({ navigate, route, chrome }) {
|
||||
@@ -32,124 +46,158 @@ export function render({ navigate, route, chrome }) {
|
||||
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
||||
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
||||
let includeDeleted = false;
|
||||
let disposed = false;
|
||||
let rows = [];
|
||||
let query = '';
|
||||
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
screen.className = 'stack profile-list-screen';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'stack';
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Загрузка...';
|
||||
body.className = 'profile-list-body';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: TITLES[initialKind] || 'Список',
|
||||
back: { label: '←', onClick: () => navigateBack() },
|
||||
back: { onClick: () => navigateBack() },
|
||||
}));
|
||||
|
||||
if (isChannelsScreen) {
|
||||
const filter = document.createElement('label');
|
||||
filter.className = 'profile-list-deleted-filter';
|
||||
filter.innerHTML = '<input type="checkbox" id="profile-list-show-deleted"> <span>Показать удалённые</span>';
|
||||
screen.append(filter);
|
||||
}
|
||||
if (isFriendsScreen) {
|
||||
const tabs = document.createElement('div');
|
||||
tabs.innerHTML = friendTabsHtml(activeKind);
|
||||
screen.append(tabs.firstElementChild);
|
||||
tabs.className = 'tabs profile-list-kind';
|
||||
tabs.setAttribute('role', 'radiogroup');
|
||||
tabs.setAttribute('aria-label', 'Кого показать');
|
||||
for (const [kind, label] of [['friends', 'Друзья'], ['close_friends', 'Близкие друзья']]) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'tab-btn';
|
||||
button.dataset.kind = kind;
|
||||
button.setAttribute('role', 'radio');
|
||||
button.setAttribute('aria-checked', String(kind === activeKind));
|
||||
button.textContent = label;
|
||||
button.addEventListener('click', () => {
|
||||
if (kind === activeKind) return;
|
||||
activeKind = kind;
|
||||
tabs.querySelectorAll('.tab-btn').forEach((el) => el.setAttribute('aria-checked', String(el.dataset.kind === activeKind)));
|
||||
void load(activeKind);
|
||||
});
|
||||
tabs.append(button);
|
||||
}
|
||||
screen.append(tabs);
|
||||
}
|
||||
screen.append(status, body);
|
||||
|
||||
if (isChannelsScreen) {
|
||||
const filter = document.createElement('div');
|
||||
filter.className = 'nav-list';
|
||||
filter.innerHTML = `
|
||||
<label class="nav-row nav-row--switch">
|
||||
<span class="nav-row__text"><span class="nav-row__label">Показать удалённые</span></span>
|
||||
<input class="switch" type="checkbox" />
|
||||
</label>`;
|
||||
filter.querySelector('input').addEventListener('change', (event) => {
|
||||
includeDeleted = Boolean(event.currentTarget.checked);
|
||||
void load(activeKind);
|
||||
});
|
||||
screen.append(filter);
|
||||
}
|
||||
|
||||
// Поиск по списку – когда людей много (у «Друзей» их бывают сотни).
|
||||
const searchWrap = document.createElement('label');
|
||||
searchWrap.className = 'search-field profile-list-search';
|
||||
searchWrap.hidden = true;
|
||||
searchWrap.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span><input class="search-field__input" type="search" placeholder="Имя или логин" autocomplete="off" enterkeyhint="search" aria-label="Поиск по списку" />`;
|
||||
const searchInput = searchWrap.querySelector('input');
|
||||
searchInput.addEventListener('input', () => {
|
||||
query = searchText(searchInput.value);
|
||||
renderRows();
|
||||
});
|
||||
screen.append(searchWrap, body);
|
||||
|
||||
let loadGeneration = 0;
|
||||
|
||||
function renderRelationRows(rows) {
|
||||
rows.forEach((row) => {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({
|
||||
login: row.login,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
avatar: parseAvatar(row.avatarAr),
|
||||
size: 'md',
|
||||
}));
|
||||
const fullName = userDisplayName(row);
|
||||
const t = document.createElement('div');
|
||||
t.className = 'profile-list-row-text';
|
||||
const marks = [
|
||||
row.relationType && row.relationType !== 'none' ? ({ contact: 'контакт', friend: 'друг', close_friend: 'близкий друг' }[row.relationType] || row.relationType) : '',
|
||||
row.accountRole === 'primary' ? 'основной' : row.accountRole === 'non_voting' ? 'голос не учитывается' : '',
|
||||
row.shineStatus === 'shining' ? 'сияющий' : row.shineStatus === 'not_interested' ? 'сияние неинтересно' : '',
|
||||
row.primaryConfirmed ? 'основной подтверждён ✓' : '',
|
||||
row.shineConfirmed ? 'сияющий подтверждён ✓' : '',
|
||||
].filter(Boolean).join(' · ');
|
||||
t.innerHTML = `<b>${fullName}</b><small>@${String(row.login || '')}${marks ? ` · ${marks}` : ''}</small>`;
|
||||
el.append(t);
|
||||
el.addEventListener('click', () => navigate(`SHiNE/${encodeURIComponent(row.login)}`));
|
||||
body.append(el);
|
||||
function relationRow(row) {
|
||||
const marks = [
|
||||
RELATION_TEXT[row.relationType] || '',
|
||||
row.shineStatus === 'shining' ? 'сияющий' : '',
|
||||
row.accountRole === 'primary' ? 'официальный' : '',
|
||||
row.primaryConfirmed ? 'официальный подтверждён' : '',
|
||||
row.shineConfirmed ? 'сияние подтверждено' : '',
|
||||
].filter(Boolean);
|
||||
const name = userDisplayName(row);
|
||||
const sub = [name !== row.login ? `@${row.login}` : '', ...marks].filter(Boolean).join(' · ');
|
||||
return createPersonRow({
|
||||
login: row.login,
|
||||
name,
|
||||
firstName: row.firstName,
|
||||
lastName: row.lastName,
|
||||
avatar: parseAvatar(row.avatarAr),
|
||||
official: row.accountRole === 'primary',
|
||||
ring: row.shineStatus === 'shining' ? 'shining' : (row.relationType === 'close_friend' ? 'close' : ''),
|
||||
sub,
|
||||
onClick: () => navigate(`SHiNE/${encodeURIComponent(row.login)}`),
|
||||
actions: [{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(row.login)}`) }],
|
||||
});
|
||||
}
|
||||
|
||||
function channelRow(row) {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: (row.avatarAr || row.avatarSha256) ? { ar: String(row.avatarAr || ''), sha256Hex: String(row.avatarSha256 || '') } : null, size: 'md' }));
|
||||
const text = document.createElement('div');
|
||||
text.className = 'profile-list-row-text';
|
||||
const title = document.createElement('b');
|
||||
title.textContent = `${String(row.displayName || row.slug || '')}${row.deleted ? ' · удалён' : ''}`;
|
||||
const sub = document.createElement('small');
|
||||
sub.textContent = `${String(row.ownerLogin || '')} / ${String(row.slug || '')}`;
|
||||
text.append(title, sub);
|
||||
el.append(text);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderRows() {
|
||||
body.replaceChildren();
|
||||
const matches = (row) => !query || searchText(isChannelsScreen
|
||||
? `${row.displayName} ${row.slug} ${row.ownerLogin}`
|
||||
: `${userDisplayName(row)} ${row.login}`).includes(query);
|
||||
const visible = rows.filter(matches);
|
||||
if (!rows.length) {
|
||||
body.append(createStateMessage({ icon: isChannelsScreen ? 'channels' : 'network', title: EMPTY_TEXT[activeKind] || 'Пока никого.' }));
|
||||
return;
|
||||
}
|
||||
if (!visible.length) {
|
||||
body.append(createStateMessage({ icon: 'search', title: 'Никого не нашлось', text: 'Проверьте имя или логин.' }));
|
||||
return;
|
||||
}
|
||||
const frag = document.createDocumentFragment();
|
||||
visible.forEach((row) => frag.append(isChannelsScreen ? channelRow(row) : relationRow(row)));
|
||||
body.append(frag);
|
||||
}
|
||||
|
||||
async function load(kind) {
|
||||
const generation = ++loadGeneration;
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Загрузка...';
|
||||
body.replaceChildren();
|
||||
body.replaceChildren(createLoadingState({ label: 'Загружаю список' }));
|
||||
try {
|
||||
if (kind === 'channels_owned' || kind === 'channels_following') {
|
||||
const payload = await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted);
|
||||
if (generation !== loadGeneration) return;
|
||||
const rows = Array.isArray(payload?.channels) ? payload.channels : [];
|
||||
rows.forEach((row) => {
|
||||
const el = document.createElement('button');
|
||||
el.type = 'button';
|
||||
el.className = 'ui-button card row profile-list-row';
|
||||
el.append(renderUserAvatar({ login: row.ownerLogin, firstName: row.displayName, lastName: '', avatar: (row.avatarAr || row.avatarSha256) ? { ar: String(row.avatarAr || ''), sha256Hex: String(row.avatarSha256 || '') } : null, size: 'md' }));
|
||||
const t = document.createElement('div');
|
||||
t.className = 'profile-list-row-text';
|
||||
t.innerHTML = `<b>${String(row.displayName || row.slug || '')}${row.deleted ? ' · Удалён' : ''}</b><small>${String(row.ownerLogin || '')} / ${String(row.slug || '')}</small>`;
|
||||
el.append(t);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
body.append(el);
|
||||
});
|
||||
status.textContent = rows.length ? '' : 'Список пуст.';
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (generation !== loadGeneration) return;
|
||||
const rows = Array.isArray(payload?.users) ? payload.users : [];
|
||||
renderRelationRows(rows);
|
||||
status.textContent = rows.length ? '' : 'Список пуст.';
|
||||
} catch (e) {
|
||||
if (generation !== loadGeneration) return;
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = `Ошибка: ${e.message || 'unknown'}`;
|
||||
const payload = isChannelsScreen
|
||||
? await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted)
|
||||
: await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
rows = Array.isArray(isChannelsScreen ? payload?.channels : payload?.users) ? (isChannelsScreen ? payload.channels : payload.users) : [];
|
||||
searchWrap.hidden = rows.length < SEARCH_FROM;
|
||||
renderRows();
|
||||
} catch (error) {
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
body.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить список',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => { void load(activeKind); },
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if (isChannelsScreen) {
|
||||
screen.querySelector('#profile-list-show-deleted')?.addEventListener('change', (event) => {
|
||||
includeDeleted = !!event.currentTarget.checked;
|
||||
void load(activeKind);
|
||||
});
|
||||
}
|
||||
|
||||
if (isFriendsScreen) {
|
||||
screen.addEventListener('click', (event) => {
|
||||
const tab = event.target.closest('[data-friend-kind]');
|
||||
if (!tab) return;
|
||||
const nextKind = String(tab.dataset.friendKind || '');
|
||||
if (!nextKind || nextKind === activeKind) return;
|
||||
activeKind = nextKind;
|
||||
screen.querySelectorAll('[data-friend-kind]').forEach((button) => {
|
||||
const selected = button.dataset.friendKind === activeKind;
|
||||
button.classList.toggle('is-active', selected);
|
||||
button.setAttribute('aria-selected', selected ? 'true' : 'false');
|
||||
});
|
||||
void load(activeKind);
|
||||
});
|
||||
}
|
||||
screen.cleanup = () => {
|
||||
disposed = true;
|
||||
loadGeneration += 1;
|
||||
};
|
||||
|
||||
void load(activeKind);
|
||||
return screen;
|
||||
|
||||
@@ -2,10 +2,15 @@ import { createTopBar } from '../components/topbar.js';
|
||||
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
import { state } from '../state.js';
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { createPersonNotePreview, openPersonNoteSheet } from '../components/person-note-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { PEOPLE_NOTES_EVENT, getPersonNote } from '../services/people-notes.js';
|
||||
|
||||
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||||
|
||||
@@ -32,17 +37,28 @@ export function render({ navigate, route, chrome }) {
|
||||
chrome?.setTopbar(header);
|
||||
|
||||
const status = document.createElement('div');
|
||||
status.className = 'status-line user-profile-status';
|
||||
status.textContent = 'Загрузка профиля...';
|
||||
status.className = 'user-profile-status';
|
||||
status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'user-profile-body';
|
||||
screen.append(status, body);
|
||||
|
||||
let card = null;
|
||||
let disposed = false;
|
||||
let noteSheet = null;
|
||||
let relation = null; // кем человек вам приходится – для плитки «Добавить связь»
|
||||
|
||||
function openNote() {
|
||||
noteSheet?.close();
|
||||
const name = [card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login;
|
||||
noteSheet = openPersonNoteSheet({ login: card.login, name, onClose: () => { noteSheet = null; } });
|
||||
}
|
||||
|
||||
function renderProfile() {
|
||||
if (!card) return;
|
||||
if (!card || disposed) return;
|
||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||
const note = isSelf ? null : getPersonNote(card.login);
|
||||
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
@@ -55,6 +71,20 @@ export function render({ navigate, route, chrome }) {
|
||||
].join(''),
|
||||
});
|
||||
|
||||
// Личная заметка – сразу под кнопками действий; видна только владельцу аккаунта.
|
||||
let noteEl = createPersonNotePreview(note, { className: 'user-profile-note', onClick: openNote });
|
||||
if (noteEl) {
|
||||
noteEl.setAttribute('aria-label', `Ваша заметка: ${noteEl.textContent}. Изменить`);
|
||||
} else if (!isSelf) {
|
||||
noteEl = document.createElement('button');
|
||||
noteEl.type = 'button';
|
||||
noteEl.className = 'text-btn user-profile-note-add';
|
||||
noteEl.innerHTML = `${iconHtml('edit')}<span>Добавить личную заметку</span>`;
|
||||
noteEl.addEventListener('click', openNote);
|
||||
}
|
||||
if (noteEl) body.querySelector('.pf-tiles-wrap')?.after(noteEl);
|
||||
syncRelationTile();
|
||||
|
||||
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||
avatarSlot?.append(renderUserAvatar({
|
||||
login: card.login,
|
||||
@@ -63,9 +93,38 @@ export function render({ navigate, route, chrome }) {
|
||||
avatar: card.avatar,
|
||||
size: 'xl',
|
||||
className: 'user-profile-hero-avatar',
|
||||
official: card.accountRole === 'primary',
|
||||
}));
|
||||
|
||||
status.textContent = '';
|
||||
status.replaceChildren();
|
||||
}
|
||||
|
||||
// Плитка показывает текущую связь («Друг ✓») или предлагает ответить, если человек
|
||||
// добавил вас первым; нажатие – как раньше, в управление связью.
|
||||
function syncRelationTile() {
|
||||
const tile = body.querySelector('[data-profile-action="add"]');
|
||||
if (!tile || !relation) return;
|
||||
const r = relation;
|
||||
const theyFriend = r.inFriend || r.inCloseFriend;
|
||||
let icon = 'user-plus';
|
||||
let label = 'Добавить связь';
|
||||
let hint = '';
|
||||
if (r.outCloseFriend) { icon = 'check'; label = 'Близкий друг'; }
|
||||
else if (r.outFriend) { icon = 'check'; label = 'Друг'; }
|
||||
else if (r.outContact) { icon = 'check'; label = 'Контакт'; }
|
||||
else if (theyFriend) { label = 'Дружить в ответ'; hint = 'хочет с вами дружить'; }
|
||||
else if (r.inContact) { label = 'Добавить в ответ'; hint = 'добавил(а) вас в контакты'; }
|
||||
tile.innerHTML = `${iconHtml(icon)}<span></span>`;
|
||||
tile.querySelector('span').textContent = label;
|
||||
tile.classList.toggle('is-related', icon === 'check');
|
||||
tile.setAttribute('aria-label', icon === 'check' ? `${label}. Изменить связь` : label);
|
||||
body.querySelector('.user-profile-relation-hint')?.remove();
|
||||
if (hint) {
|
||||
const note = document.createElement('p');
|
||||
note.className = 'user-profile-relation-hint';
|
||||
note.textContent = `${[card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login} ${hint}`;
|
||||
body.querySelector('.pf-tiles-wrap')?.before(note);
|
||||
}
|
||||
}
|
||||
|
||||
body.addEventListener('click', (event) => {
|
||||
@@ -92,15 +151,43 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
});
|
||||
|
||||
const onNotesChanged = () => renderProfile();
|
||||
window.addEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
noteSheet?.close();
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
card = await loadUserProfileCard(requestedLogin);
|
||||
const loaded = await loadUserProfileCard(requestedLogin);
|
||||
if (disposed) return;
|
||||
card = loaded;
|
||||
renderProfile();
|
||||
if (selfLogin && card.login.toLowerCase() !== selfLogin.toLowerCase()) {
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login })
|
||||
.then((flags) => {
|
||||
if (disposed) return;
|
||||
relation = flags;
|
||||
syncRelationTile();
|
||||
})
|
||||
.catch(() => { /* без сведений о связи плитка остаётся «Добавить связь» */ });
|
||||
}
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line user-profile-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
||||
});
|
||||
const showLoadError = (error) => {
|
||||
if (disposed) return;
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить профиль',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { escapeProfileHtml } from '../components/profile-card.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
|
||||
export const pageMeta = { id: 'user-relation-manage-view', title: 'Добавить связь' };
|
||||
|
||||
@@ -62,12 +65,12 @@ function socialButtonsHtml(flags = {}) {
|
||||
</button>`).join('');
|
||||
}
|
||||
|
||||
function officialBlockHtml(flags = {}) {
|
||||
function officialBlockHtml(flags = {}, targetIsOfficial = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--official">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>Основной аккаунт</strong>
|
||||
<span>Этот аккаунт — основной</span>
|
||||
<span>${targetIsOfficial ? 'Этот аккаунт отмечен как основной' : 'Подтвердите, если это основной аккаунт этого человека'}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outOfficialAccount ? '<div class="relation-manage-confirmation">✓ Вы подтвердили его основной аккаунт</div>' : ''}
|
||||
@@ -79,12 +82,12 @@ function officialBlockHtml(flags = {}) {
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function shineBlockHtml(flags = {}) {
|
||||
function shineBlockHtml(flags = {}, targetIsShining = false) {
|
||||
return `
|
||||
<section class="card stack relation-manage-card relation-manage-card--shine">
|
||||
<div class="relation-manage-card-head">
|
||||
<strong>Сияющий</strong>
|
||||
<span>Этот аккаунт — сияющий</span>
|
||||
<span>${targetIsShining ? 'Этот человек отмечен как сияющий' : 'Подтвердите, если считаете этого человека сияющим'}</span>
|
||||
</div>
|
||||
<div class="relation-manage-confirmations">
|
||||
${flags.outShineConfirmed ? '<div class="relation-manage-confirmation">✓ Вы подтверждаете его сияющим</div>' : ''}
|
||||
@@ -152,8 +155,11 @@ export function render({ route, chrome }) {
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const canPrimary = selfCard?.accountRole === 'primary' && targetCard?.accountRole === 'primary';
|
||||
const canShine = selfCard?.shineStatus === 'shining' && targetCard?.shineStatus === 'shining';
|
||||
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует основной аккаунт,
|
||||
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений.
|
||||
const selfPrimary = selfCard?.accountRole === 'primary';
|
||||
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
|
||||
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
|
||||
|
||||
body.innerHTML = `
|
||||
<section class="card stack relation-manage-card relation-manage-card--social">
|
||||
@@ -166,26 +172,36 @@ export function render({ route, chrome }) {
|
||||
${socialButtonsHtml(flags)}
|
||||
</div>
|
||||
</section>
|
||||
${canPrimary ? officialBlockHtml(flags) : ''}
|
||||
${canShine ? shineBlockHtml(flags) : ''}
|
||||
${canPrimary ? officialBlockHtml(flags, targetCard?.accountRole === 'primary') : ''}
|
||||
${canShine ? shineBlockHtml(flags, targetCard?.shineStatus === 'shining') : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
async function refresh({ loading = true } = {}) {
|
||||
if (loading) {
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = 'Загрузка...';
|
||||
}
|
||||
// Спиннер – только если ответ задержался, иначе он мелькает и сдвигает экран.
|
||||
const loadingTimer = loading ? window.setTimeout(() => {
|
||||
if (screen.isConnected && !body.childElementCount) status.replaceChildren(createLoadingState({ label: 'Загрузка', delayMs: 0 }));
|
||||
}, 500) : 0;
|
||||
[selfCard, targetCard, flags] = await Promise.all([
|
||||
loadUserProfileCard(selfLogin),
|
||||
loadUserProfileCard(targetLogin),
|
||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin }),
|
||||
]);
|
||||
window.clearTimeout(loadingTimer);
|
||||
renderBody();
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = '';
|
||||
}
|
||||
|
||||
const SOCIAL_DONE = {
|
||||
none: 'Связь убрана',
|
||||
contact: 'Добавлен в контакты',
|
||||
friend: 'Добавлен в друзья',
|
||||
close_friend: 'Добавлен в близкие друзья',
|
||||
};
|
||||
|
||||
// Выбор сохраняется прямо на нажатой кнопке (без строки статуса, которая сдвигала экран),
|
||||
// после сохранения – короткое сообщение и возврат на страницу пользователя.
|
||||
body.addEventListener('click', async (event) => {
|
||||
const button = event.target.closest('button');
|
||||
if (!button || busy) return;
|
||||
@@ -193,24 +209,36 @@ export function render({ route, chrome }) {
|
||||
const social = button.dataset.socialKind;
|
||||
const confirm = button.dataset.confirm;
|
||||
if (!social && !confirm) return;
|
||||
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
|
||||
|
||||
busy = true;
|
||||
body.classList.add('is-busy');
|
||||
status.className = 'status-line relation-manage-status';
|
||||
status.textContent = 'Сохранение...';
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = true; });
|
||||
const label = button.textContent;
|
||||
button.classList.add('is-pending');
|
||||
button.textContent = 'Сохраняем…';
|
||||
|
||||
try {
|
||||
let done = '';
|
||||
if (social) {
|
||||
await changeSocial(social);
|
||||
done = SOCIAL_DONE[social] || 'Связь сохранена';
|
||||
} else if (confirm === 'official_account') {
|
||||
await setKind('official_account', !flags.outOfficialAccount);
|
||||
done = flags.outOfficialAccount ? 'Подтверждение убрано' : 'Вы подтвердили официальный аккаунт';
|
||||
} else if (confirm === 'shine_confirmed') {
|
||||
await setKind('shine_confirmed', !flags.outShineConfirmed);
|
||||
done = flags.outShineConfirmed ? 'Подтверждение убрано' : 'Вы подтвердили сияние';
|
||||
}
|
||||
await refresh({ loading: false });
|
||||
if (!screen.isConnected) return;
|
||||
showToast(done);
|
||||
navigateBack();
|
||||
} catch (error) {
|
||||
status.className = 'status-line relation-manage-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось изменить связь'}`;
|
||||
if (!screen.isConnected) return;
|
||||
showToast(toUserMessage(error, 'Не удалось изменить связь'), { kind: 'error', timeoutMs: 4000 });
|
||||
button.textContent = label;
|
||||
button.classList.remove('is-pending');
|
||||
body.querySelectorAll('button').forEach((item) => { item.disabled = false; });
|
||||
} finally {
|
||||
busy = false;
|
||||
body.classList.remove('is-busy');
|
||||
@@ -223,10 +251,18 @@ export function render({ route, chrome }) {
|
||||
return screen;
|
||||
}
|
||||
|
||||
refresh().catch((error) => {
|
||||
status.className = 'status-line relation-manage-status is-unavailable';
|
||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось загрузить связи'}`;
|
||||
});
|
||||
const showLoadError = (error) => {
|
||||
status.className = 'relation-manage-status';
|
||||
status.replaceChildren(createErrorState({
|
||||
title: 'Не удалось загрузить связь',
|
||||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||
onRetry: () => {
|
||||
status.replaceChildren();
|
||||
refresh().catch(showLoadError);
|
||||
},
|
||||
}));
|
||||
};
|
||||
refresh().catch(showLoadError);
|
||||
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -989,7 +989,7 @@ export function render({navigate, chrome}) {
|
||||
const stateCard = document.createElement('div');
|
||||
stateCard.className = 'card stack';
|
||||
stateCard.innerHTML = `
|
||||
<p class="meta-muted" style="margin:0;">Текущее состояние покупки загружается...</p>
|
||||
<div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="Загрузка"></span></div>
|
||||
`;
|
||||
|
||||
const amountLabel = document.createElement('label');
|
||||
|
||||
+82
-8
@@ -20,6 +20,7 @@ const PRETTY_PATHS = new Map([
|
||||
['profiles-view', 'profiles'],
|
||||
['messages-list', 'messages'],
|
||||
['contact-search-view', 'contacts'],
|
||||
['search-view', 'search'],
|
||||
['chat-view', 'chat'],
|
||||
['channels-list', 'channels'],
|
||||
['add-channel-view', 'channels/new'],
|
||||
@@ -31,15 +32,20 @@ const PRETTY_PATHS = new Map([
|
||||
['network-view', 'network'],
|
||||
['notifications-view', 'notifications'],
|
||||
['settings-view', 'settings'],
|
||||
['access-keys-view', 'settings/keys'],
|
||||
['my-blockchain-view', 'settings/blockchain'],
|
||||
['my-blockchain-history-view', 'settings/blockchain/history'],
|
||||
['key-rotation-view', 'settings/key-rotation'],
|
||||
['access-servers-view', 'settings/access-servers'],
|
||||
['settings-servers-view', 'settings/server-options'],
|
||||
['server-settings-view', 'settings/servers'],
|
||||
['arweave-uploads-view', 'settings/arweave-uploads'],
|
||||
['developer-settings-view', 'settings/developer'],
|
||||
['advanced-settings-view', 'settings/advanced'],
|
||||
['trusted-device-login-settings-view', 'settings/device-login'],
|
||||
['language-view', 'settings/language'],
|
||||
['appearance-view', 'settings/appearance'],
|
||||
['notification-settings-view', 'settings/notifications'],
|
||||
['app-log-view', 'settings/app-log'],
|
||||
['pwa-diagnostics-view', 'settings/pwa-diagnostics'],
|
||||
['solana-users-init-view', 'settings/solana-users-init'],
|
||||
@@ -149,14 +155,19 @@ export function parseRouteFromPath(pathname = '') {
|
||||
if (segments.length >= baseOffset + 1) {
|
||||
const ownerBlockchainName = shineLogin;
|
||||
const channelName = decodePart(segments[baseOffset] || '');
|
||||
const messageBlockNumber = segments[baseOffset + 1] || '';
|
||||
if (ownerBlockchainName && channelName && messageBlockNumber) {
|
||||
const streamMode = decodePart(segments[baseOffset + 1] || '').toLowerCase() === 's';
|
||||
const streamOrdinal = streamMode ? decodePart(segments[baseOffset + 2] || '') : '';
|
||||
if (ownerBlockchainName && channelName && streamMode && /^[1-9][0-9]*$/.test(streamOrdinal) && segments.length === baseOffset + 3) {
|
||||
return { pageId: 'channel-view', params: { ownerBlockchainName, channelName, channelId: '', scrollToMessageOrdinal: streamOrdinal } };
|
||||
}
|
||||
const messageOrdinal = segments[baseOffset + 1] || '';
|
||||
if (ownerBlockchainName && channelName && /^[1-9][0-9]*$/.test(messageOrdinal) && segments.length === baseOffset + 2) {
|
||||
return {
|
||||
pageId: 'channel-thread-view',
|
||||
params: {
|
||||
ownerBlockchainName,
|
||||
channelName,
|
||||
messageBlockNumber,
|
||||
messageOrdinal,
|
||||
messageBlockHash: '',
|
||||
messageBlockchainName: '',
|
||||
channelOwnerBlockchainName: ownerBlockchainName,
|
||||
@@ -203,6 +214,9 @@ export function parseRouteFromPath(pathname = '') {
|
||||
}
|
||||
|
||||
if (pageId === 'chat' || pageId === 'chat-view') {
|
||||
if (decodePart(segments[2] || '').toLowerCase() === 'media') {
|
||||
return { pageId: 'chat-media-view', params: { chatId: decodePart(dynamicId) } };
|
||||
}
|
||||
return { pageId: 'chat-view', params: { chatId: dynamicId ? decodeURIComponent(dynamicId) : '' } };
|
||||
}
|
||||
|
||||
@@ -257,6 +271,8 @@ export function parseRouteFromPath(pathname = '') {
|
||||
return { pageId: 'messages-list', params: {} };
|
||||
}
|
||||
|
||||
if (pageId === 'search') return { pageId: 'search-view', params: {} };
|
||||
|
||||
if (pageId === 'contacts') {
|
||||
return { pageId: 'contact-search-view', params: {} };
|
||||
}
|
||||
@@ -321,7 +337,10 @@ export function parseRouteFromPath(pathname = '') {
|
||||
|
||||
if (pageId === 'settings') {
|
||||
const sub = decodePart(segments[1] || '').toLowerCase();
|
||||
if (sub === 'keys') return { pageId: 'access-keys-view', params: {} };
|
||||
if (sub === 'server-options') return { pageId: 'settings-servers-view', params: {} };
|
||||
if (sub === 'access-servers') return { pageId: 'access-servers-view', params: {} };
|
||||
if (sub === 'blockchain' && decodePart(segments[2] || '').toLowerCase() === 'history') return { pageId: 'my-blockchain-history-view', params: {} };
|
||||
if (sub === 'blockchain') return { pageId: 'my-blockchain-view', params: {} };
|
||||
if (sub === 'key-rotation') return { pageId: 'key-rotation-view', params: {} };
|
||||
if (sub === 'servers') return { pageId: 'server-settings-view', params: {} };
|
||||
@@ -330,6 +349,8 @@ export function parseRouteFromPath(pathname = '') {
|
||||
if (sub === 'advanced') return { pageId: 'advanced-settings-view', params: {} };
|
||||
if (sub === 'device-login') return { pageId: 'trusted-device-login-settings-view', params: {} };
|
||||
if (sub === 'language') return { pageId: 'language-view', params: {} };
|
||||
if (sub === 'appearance') return { pageId: 'appearance-view', params: {} };
|
||||
if (sub === 'notifications') return { pageId: 'notification-settings-view', params: {} };
|
||||
if (sub === 'app-log') return { pageId: 'app-log-view', params: {} };
|
||||
if (sub === 'pwa-diagnostics') return { pageId: 'pwa-diagnostics-view', params: {} };
|
||||
if (sub === 'solana-users-init') return { pageId: 'solana-users-init-view', params: {} };
|
||||
@@ -451,16 +472,53 @@ export function getRoute() {
|
||||
export function navigate(path) {
|
||||
const cleanPath = toPrettyPath(path);
|
||||
const nextPath = cleanPath ? `/${cleanPath}` : '/';
|
||||
if (window.location.pathname !== nextPath) {
|
||||
const fromPath = window.location.pathname;
|
||||
if (fromPath !== nextPath) {
|
||||
previousTrackedPath = currentTrackedPath;
|
||||
currentTrackedPath = nextPath;
|
||||
}
|
||||
if (window.location.pathname !== nextPath) {
|
||||
window.history.pushState({}, '', nextPath);
|
||||
if (fromPath !== nextPath) {
|
||||
// Запись помнит, откуда на неё пришли: «назад» в шапке может вернуться по истории, а не открывать страницу заново.
|
||||
window.history.pushState({ shineFrom: fromPath }, '', nextPath);
|
||||
}
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
}
|
||||
|
||||
// Слой поверх экрана (редактор) кладёт в историю запись с тем же адресом, чтобы «назад» закрывало его.
|
||||
// Роутер разбирает такие возвраты первым: закрывает слой и не пересоздаёт экран под ним.
|
||||
const historyLayers = [];
|
||||
let ownLayerPops = 0;
|
||||
|
||||
export function openHistoryLayer(onBack) {
|
||||
const id = `${Date.now()}:${Math.random()}`;
|
||||
window.history.pushState({ ...window.history.state, shineLayer: id }, '', window.location.href);
|
||||
const layer = { onBack };
|
||||
historyLayers.push(layer);
|
||||
return {
|
||||
// Закрытие изнутри (крестик, отправка) убирает свою запись из истории.
|
||||
close() {
|
||||
const index = historyLayers.indexOf(layer);
|
||||
if (index < 0) return;
|
||||
historyLayers.splice(index, 1);
|
||||
if (window.history.state?.shineLayer === id) {
|
||||
ownLayerPops += 1;
|
||||
window.history.back();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function consumeHistoryLayerPop() {
|
||||
if (ownLayerPops > 0) {
|
||||
ownLayerPops -= 1;
|
||||
return true;
|
||||
}
|
||||
const layer = historyLayers.pop();
|
||||
if (!layer) return false;
|
||||
layer.onBack();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function toPrettyPath(path) {
|
||||
const raw = String(path || '').replace(/^\/+/, '').replace(/\/+$/, '');
|
||||
if (!raw) return '';
|
||||
@@ -471,6 +529,17 @@ export function toPrettyPath(path) {
|
||||
return [prettyHead, ...tail].join('/');
|
||||
}
|
||||
|
||||
// Стрелка «назад» в шапке: если сюда пришли со страницы, которую isParent признаёт своей, – шаг по истории
|
||||
// (как стек: ответ → запись → канал), иначе переход на fallback. Повторный navigate гонял бы по кругу две страницы.
|
||||
export function navigateUp(isParent, fallback) {
|
||||
const from = String(window.history.state?.shineFrom || '');
|
||||
if (from && isParent(parseRouteFromPath(from), from)) {
|
||||
window.history.back();
|
||||
return;
|
||||
}
|
||||
navigate(fallback);
|
||||
}
|
||||
|
||||
export function navigateBack() {
|
||||
if (window.history.length <= 1) return;
|
||||
window.history.back();
|
||||
@@ -499,9 +568,12 @@ function resolveToolbarTab(pageId) {
|
||||
pageId === 'profiles-view' ||
|
||||
pageId === 'wallet-view' ||
|
||||
pageId === 'settings-view' ||
|
||||
pageId === 'access-keys-view' ||
|
||||
pageId === 'my-blockchain-view' ||
|
||||
pageId === 'my-blockchain-history-view' ||
|
||||
pageId === 'key-rotation-view' ||
|
||||
pageId === 'access-servers-view' ||
|
||||
pageId === 'settings-servers-view' ||
|
||||
pageId === 'developer-settings-view' ||
|
||||
pageId === 'advanced-settings-view' ||
|
||||
pageId === 'server-settings-view' ||
|
||||
@@ -516,12 +588,14 @@ function resolveToolbarTab(pageId) {
|
||||
pageId === 'show-keys-view' ||
|
||||
pageId === 'device-session-view' ||
|
||||
pageId === 'language-view' ||
|
||||
pageId === 'appearance-view' ||
|
||||
pageId === 'notification-settings-view' ||
|
||||
pageId === 'app-log-view' ||
|
||||
pageId === 'pwa-diagnostics-view' ||
|
||||
pageId === 'solana-users-init-view'
|
||||
) return 'profile-view';
|
||||
if (pageId === 'chat-view' || pageId === 'contact-search-view') return 'messages-list';
|
||||
if (pageId === 'channel-view' || pageId === 'channel-about-view' || pageId === 'channel-donate-view' || pageId === 'channel-thread-view' || pageId === 'add-channel-view' || pageId === 'add-personal-public-chat-view') return 'channels-list';
|
||||
if (pageId === 'chat-view' || pageId === 'chat-media-view' || pageId === 'contact-search-view') return 'messages-list';
|
||||
if (pageId === 'search-view' || pageId === 'channel-view' || pageId === 'channel-about-view' || pageId === 'channel-donate-view' || pageId === 'channel-thread-view' || pageId === 'add-channel-view' || pageId === 'add-personal-public-chat-view') return 'channels-list';
|
||||
return 'profile-view';
|
||||
}
|
||||
|
||||
|
||||
@@ -17,12 +17,16 @@ export function escapeHtml(text) {
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
// Размер файла по-русски: «83 Б», «93 КБ», «1,4 МБ»; после 10 – без дробной части.
|
||||
export function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||
if (value < 1024) return `${value} B`;
|
||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
|
||||
return `${(value / (1024 * 1024)).toFixed(2)} MB`;
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 Б';
|
||||
for (const [unit, size] of [['ГБ', 1024 ** 3], ['МБ', 1024 ** 2], ['КБ', 1024]]) {
|
||||
if (value < size) continue;
|
||||
const amount = value / size;
|
||||
return `${amount.toLocaleString('ru-RU', { maximumFractionDigits: amount >= 10 ? 0 : 1 })} ${unit}`;
|
||||
}
|
||||
return `${Math.round(value)} Б`;
|
||||
}
|
||||
|
||||
function normalizeName(name) {
|
||||
@@ -214,6 +218,17 @@ function createFileCard({ item, url, messageTimestampMs, slide }) {
|
||||
return card;
|
||||
}
|
||||
|
||||
function formatVideoDuration(seconds) {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return '';
|
||||
const wholeSeconds = Math.floor(seconds);
|
||||
const hours = Math.floor(wholeSeconds / 3600);
|
||||
const minutes = Math.floor((wholeSeconds % 3600) / 60);
|
||||
const secondsPart = String(wholeSeconds % 60).padStart(2, '0');
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, '0')}:${secondsPart}`
|
||||
: `${String(minutes).padStart(2, '0')}:${secondsPart}`;
|
||||
}
|
||||
|
||||
function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }) {
|
||||
const frame = document.createElement('div');
|
||||
frame.className = `message-attachment-media-frame message-attachment-media-frame--${kind}`;
|
||||
@@ -230,16 +245,18 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
onOpen?.();
|
||||
});
|
||||
|
||||
// Горизонтальное фото или видео занимает свою высоту, а не рамку 20rem с пустыми полосами.
|
||||
const applyMediaLayout = (media, width, height) => {
|
||||
const isLandscape = width > 0 && height > 0 && width > height;
|
||||
media.classList.toggle('is-landscape', isLandscape);
|
||||
frame.classList.toggle('is-landscape', isLandscape);
|
||||
slide.classList.toggle('has-landscape-media', isLandscape);
|
||||
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
|
||||
};
|
||||
const bindImageLayout = (img) => {
|
||||
img.addEventListener('load', () => {
|
||||
frame.classList.add('is-loaded');
|
||||
const naturalWidth = Number(img.naturalWidth || 0);
|
||||
const naturalHeight = Number(img.naturalHeight || 0);
|
||||
const isLandscape = naturalWidth > 0 && naturalHeight > 0 && naturalWidth > naturalHeight;
|
||||
img.classList.toggle('is-landscape', isLandscape);
|
||||
frame.classList.toggle('is-landscape', isLandscape);
|
||||
slide.classList.toggle('has-landscape-media', isLandscape);
|
||||
slide.parentElement?.classList.toggle('has-landscape-media', isLandscape);
|
||||
applyMediaLayout(img, Number(img.naturalWidth || 0), Number(img.naturalHeight || 0));
|
||||
}, { once: true });
|
||||
};
|
||||
|
||||
@@ -261,10 +278,27 @@ function createMediaSlide({ item, url, kind, messageTimestampMs, slide, onOpen }
|
||||
video.playsInline = true;
|
||||
video.addEventListener('error', () => replaceWithUnavailable(slide, messageTimestampMs, attachmentStorage(item)), { once: true });
|
||||
video.addEventListener('loadeddata', () => frame.classList.add('is-loaded'), { once: true });
|
||||
|
||||
// Размер известен из S:att, длительность появляется после получения метаданных.
|
||||
// <video> сам запрашивает небольшие диапазоны через HTTP Range, без fetch всего файла.
|
||||
const info = document.createElement('span');
|
||||
info.className = 'message-attachment-video-info';
|
||||
const videoSize = formatBytes(item.size);
|
||||
info.textContent = videoSize;
|
||||
video.addEventListener('loadedmetadata', () => {
|
||||
applyMediaLayout(video, Number(video.videoWidth || 0), Number(video.videoHeight || 0));
|
||||
const duration = formatVideoDuration(video.duration);
|
||||
info.textContent = duration ? `${videoSize} · ${duration}` : videoSize;
|
||||
// Metadata сама по себе не гарантирует первого кадра. Переход к самому
|
||||
// началу видео побуждает браузер запросить только нужные части файла.
|
||||
if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA && Number.isFinite(video.duration) && video.duration > 0) {
|
||||
try { video.currentTime = Math.min(0.05, video.duration); } catch { /* зависит от кодека */ }
|
||||
}
|
||||
}, { once: true });
|
||||
const play = document.createElement('span');
|
||||
play.className = 'message-attachment-play';
|
||||
play.textContent = '▶';
|
||||
frame.append(video, play);
|
||||
frame.append(video, play, info);
|
||||
}
|
||||
|
||||
return frame;
|
||||
@@ -334,9 +368,11 @@ async function resolveAttachmentDisplayUrl(item, options = {}) {
|
||||
fallbackServerLogin: options.fallbackServerLogin,
|
||||
});
|
||||
const kind = getAttachmentKind(item);
|
||||
if (kind === 'file') return { url: serverUrl, objectUrl: false };
|
||||
// Видео подключаем напрямую. Иначе fetch + Blob + полный SHA-256 сначала
|
||||
// скачает ВСЕ байты и браузер не сможет запрашивать Range для просмотра.
|
||||
if (kind === 'video' || kind === 'file') return { url: serverUrl, objectUrl: false };
|
||||
|
||||
// /files хранит только байты и SHA-256. Для media тип задаёт клиент по имени из S:att.
|
||||
// Для изображений сохраняем прежнюю проверку SHA-256 после скачивания.
|
||||
const response = await fetch(serverUrl);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} ${serverUrl}`);
|
||||
const buffer = await response.arrayBuffer();
|
||||
@@ -352,10 +388,14 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
authorLogin = '',
|
||||
solanaEndpoint = '',
|
||||
fallbackServerLogin = '',
|
||||
// Свой источник файла: async (item) => ({ url, objectUrl }). Нужен личным сообщениям,
|
||||
// где вложение зашифровано и описано не S:att, а своим тех-блоком (без sha256).
|
||||
resolveUrl = null,
|
||||
} = {}) {
|
||||
const items = (Array.isArray(attachments) ? attachments : [])
|
||||
.slice(0, MAX_MESSAGE_ATTACHMENTS)
|
||||
.map((raw) => {
|
||||
if (resolveUrl) return raw && typeof raw === 'object' ? { ...raw, name: normalizeName(raw.name), size: Number(raw.size || 0) } : null;
|
||||
try {
|
||||
return normalizeAttachment(raw);
|
||||
} catch {
|
||||
@@ -396,7 +436,7 @@ export function createAttachmentCarouselElement(attachments = [], {
|
||||
const getResolved = (itemIndex) => {
|
||||
if (resolved.has(itemIndex)) return Promise.resolve(resolved.get(itemIndex));
|
||||
if (pending.has(itemIndex)) return pending.get(itemIndex);
|
||||
const promise = resolveAttachmentDisplayUrl(items[itemIndex], options)
|
||||
const promise = Promise.resolve(resolveUrl ? resolveUrl(items[itemIndex]) : resolveAttachmentDisplayUrl(items[itemIndex], options))
|
||||
.then((value) => {
|
||||
resolved.set(itemIndex, value);
|
||||
pending.delete(itemIndex);
|
||||
|
||||
@@ -3206,8 +3206,23 @@ export class AuthService {
|
||||
return response.payload || {};
|
||||
}
|
||||
|
||||
async searchChannels(query, { limit = 10, ownerLogin = '' } = {}) {
|
||||
const payload = { query, limit };
|
||||
if (ownerLogin) payload.ownerLogin = ownerLogin;
|
||||
const response = await this.ws.request('SearchChannels', payload);
|
||||
if (response.status !== 200) throw opError('SearchChannels', response);
|
||||
return Array.isArray(response.payload?.channels) ? response.payload.channels : [];
|
||||
}
|
||||
|
||||
async searchPeople(query, { limit = 10 } = {}) {
|
||||
const response = await this.ws.request('SearchUsers', { prefix: query, limit });
|
||||
if (response.status !== 200) throw opError('SearchUsers', response);
|
||||
return Array.isArray(response.payload?.users) ? response.payload.users : [];
|
||||
}
|
||||
|
||||
async searchUsers(prefix, options = {}) {
|
||||
const payload = { prefix };
|
||||
if (Number.isInteger(options?.limit)) payload.limit = options.limit;
|
||||
if (typeof options?.isServer === 'boolean') {
|
||||
payload.isServer = options.isServer;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Public channel URLs use one-based publication positions, not blockchain block numbers.
|
||||
// Order must match the channel feed: message time, then original block number.
|
||||
function messageTimestamp(message) {
|
||||
const value = Number(message?.timestampMs ?? message?.createdAtMs ?? 0);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function blockNumber(message) {
|
||||
const value = Number(message?.messageRef?.blockNumber);
|
||||
return Number.isSafeInteger(value) ? value : 0;
|
||||
}
|
||||
|
||||
export function sortedChannelPublications(messages = []) {
|
||||
return [...messages].sort((a, b) => {
|
||||
const byTime = messageTimestamp(a) - messageTimestamp(b);
|
||||
return byTime !== 0 ? byTime : blockNumber(a) - blockNumber(b);
|
||||
});
|
||||
}
|
||||
|
||||
export function parsePublicationOrdinal(value) {
|
||||
const text = String(value ?? '').trim();
|
||||
if (!/^[1-9][0-9]*$/.test(text)) return null;
|
||||
const number = Number(text);
|
||||
return Number.isSafeInteger(number) ? number : null;
|
||||
}
|
||||
|
||||
export function publicationAtOrdinal(messages, ordinal) {
|
||||
const value = parsePublicationOrdinal(ordinal);
|
||||
if (!value) return null;
|
||||
return sortedChannelPublications(messages)[value - 1] || null;
|
||||
}
|
||||
|
||||
export function ordinalForPublication(messages, reference) {
|
||||
if (!reference) return null;
|
||||
const number = Number(reference.blockNumber);
|
||||
const hash = String(reference.blockHash || '').trim().toLowerCase();
|
||||
const owner = String(reference.blockchainName || '').trim().toLowerCase();
|
||||
const i = sortedChannelPublications(messages).findIndex((item) => {
|
||||
const ref = item?.messageRef;
|
||||
if (Number(ref?.blockNumber) !== number) return false;
|
||||
if (hash && String(ref?.blockHash || '').trim().toLowerCase() !== hash) return false;
|
||||
if (owner && String(item?.authorBlockchainName || '').trim().toLowerCase() !== owner) return false;
|
||||
return true;
|
||||
});
|
||||
return i < 0 ? null : i + 1;
|
||||
}
|
||||
@@ -8,3 +8,18 @@ export function restoreChannelPosition(value) {
|
||||
const root = document.getElementById('app-screen');
|
||||
if (root && Number.isFinite(value)) root.scrollTop = value;
|
||||
}
|
||||
|
||||
// «Открыть обсуждение» из ленты ведёт сразу в редактор ответа: лента отмечает путь, обсуждение забирает отметку один раз.
|
||||
let replyOnOpenPath = '';
|
||||
const normalizePath = (path) => {
|
||||
const raw = String(path || '').split(/[?#]/)[0];
|
||||
let decoded = raw;
|
||||
try { decoded = decodeURIComponent(raw); } catch { /* оставляем как есть */ }
|
||||
return decoded.replace(/^\/+|\/+$/g, '').toLowerCase();
|
||||
};
|
||||
export function requestReplyEditorOnOpen(path) { replyOnOpenPath = normalizePath(path); }
|
||||
export function consumeReplyEditorOnOpen(path) {
|
||||
const match = Boolean(replyOnOpenPath) && replyOnOpenPath === normalizePath(path);
|
||||
replyOnOpenPath = '';
|
||||
return match;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const TOAST_HOST_ID = 'shine-toast-host';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
const TOAST_HOST_ID = 'shine-toast-host';
|
||||
|
||||
const rtf = (() => {
|
||||
try {
|
||||
@@ -93,6 +94,22 @@ export function formatListTime(timestampMs) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', year: '2-digit' }).format(dt);
|
||||
}
|
||||
|
||||
// Возраст записи в шапке поста и ответа: «сейчас», «5 мин», «2 ч», «3 д», потом «12 окт», в прошлом году «12 окт 2025».
|
||||
export function formatShortAge(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '';
|
||||
const ageMinutes = Math.max(0, Math.floor((Date.now() - ts) / 60000));
|
||||
if (ageMinutes < 1) return 'сейчас';
|
||||
if (ageMinutes < 60) return `${ageMinutes} мин`;
|
||||
const ageHours = Math.floor(ageMinutes / 60);
|
||||
if (ageHours < 24) return `${ageHours} ч`;
|
||||
const ageDays = Math.floor(ageHours / 24);
|
||||
if (ageDays < 7) return `${ageDays} д`;
|
||||
const dt = new Date(ts);
|
||||
const day = `${dt.getDate()} ${SHORT_MONTHS[dt.getMonth()]}`;
|
||||
return dt.getFullYear() === new Date().getFullYear() ? day : `${day} ${dt.getFullYear()}`;
|
||||
}
|
||||
|
||||
export function formatRelativeTime(timestampMs) {
|
||||
const ts = toNumber(timestampMs);
|
||||
if (!ts) return '–';
|
||||
@@ -137,27 +154,87 @@ function ensureToastHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
export function showToast(message, { kind = 'success', timeoutMs = 2500 } = {}) {
|
||||
// Тост встаёт над нижним меню и панелью ввода (что из них выше), а не поверх них.
|
||||
function placeToastHost(host) {
|
||||
const tops = ['toolbar-slot', 'composer-slot']
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((el) => el && !el.hidden && el.offsetHeight > 0)
|
||||
.map((el) => el.getBoundingClientRect().top);
|
||||
const viewportBottom = window.visualViewport ? window.visualViewport.height + window.visualViewport.offsetTop : window.innerHeight;
|
||||
const edge = tops.length ? Math.min(...tops, viewportBottom) : viewportBottom;
|
||||
host.style.bottom = `${Math.max(12, Math.round(window.innerHeight - edge + 12))}px`;
|
||||
}
|
||||
|
||||
const TOAST_ICONS = { success: 'check', error: 'alert', info: 'info' };
|
||||
|
||||
/**
|
||||
* Короткое сообщение внизу экрана. kind: 'success' (галочка), 'error' (восклицание, дольше
|
||||
* висит), 'info' (i). action – { label, onClick } – кнопка справа («Повторить», «Отменить»).
|
||||
* Одинаковое сообщение подряд не дублируется – показанное просто продлевается.
|
||||
*/
|
||||
export function showToast(message, { kind = 'success', timeoutMs = 2500, action = null } = {}) {
|
||||
const text = String(message || '').trim();
|
||||
if (!text) return;
|
||||
const safeKind = TOAST_ICONS[kind] ? kind : 'success';
|
||||
|
||||
const host = ensureToastHost();
|
||||
placeToastHost(host);
|
||||
const same = [...host.children].find((el) => el.dataset.text === text && !el.classList.contains('is-hiding'));
|
||||
if (same?.restartToast) {
|
||||
same.restartToast();
|
||||
return;
|
||||
}
|
||||
while (host.children.length >= 3) host.firstElementChild.remove();
|
||||
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast--${kind}`;
|
||||
toast.textContent = text;
|
||||
host.append(toast);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.add('is-visible');
|
||||
});
|
||||
toast.className = `toast toast--${safeKind}`;
|
||||
toast.dataset.text = text;
|
||||
toast.setAttribute('role', safeKind === 'error' ? 'alert' : 'status');
|
||||
const icon = document.createElement('span');
|
||||
icon.className = 'toast__icon';
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.innerHTML = iconHtml(TOAST_ICONS[safeKind]);
|
||||
const body = document.createElement('span');
|
||||
body.className = 'toast__text';
|
||||
body.textContent = text;
|
||||
toast.append(icon, body);
|
||||
|
||||
let timer = 0;
|
||||
const hide = () => {
|
||||
window.clearTimeout(timer);
|
||||
if (toast.classList.contains('is-hiding')) return;
|
||||
toast.classList.remove('is-visible');
|
||||
toast.classList.add('is-hiding');
|
||||
setTimeout(() => toast.remove(), 220);
|
||||
};
|
||||
if (action?.label && typeof action.onClick === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'toast__action';
|
||||
button.textContent = action.label;
|
||||
button.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
hide();
|
||||
action.onClick();
|
||||
});
|
||||
toast.append(button);
|
||||
}
|
||||
// Касание закрывает сообщение раньше времени.
|
||||
toast.addEventListener('click', hide);
|
||||
host.append(toast);
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.add('is-visible');
|
||||
});
|
||||
|
||||
setTimeout(hide, Math.max(1200, Number(timeoutMs) || 2500));
|
||||
// Время на чтение: ошибки и длинный текст висят дольше.
|
||||
const base = Math.max(1200, Number(timeoutMs) || 2500);
|
||||
const forReading = 1500 + text.length * 45;
|
||||
const duration = Math.min(8000, Math.max(base, safeKind === 'error' ? Math.max(4000, forReading) : Math.min(forReading, base * 1.6)));
|
||||
toast.restartToast = () => {
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(hide, duration);
|
||||
};
|
||||
toast.restartToast();
|
||||
}
|
||||
|
||||
export function softHaptic(duration = 15) {
|
||||
@@ -217,6 +294,27 @@ export function createSkeletonCard(className = '') {
|
||||
return card;
|
||||
}
|
||||
|
||||
// Заглушка в форме настоящих экранов: 'list' – строки списка (круглый аватар, название, подпись),
|
||||
// 'post' – записи как в ленте и обсуждении (аватар слева, имя, две строки текста).
|
||||
export function createSkeletonRows(kind = 'list', count = 4) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = `skeleton-rows skeleton-rows--${kind}`;
|
||||
wrap.setAttribute('aria-busy', 'true');
|
||||
wrap.setAttribute('aria-label', 'Загрузка');
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'skeleton-row';
|
||||
row.innerHTML = kind === 'post'
|
||||
? '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-90"></span><span class="skeleton-line w-70"></span></span>'
|
||||
: '<span class="skeleton-avatar"></span><span class="skeleton-body"><span class="skeleton-line w-40"></span><span class="skeleton-line w-70"></span></span>';
|
||||
wrap.append(row);
|
||||
}
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Показать заглушку, только если загрузка заметно затянулась: быстрый ответ не должен мигать заглушкой.
|
||||
export const SKELETON_DELAY_MS = 500;
|
||||
|
||||
export function normalizeChannelDescription(value) {
|
||||
const text = String(value == null ? '' : value).trim().replace(/\s+/g, ' ');
|
||||
if (!text) return '';
|
||||
@@ -276,3 +374,37 @@ export async function longPressFeel(el, delayMs = 130) {
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.max(60, Number(delayMs) || 130)));
|
||||
if (node) node.classList.remove('is-long-press');
|
||||
}
|
||||
|
||||
// Репост в блокчейне ещё дорабатывается (обещан скоро) – кнопка уже на месте, как четвёртая в ряду действий.
|
||||
// Когда появится, здесь вызывать настоящий обработчик.
|
||||
export const REPOSTS_ENABLED = false;
|
||||
export function notifyRepostSoon() {
|
||||
showToast('Репосты скоро появятся', { kind: 'info' });
|
||||
}
|
||||
|
||||
// Общая карточка «не удалось загрузить»: короткий заголовок, причина в пару строк и крупная кнопка снизу.
|
||||
export function createLoadErrorCard({ title, message, onRetry, secondary = null }) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack channels-status';
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = title;
|
||||
const details = document.createElement('p');
|
||||
details.className = 'meta-muted';
|
||||
// Под текстом и так кнопка «Повторить» – совет «повторите попытку» в тексте лишний.
|
||||
details.textContent = String(message || '').replace(/\s*Повторите попытку[^.]*\.?\s*$/u, '').trim();
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.className = 'primary-btn';
|
||||
retry.textContent = 'Повторить';
|
||||
retry.addEventListener('click', onRetry);
|
||||
card.append(heading, details, retry);
|
||||
if (secondary) {
|
||||
const extra = document.createElement('button');
|
||||
extra.type = 'button';
|
||||
extra.className = 'secondary-btn';
|
||||
extra.textContent = secondary.label;
|
||||
extra.addEventListener('click', secondary.onClick);
|
||||
card.append(extra);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Настройки этого устройства (не аккаунта): звук сообщений и т. п. Хранятся в localStorage;
|
||||
// в приватном режиме живут до закрытия вкладки.
|
||||
const STORAGE_KEY = 'shine-device-prefs-v1';
|
||||
export const DEVICE_PREFS_EVENT = 'shine-device-prefs-updated';
|
||||
|
||||
let memory = null;
|
||||
|
||||
function readAll() {
|
||||
if (memory) return memory;
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
|
||||
memory = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
} catch {
|
||||
memory = {};
|
||||
}
|
||||
return memory;
|
||||
}
|
||||
|
||||
export function getDevicePref(name, fallback) {
|
||||
const value = readAll()[name];
|
||||
return value === undefined ? fallback : value;
|
||||
}
|
||||
|
||||
export function setDevicePref(name, value) {
|
||||
const all = { ...readAll(), [name]: value };
|
||||
memory = all;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
|
||||
} catch {
|
||||
// Нет места или приватный режим – настройка действует до перезагрузки.
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent(DEVICE_PREFS_EVENT, { detail: { name, value } }));
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// Настройки личных чатов на этом устройстве: «без звука» (навсегда или до срока) и «закреплён».
|
||||
// Сервер про них не знает: хранятся в localStorage отдельно для каждого аккаунта.
|
||||
// Список «без звука» дублируется в Cache Storage, чтобы его видел service worker:
|
||||
// push о новом сообщении от такого собеседника не показывается, пока приложение закрыто.
|
||||
import { normalizeDmChatId, state } from '../state.js';
|
||||
|
||||
const STORAGE_PREFIX = 'shine-dm-chat-prefs-v1:';
|
||||
const SW_CACHE_NAME = 'shine-dm-prefs';
|
||||
const SW_CACHE_URL = '/__shine/dm-muted.json';
|
||||
export const DM_CHAT_PREFS_EVENT = 'shine-dm-chat-prefs-updated';
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
// muted – список собеседников; mutedUntil – срок (мс) для тех, у кого звук выключен на время.
|
||||
// Нет срока – «без звука» навсегда (так же понимают список и прежние версии приложения).
|
||||
function parsePrefs(raw) {
|
||||
const untilRaw = raw?.mutedUntil && typeof raw.mutedUntil === 'object' ? raw.mutedUntil : {};
|
||||
// Без прототипа: логин вроде «constructor» не должен находить чужие свойства.
|
||||
const mutedUntil = Object.create(null);
|
||||
Object.entries(untilRaw).forEach(([id, until]) => {
|
||||
if (Number(until) > 0) mutedUntil[id] = Number(until);
|
||||
});
|
||||
return {
|
||||
muted: Array.isArray(raw?.muted) ? raw.muted.map(String) : [],
|
||||
pinned: Array.isArray(raw?.pinned) ? raw.pinned.map(String) : [],
|
||||
mutedUntil,
|
||||
};
|
||||
}
|
||||
|
||||
function readPrefs() {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return parsePrefs(null);
|
||||
try {
|
||||
return parsePrefs(JSON.parse(localStorage.getItem(STORAGE_PREFIX + owner) || '{}'));
|
||||
} catch {
|
||||
return parsePrefs(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Чей срок «без звука» ещё не вышел: { собеседник: срок, 0 – навсегда }.
|
||||
function activeMutes(prefs, now = Date.now()) {
|
||||
const result = Object.create(null);
|
||||
prefs.muted.forEach((id) => {
|
||||
const until = Number(prefs.mutedUntil[id] || 0);
|
||||
if (!until || until > now) result[id] = until;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
function writePrefs(prefs) {
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
// Истёкшие сроки при записи убираются, чтобы список не копился.
|
||||
const active = activeMutes(prefs);
|
||||
const next = {
|
||||
muted: prefs.muted.filter((id) => id in active),
|
||||
pinned: prefs.pinned,
|
||||
mutedUntil: Object.fromEntries(Object.entries(active).filter(([, until]) => until > 0)),
|
||||
};
|
||||
try {
|
||||
localStorage.setItem(STORAGE_PREFIX + owner, JSON.stringify(next));
|
||||
} catch {
|
||||
// Приватный режим или переполненное хранилище: настройка проживёт до перезагрузки вкладки.
|
||||
}
|
||||
void syncMutedForServiceWorker();
|
||||
scheduleExpiry(next);
|
||||
window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT));
|
||||
}
|
||||
|
||||
// Когда срок «без звука» выходит, пока приложение открыто, списки и шапка чата узнают об этом
|
||||
// тем же событием, что и о ручном включении звука.
|
||||
let expiryTimer = 0;
|
||||
function scheduleExpiry(prefs = readPrefs()) {
|
||||
if (expiryTimer) window.clearTimeout(expiryTimer);
|
||||
expiryTimer = 0;
|
||||
const now = Date.now();
|
||||
const nearest = Math.min(...Object.values(activeMutes(prefs, now)).filter((until) => until > now));
|
||||
if (!Number.isFinite(nearest)) return;
|
||||
expiryTimer = window.setTimeout(() => {
|
||||
expiryTimer = 0;
|
||||
void syncMutedForServiceWorker();
|
||||
window.dispatchEvent(new CustomEvent(DM_CHAT_PREFS_EVENT));
|
||||
scheduleExpiry();
|
||||
}, Math.min(nearest - now + 250, 2 ** 31 - 1));
|
||||
}
|
||||
|
||||
function ensureExpiryScheduled(prefs) {
|
||||
if (!expiryTimer) scheduleExpiry(prefs);
|
||||
}
|
||||
|
||||
// Все аккаунты этого устройства: push приходит с toLogin, и worker сверяет пару «кому – от кого».
|
||||
// Формат для worker: { владелец: { собеседник: срок в мс, 0 – навсегда } }.
|
||||
async function syncMutedForServiceWorker() {
|
||||
try {
|
||||
if (!globalThis.caches) return;
|
||||
const muted = {};
|
||||
const now = Date.now();
|
||||
for (let i = 0; i < localStorage.length; i += 1) {
|
||||
const key = localStorage.key(i) || '';
|
||||
if (!key.startsWith(STORAGE_PREFIX)) continue;
|
||||
const active = activeMutes(parsePrefs(JSON.parse(localStorage.getItem(key) || '{}')), now);
|
||||
if (Object.keys(active).length) muted[key.slice(STORAGE_PREFIX.length)] = active;
|
||||
}
|
||||
const cache = await caches.open(SW_CACHE_NAME);
|
||||
await cache.put(SW_CACHE_URL, new Response(JSON.stringify(muted), { headers: { 'Content-Type': 'application/json' } }));
|
||||
} catch {
|
||||
// Без Cache Storage «без звука» действует только пока приложение открыто.
|
||||
}
|
||||
}
|
||||
|
||||
function toggleIn(listName, chatId, enabled) {
|
||||
const id = normalizeDmChatId(chatId);
|
||||
if (!id) return;
|
||||
const prefs = readPrefs();
|
||||
const rest = prefs[listName].filter((x) => x !== id);
|
||||
prefs[listName] = enabled ? [id, ...rest] : rest;
|
||||
return { id, prefs };
|
||||
}
|
||||
|
||||
export function isDmChatMuted(chatId) {
|
||||
const prefs = readPrefs();
|
||||
ensureExpiryScheduled(prefs);
|
||||
return normalizeDmChatId(chatId) in activeMutes(prefs);
|
||||
}
|
||||
|
||||
// Срок «без звука»: null – звук включён, 0 – выключен навсегда, иначе время (мс), когда включится.
|
||||
export function getDmChatMutedUntil(chatId) {
|
||||
const active = activeMutes(readPrefs());
|
||||
const id = normalizeDmChatId(chatId);
|
||||
return id in active ? active[id] : null;
|
||||
}
|
||||
|
||||
// untilMs – когда звук включится сам; 0 – «навсегда».
|
||||
export function setDmChatMuted(chatId, muted, { untilMs = 0 } = {}) {
|
||||
const result = toggleIn('muted', chatId, muted);
|
||||
if (!result) return;
|
||||
const { id, prefs } = result;
|
||||
if (muted && Number(untilMs) > Date.now()) prefs.mutedUntil[id] = Number(untilMs);
|
||||
else delete prefs.mutedUntil[id];
|
||||
writePrefs(prefs);
|
||||
}
|
||||
|
||||
export function isDmChatPinned(chatId) {
|
||||
return readPrefs().pinned.includes(normalizeDmChatId(chatId));
|
||||
}
|
||||
|
||||
export function setDmChatPinned(chatId, pinned) {
|
||||
const result = toggleIn('pinned', chatId, pinned);
|
||||
if (result) writePrefs(result.prefs);
|
||||
}
|
||||
|
||||
// Порядок закреплённых: последний закреплённый – выше всех.
|
||||
export function getPinnedDmChats() {
|
||||
return readPrefs().pinned;
|
||||
}
|
||||
|
||||
// Чаты «без звука» – для списка в настройках уведомлений: [{ chatId, until }], until 0 – навсегда.
|
||||
export function getMutedDmChats() {
|
||||
const prefs = readPrefs();
|
||||
ensureExpiryScheduled(prefs);
|
||||
return Object.entries(activeMutes(prefs)).map(([chatId, until]) => ({ chatId, until }));
|
||||
}
|
||||
|
||||
// «до 14:30», «до завтра, 9:00», «до 20 октября, 9:00»; для «навсегда» – пустая строка.
|
||||
export function formatDmMuteUntil(until, now = new Date()) {
|
||||
const value = Number(until || 0);
|
||||
if (!value) return '';
|
||||
const date = new Date(value);
|
||||
const time = date.toLocaleTimeString('ru-RU', { hour: 'numeric', minute: '2-digit' });
|
||||
const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const days = Math.round((startOfDay(date) - startOfDay(now)) / 86400000);
|
||||
if (days <= 0) return `до ${time}`;
|
||||
if (days === 1) return `до завтра, ${time}`;
|
||||
return `до ${date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}, ${time}`;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Загрузка истории личной переписки с сервера страницами и разбор её в локальный state.
|
||||
// Нужна и ленте чата (подгрузка вверх), и поиску по переписке, и экрану «Медиа и файлы».
|
||||
import { addAppLogEntry, addSignedMessageToChat, authService, normalizeDmChatId, state } from '../state.js';
|
||||
import { loadEncryptedUserSecrets } from './key-vault.js';
|
||||
|
||||
export const DM_HISTORY_PAGE_SIZE = 50;
|
||||
|
||||
// Чаты, история которых в этой вкладке загружена до самого начала: новые сообщения дальше
|
||||
// приходят по WebSocket, и повторно листать сервер не нужно.
|
||||
const fullyLoadedChats = new Set();
|
||||
const fullLoads = new Map();
|
||||
|
||||
// Ключ с владельцем: после входа в другой аккаунт той же вкладкой история грузится заново.
|
||||
function loadKey(chatId) {
|
||||
return `${String(state.session?.login || '').trim().toLowerCase()}|${normalizeDmChatId(chatId)}`;
|
||||
}
|
||||
|
||||
export function isDmHistoryFullyLoaded(chatId) {
|
||||
return fullyLoadedChats.has(loadKey(chatId));
|
||||
}
|
||||
|
||||
export function markDmHistoryFullyLoaded(chatId) {
|
||||
fullyLoadedChats.add(loadKey(chatId));
|
||||
}
|
||||
|
||||
// baseKey и messageKey: «from|to|timeMs|nonce».
|
||||
export function parseBaseKey(baseKey) {
|
||||
const raw = String(baseKey || '').trim();
|
||||
const parts = raw.split('|');
|
||||
if (parts.length < 4) return null;
|
||||
const fromLogin = parts[0] || '';
|
||||
const toLogin = parts[1] || '';
|
||||
const timeMs = Number(parts[2] || 0);
|
||||
const nonce = Number(parts[3] || 0);
|
||||
if (!fromLogin || !toLogin || !Number.isFinite(timeMs) || !Number.isFinite(nonce)) return null;
|
||||
return { fromLogin, toLogin, timeMs, nonce };
|
||||
}
|
||||
|
||||
// Время сообщения: из ключа (оно подписано), для ещё не отправленных – из временного id.
|
||||
export function resolveMessageTimeMs(msg) {
|
||||
const base = parseBaseKey(msg?.baseKey);
|
||||
if (base?.timeMs && Number.isFinite(base.timeMs) && base.timeMs > 0) return base.timeMs;
|
||||
|
||||
const messageKey = String(msg?.messageKey || '').trim();
|
||||
if (messageKey) {
|
||||
const parts = messageKey.split('|');
|
||||
const timeMs = Number(parts[2] || 0);
|
||||
if (parts.length >= 4 && Number.isFinite(timeMs) && timeMs > 0) return timeMs;
|
||||
}
|
||||
|
||||
const tempId = String(msg?.tempId || '').trim();
|
||||
if (tempId.startsWith('tmp-')) {
|
||||
const ts = Number(tempId.split('-')[1] || 0);
|
||||
if (Number.isFinite(ts) && ts > 0) return ts;
|
||||
}
|
||||
|
||||
const fallback = Number(msg?.createdAtMs || 0);
|
||||
if (Number.isFinite(fallback) && fallback > 0) return fallback;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function mergeDirectMessagesPage(chatId, payloadMessages) {
|
||||
const items = Array.isArray(payloadMessages) ? [...payloadMessages] : [];
|
||||
items.sort((a, b) => Number(a?.timeMs || 0) - Number(b?.timeMs || 0));
|
||||
// Ключ расшифровки достаём из хранилища один раз на страницу: по сообщению это занимало
|
||||
// ~25 мс (расшифровка контейнера ключей), и страница из 50 сообщений грузилась секунду.
|
||||
let clientPrivatePkcs8B64 = '';
|
||||
if (items.length) {
|
||||
try {
|
||||
const secrets = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
|
||||
clientPrivatePkcs8B64 = String(secrets?.clientKey || '').trim();
|
||||
} catch {
|
||||
// Расшифровка ниже сама сообщит, чего не хватает.
|
||||
}
|
||||
}
|
||||
for (const item of items) {
|
||||
const blobB64 = String(item?.blobB64 || '').trim();
|
||||
const messageKey = String(item?.messageKey || '').trim();
|
||||
if (!blobB64 || !messageKey) continue;
|
||||
try {
|
||||
const parsed = authService.parseSignedMessageBlob(blobB64);
|
||||
let text = '';
|
||||
try {
|
||||
const decrypted = await authService.decryptSignedMessageContent({
|
||||
parsed,
|
||||
login: state.session.login,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
clientPrivatePkcs8B64,
|
||||
});
|
||||
text = String(decrypted?.text || '');
|
||||
} catch (error) {
|
||||
text = `Нерасшифрованное сообщение (${error?.message || 'decrypt failed'})`;
|
||||
}
|
||||
addSignedMessageToChat({
|
||||
chatId,
|
||||
messageKey,
|
||||
baseKey: String(item?.baseKey || parsed?.baseKey || ''),
|
||||
from: Number(parsed?.messageType || 0) === 2 ? 'out' : 'in',
|
||||
text,
|
||||
messageType: Number(parsed?.messageType || item?.messageType || 0),
|
||||
unread: false,
|
||||
readAtMs: Number(item?.readAtMs || 0),
|
||||
rawBlobB64: blobB64,
|
||||
revisionTimeMs: Number(item?.revisionTimeMs || parsed?.revisionTimeMs || 0),
|
||||
deliveryState: String(item?.deliveryState || ''),
|
||||
});
|
||||
} catch (error) {
|
||||
addAppLogEntry({
|
||||
level: 'warn',
|
||||
source: 'dm-history',
|
||||
message: 'Не удалось обработать сообщение из истории DM',
|
||||
details: { chatId, messageKey, error: error?.message || 'unknown' },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Листает историю от новых к старым до конца. onPage получает число загруженных страниц
|
||||
// (для подписи «Загружаю историю…»). Параллельные вызовы для одного чата делят одну загрузку.
|
||||
export function loadFullDmHistory(chatId, { onPage } = {}) {
|
||||
const id = normalizeDmChatId(chatId);
|
||||
const key = loadKey(id);
|
||||
if (fullyLoadedChats.has(key)) return Promise.resolve({ peer: null });
|
||||
if (fullLoads.has(key)) return fullLoads.get(key);
|
||||
const run = (async () => {
|
||||
let beforeTimeMs = 0;
|
||||
let beforeMessageKey = '';
|
||||
let peer = null;
|
||||
for (let page = 1; ; page += 1) {
|
||||
const payload = await authService.getDirectMessages({
|
||||
peerLogin: id,
|
||||
limit: DM_HISTORY_PAGE_SIZE,
|
||||
beforeTimeMs,
|
||||
beforeMessageKey,
|
||||
});
|
||||
peer = peer || payload?.peer || null;
|
||||
await mergeDirectMessagesPage(id, payload?.messages || []);
|
||||
onPage?.(page);
|
||||
const nextTime = Number(payload?.nextBeforeTimeMs || 0);
|
||||
const nextKey = String(payload?.nextBeforeMessageKey || '').trim();
|
||||
// Сервер без курсора или курсор не сдвинулся – дальше листать нечего.
|
||||
if (!payload?.hasMore || (!nextTime && !nextKey) || (nextTime === beforeTimeMs && nextKey === beforeMessageKey)) break;
|
||||
beforeTimeMs = nextTime;
|
||||
beforeMessageKey = nextKey;
|
||||
}
|
||||
fullyLoadedChats.add(key);
|
||||
return { peer };
|
||||
})();
|
||||
fullLoads.set(key, run);
|
||||
run.finally(() => fullLoads.delete(key)).catch(() => {});
|
||||
return run;
|
||||
}
|
||||
@@ -72,7 +72,7 @@ function makeFrame({ prevHash, back32Hash=ZERO_HASH, blockNumber, type, subType,
|
||||
export const KEY_ROTATION_REASONS = Object.freeze([
|
||||
{ code:1, label:'Обычная смена пароля / ключей' },
|
||||
{ code:2, label:'Возможная компрометация ключей' },
|
||||
{ code:3, label:'Подтверждённая компрометация — откат истории' },
|
||||
{ code:3, label:'Подтверждённая компрометация – откат истории' },
|
||||
{ code:4, label:'Восстановление доступа' },
|
||||
]);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user