SHA256
Compare commits
56
Commits
dda21a54ff
...
ui-polish
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
bca788c5e6 | ||
|
|
68eec2b28b | ||
|
|
694aaf1f0e | ||
|
|
5caa4ce0ae | ||
|
|
af5b26c934 | ||
|
|
6997bc7600 | ||
|
|
9eedbf60a8 | ||
|
|
6294646922 | ||
|
|
42797b1a43 | ||
|
|
8c3751aba0 | ||
|
|
f40353725e | ||
|
|
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 | ||
|
|
74bace639c |
@@ -79,6 +79,7 @@ shine-solana/shine/scripts/**/TEMP_*.md
|
|||||||
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
||||||
ESP32/esp32-config-tool/
|
ESP32/esp32-config-tool/
|
||||||
ESP32/local-sketches/
|
ESP32/local-sketches/
|
||||||
|
ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/
|
||||||
ESP32/**/.git/
|
ESP32/**/.git/
|
||||||
ESP32/**/.idea/
|
ESP32/**/.idea/
|
||||||
ESP32-wallet/.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-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-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" ;;
|
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-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-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" ;;
|
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" ;;
|
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown mode: ${MODE}" >&2
|
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
|
exit 2
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|||||||
@@ -15,8 +15,10 @@
|
|||||||
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
||||||
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
||||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
- `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_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
||||||
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
- `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/` и теперь является основным
|
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
||||||
|
|
||||||
## Запуск
|
## Запуск
|
||||||
@@ -31,5 +33,7 @@
|
|||||||
- `./burn.sh lvgl-official-based-test`
|
- `./burn.sh lvgl-official-based-test`
|
||||||
- `./burn.sh lvgl-subserver-touch-test`
|
- `./burn.sh lvgl-subserver-touch-test`
|
||||||
- `./burn.sh lvgl-russian-font-test`
|
- `./burn.sh lvgl-russian-font-test`
|
||||||
|
- `./burn.sh breath-dual-mode-monitor`
|
||||||
- `./burn.sh usb-contact-test`
|
- `./burn.sh usb-contact-test`
|
||||||
- `./burn.sh usb-contact-debug-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_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/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`
|
- `main-device/test_sketches/usb_contact_screen_start_stub/usb_contact_screen_start_stub.ino`
|
||||||
|
|
||||||
## Purpose
|
## 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.
|
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
|
## 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.
|
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
|
- reset/power cycle restores ordinary native USB boot
|
||||||
|
|
||||||
This version is intended to monitor breathing cadence from a dry-contact USB D-/D+ sensor.
|
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 DB_FORMAT_VERSION = 2;
|
||||||
public static final int SCHEMA_VERSION_1 = 1;
|
public static final int SCHEMA_VERSION_1 = 1;
|
||||||
public static final int SCHEMA_VERSION_31 = 31;
|
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_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.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() {}
|
private DatabaseInitializer() {}
|
||||||
|
|
||||||
@@ -119,9 +121,13 @@ public final class DatabaseInitializer {
|
|||||||
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
|
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
|
||||||
currentVersion = readCurrentSchemaVersion(conn);
|
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(
|
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 --------------------
|
// -------------------- MAPPER --------------------
|
||||||
|
|
||||||
private CurrentUserEntry mapRow(ResultSet rs) throws SQLException {
|
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);
|
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;
|
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_GetChannelsCounters_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListGroupChats200_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_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_GetUserCounters_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_SetChannelReadState_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_SetChannelReadState_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelsCounters_Request;
|
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_GetPersonalDiary_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_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_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_GetUserCounters_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SetChannelReadState_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SetChannelReadState_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.connections.Net_GetUserConnectionsGraph_Handler;
|
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(
|
private static final Map<String, JsonMessageHandler> HANDLERS = Map.ofEntries(
|
||||||
Map.entry("GetUser", new Net_GetUser_Handler()),
|
Map.entry("GetUser", new Net_GetUser_Handler()),
|
||||||
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
||||||
|
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
|
||||||
|
|
||||||
// --- auth ---
|
// --- auth ---
|
||||||
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
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(
|
private static final Map<String, Class<? extends Net_Request>> REQUEST_TYPES = Map.ofEntries(
|
||||||
Map.entry("GetUser", Net_GetUser_Request.class),
|
Map.entry("GetUser", Net_GetUser_Request.class),
|
||||||
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
||||||
|
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
|
||||||
|
|
||||||
// --- auth ---
|
// --- auth ---
|
||||||
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
||||||
|
|||||||
+4
-1
@@ -20,7 +20,10 @@ public final class RemoteUserOperationPolicy {
|
|||||||
"ClientErrorLog",
|
"ClientErrorLog",
|
||||||
"ClientDebugLog",
|
"ClientDebugLog",
|
||||||
"CloseActiveSession",
|
"CloseActiveSession",
|
||||||
"ResolveLoginForAuth"
|
"ResolveLoginForAuth",
|
||||||
|
// Публичный read-only поиск доступен и REMOTE-сессии.
|
||||||
|
"SearchChannels",
|
||||||
|
"SearchUsers"
|
||||||
);
|
);
|
||||||
|
|
||||||
private RemoteUserOperationPolicy() {}
|
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) {
|
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||||
Net_SearchUsers_Request req = (Net_SearchUsers_Request) baseRequest;
|
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(
|
return NetExceptionResponseFactory.error(
|
||||||
req,
|
req,
|
||||||
WireCodes.Status.BAD_REQUEST,
|
WireCodes.Status.BAD_REQUEST,
|
||||||
@@ -39,13 +40,18 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
CurrentUsersDAO dao = CurrentUsersDAO.getInstance();
|
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<>();
|
List<String> logins = new ArrayList<>();
|
||||||
for (CurrentUserEntry u : users) {
|
List<Net_SearchUsers_Response.UserItem> users = new ArrayList<>();
|
||||||
if (u != null && u.getLogin() != null) {
|
for (var card : cards) {
|
||||||
logins.add(u.getLogin()); // регистр как в БД
|
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();
|
Net_SearchUsers_Response resp = new Net_SearchUsers_Response();
|
||||||
@@ -53,6 +59,7 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
|||||||
resp.setRequestId(req.getRequestId());
|
resp.setRequestId(req.getRequestId());
|
||||||
resp.setStatus(WireCodes.Status.OK);
|
resp.setStatus(WireCodes.Status.OK);
|
||||||
resp.setLogins(logins);
|
resp.setLogins(logins);
|
||||||
|
resp.setUsers(users);
|
||||||
|
|
||||||
log.info("✅ SearchUsers ok: prefix='{}', isServer={} -> {}", prefix, isServer, logins.size());
|
log.info("✅ SearchUsers ok: prefix='{}', isServer={} -> {}", prefix, isServer, logins.size());
|
||||||
return resp;
|
return resp;
|
||||||
|
|||||||
+3
@@ -19,7 +19,10 @@ public class Net_SearchUsers_Request extends Net_Request {
|
|||||||
|
|
||||||
private String prefix;
|
private String prefix;
|
||||||
private Boolean isServer;
|
private Boolean isServer;
|
||||||
|
private Integer limit;
|
||||||
|
|
||||||
|
public Integer getLimit() { return limit; }
|
||||||
|
public void setLimit(Integer value) { limit = value; }
|
||||||
public String getPrefix() { return prefix; }
|
public String getPrefix() { return prefix; }
|
||||||
public void setPrefix(String prefix) { this.prefix = prefix; }
|
public void setPrefix(String prefix) { this.prefix = prefix; }
|
||||||
public Boolean getIsServer() { return isServer; }
|
public Boolean getIsServer() { return isServer; }
|
||||||
|
|||||||
+14
@@ -23,6 +23,20 @@ import java.util.List;
|
|||||||
public class Net_SearchUsers_Response extends Net_Response {
|
public class Net_SearchUsers_Response extends Net_Response {
|
||||||
|
|
||||||
private List<String> logins = new ArrayList<>();
|
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 List<String> getLogins() { return logins; }
|
||||||
public void setLogins(List<String> logins) { this.logins = 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.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.AtomicMoveNotSupportedException;
|
import java.nio.file.AtomicMoveNotSupportedException;
|
||||||
import java.nio.file.FileAlreadyExistsException;
|
import java.nio.file.FileAlreadyExistsException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.LinkOption;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.nio.file.attribute.PosixFilePermission;
|
import java.nio.file.attribute.PosixFilePermission;
|
||||||
@@ -37,10 +41,10 @@ import java.util.regex.Pattern;
|
|||||||
* имя, расширение, MIME или владельца внутри пути файла. Одинаковые байты всех
|
* имя, расширение, MIME или владельца внутри пути файла. Одинаковые байты всех
|
||||||
* пользователей дедуплицируются в один объект: data/public-files/<sha256>.
|
* пользователей дедуплицируются в один объект: data/public-files/<sha256>.
|
||||||
*
|
*
|
||||||
* В production GET/HEAD /files/<sha256> рекомендуется отдавать Caddy напрямую с
|
* GET поддерживает HTTP Range для потокового просмотра видео без полной загрузки.
|
||||||
* того же каталога и кэшировать Cloudflare. Этот servlet оставляет GET/HEAD как
|
* Проверка SHA-256 выполняется при PUT; GET/HEAD читают метаданные файла без
|
||||||
* рабочий fallback; PUT всегда проходит через Java, с проверкой session-signature
|
* повторного хеширования всего содержимого. Caddy также может отдавать immutable
|
||||||
* и повторным вычислением SHA-256 полученных байтов.
|
* файлы напрямую, если настроен на корректную выдачу байтовых диапазонов и MIME.
|
||||||
*/
|
*/
|
||||||
public final class PublicFileServlet extends HttpServlet {
|
public final class PublicFileServlet extends HttpServlet {
|
||||||
|
|
||||||
@@ -202,29 +206,118 @@ public final class PublicFileServlet extends HttpServlet {
|
|||||||
|
|
||||||
String fileId = extractFileId(req);
|
String fileId = extractFileId(req);
|
||||||
Path target = fileId == null ? null : safeTarget(fileId);
|
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", "Файл не найден");
|
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
StoredObjectCheck stored = verifyStoredObject(target, fileId);
|
long size = Files.size(target);
|
||||||
if (!stored.valid()) {
|
String etag = "\"" + fileId + "\"";
|
||||||
Files.deleteIfExists(target);
|
resp.setHeader("ETag", etag);
|
||||||
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
resp.setHeader("Accept-Ranges", "bytes");
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.setStatus(HttpServletResponse.SC_OK);
|
|
||||||
resp.setContentType("application/octet-stream");
|
|
||||||
resp.setHeader("Content-Length", Long.toString(stored.size()));
|
|
||||||
resp.setHeader("ETag", "\"" + fileId + "\"");
|
|
||||||
resp.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
resp.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||||
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
|
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
|
||||||
if (!headOnly) {
|
resp.setContentType(detectContentType(target));
|
||||||
try (InputStream in = Files.newInputStream(target); OutputStream out = resp.getOutputStream()) {
|
|
||||||
in.transferTo(out);
|
// По 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 {
|
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-Origin", "*");
|
||||||
resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, PUT, OPTIONS");
|
resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, PUT, OPTIONS");
|
||||||
resp.setHeader("Access-Control-Allow-Headers",
|
resp.setHeader("Access-Control-Allow-Headers",
|
||||||
"Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Content-Length, X-Shine-Signature");
|
"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");
|
resp.setHeader("Access-Control-Expose-Headers", "Content-Length, ETag, Accept-Ranges, Content-Range, Content-Type");
|
||||||
resp.setHeader("Vary", "Origin");
|
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.15
|
client.version=1.19.32
|
||||||
server.version=1.12.13
|
server.version=1.15.0
|
||||||
|
|||||||
@@ -37,6 +37,28 @@ chmod 755 /home/player/shine-public-files
|
|||||||
|
|
||||||
## 2. Caddyfile
|
## 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**.
|
Маршруты `/files/*` должны стоять **до SPA fallback**.
|
||||||
|
|
||||||
```caddyfile
|
```caddyfile
|
||||||
@@ -92,7 +114,7 @@ shineup.me {
|
|||||||
|
|
||||||
Если используется отдельный `:80` site block, тот же `/files` routing нужно добавить и туда либо перенаправлять HTTP на HTTPS.
|
Если используется отдельный `:80` site block, тот же `/files` routing нужно добавить и туда либо перенаправлять HTTP на HTTPS.
|
||||||
|
|
||||||
После изменения:
|
После изменения любого варианта:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||||
@@ -142,6 +164,9 @@ UI дополнительно уже отправляет `Cache-Control: no-sto
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -I https://shineup.me/files/<sha256>
|
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>
|
||||||
```
|
```
|
||||||
|
|
||||||
Ожидается:
|
Ожидается:
|
||||||
|
|||||||
@@ -103,8 +103,9 @@ CADDY_CONFIG_PATH="$(ssh "$REMOTE_HOST" "set -e; \
|
|||||||
ROOT_CHECK_OUTPUT="$(ssh "$REMOTE_HOST" "set -euo pipefail; \
|
ROOT_CHECK_OUTPUT="$(ssh "$REMOTE_HOST" "set -euo pipefail; \
|
||||||
cfg='$CADDY_CONFIG_PATH'; \
|
cfg='$CADDY_CONFIG_PATH'; \
|
||||||
site='$EXPECTED_CADDY_SITE'; \
|
site='$EXPECTED_CADDY_SITE'; \
|
||||||
sudo awk -v site=\"\$site\" '
|
expected_root='$EXPECTED_CADDY_UI_ROOT'; \
|
||||||
BEGIN { in_site=0; depth=0; root_line=\"\"; root_lineno=0; have_site=0; }
|
sudo awk -v site=\"\$site\" -v expected_root=\"\$expected_root\" '
|
||||||
|
BEGIN { in_site=0; depth=0; roots=\"\"; have_site=0; have_expected=0; }
|
||||||
{
|
{
|
||||||
line=\$0;
|
line=\$0;
|
||||||
trimmed=line;
|
trimmed=line;
|
||||||
@@ -119,9 +120,12 @@ ROOT_CHECK_OUTPUT="$(ssh "$REMOTE_HOST" "set -euo pipefail; \
|
|||||||
next;
|
next;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (trimmed ~ /^root[[:space:]]+\\*[[:space:]]+/ && root_line == \"\") {
|
if (trimmed ~ /^root[[:space:]]+\\*[[:space:]]+/) {
|
||||||
root_line=line;
|
root_entry=NR \":\" line;
|
||||||
root_lineno=NR;
|
roots = roots (roots == \"\" ? \"\" : \"\\n\") root_entry;
|
||||||
|
if (line ~ expected_root) {
|
||||||
|
have_expected=1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
opens=gsub(/\\{/, \"{\", line);
|
opens=gsub(/\\{/, \"{\", line);
|
||||||
closes=gsub(/\\}/, \"}\", line);
|
closes=gsub(/\\}/, \"}\", line);
|
||||||
@@ -136,11 +140,15 @@ ROOT_CHECK_OUTPUT="$(ssh "$REMOTE_HOST" "set -euo pipefail; \
|
|||||||
print \"SITE_NOT_FOUND\";
|
print \"SITE_NOT_FOUND\";
|
||||||
exit 0;
|
exit 0;
|
||||||
}
|
}
|
||||||
if (root_line == \"\") {
|
if (roots == \"\") {
|
||||||
print \"ROOT_NOT_FOUND\";
|
print \"ROOT_NOT_FOUND\";
|
||||||
exit 0;
|
exit 0;
|
||||||
}
|
}
|
||||||
print root_lineno \":\" root_line;
|
if (have_expected) {
|
||||||
|
print \"OK\";
|
||||||
|
exit 0;
|
||||||
|
}
|
||||||
|
print roots;
|
||||||
}
|
}
|
||||||
' \"\$cfg\"")"
|
' \"\$cfg\"")"
|
||||||
|
|
||||||
@@ -160,8 +168,9 @@ elif [[ "$ROOT_CHECK_OUTPUT" == "ROOT_NOT_FOUND" ]]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "WARN: proceeding due to ALLOW_CADDY_MISMATCH=1"
|
echo "WARN: proceeding due to ALLOW_CADDY_MISMATCH=1"
|
||||||
elif [[ "$ROOT_CHECK_OUTPUT" != *"$EXPECTED_CADDY_UI_ROOT"* ]]; then
|
elif [[ "$ROOT_CHECK_OUTPUT" != "OK" ]]; then
|
||||||
echo "ERROR: Caddy root mismatch for site $EXPECTED_CADDY_SITE. Found: $ROOT_CHECK_OUTPUT" >&2
|
echo "ERROR: Caddy root mismatch for site $EXPECTED_CADDY_SITE. Found roots:" >&2
|
||||||
|
echo "$ROOT_CHECK_OUTPUT" >&2
|
||||||
echo "Caddy config: $CADDY_CONFIG_PATH" >&2
|
echo "Caddy config: $CADDY_CONFIG_PATH" >&2
|
||||||
echo "Expected path fragment: $EXPECTED_CADDY_UI_ROOT" >&2
|
echo "Expected path fragment: $EXPECTED_CADDY_UI_ROOT" >&2
|
||||||
if [[ "$ALLOW_CADDY_MISMATCH" != "1" ]]; then
|
if [[ "$ALLOW_CADDY_MISMATCH" != "1" ]]; then
|
||||||
|
|||||||
@@ -118,7 +118,7 @@
|
|||||||
|
|
||||||
### Назначение
|
### Назначение
|
||||||
|
|
||||||
Поиск пользователей по префиксу логина. Операция зарегистрирована в серверном API и используется как вспомогательная dev/test операция.
|
Поиск пользователей по префиксу логина и фрагменту публичного имени (`first_name`, `last_name`) без учёта регистра и с нормализацией `ё/е`. Совместимый ответ — массив строк `logins`.
|
||||||
При необходимости можно включить фильтр только по server PDA.
|
При необходимости можно включить фильтр только по server PDA.
|
||||||
|
|
||||||
### Запрос
|
### Запрос
|
||||||
@@ -129,12 +129,14 @@
|
|||||||
"requestId": "search-001",
|
"requestId": "search-001",
|
||||||
"payload": {
|
"payload": {
|
||||||
"prefix": "an",
|
"prefix": "an",
|
||||||
"isServer": true
|
"isServer": true,
|
||||||
|
"limit": 10
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `prefix` — обязательный префикс логина.
|
- `prefix` — обязательный поисковый фрагмент (до 120 символов); логины ищутся по началу, публичные имена — по подстроке.
|
||||||
|
- `limit` — необязательное число результатов 1–50, по умолчанию **5** (совместимость с клиентами).
|
||||||
- `isServer` — необязательный boolean-флаг; если `true`, сервер вернёт только логины,
|
- `isServer` — необязательный boolean-флаг; если `true`, сервер вернёт только логины,
|
||||||
у которых в `solana_user_pda_current` стоит `is_server = true`.
|
у которых в `solana_user_pda_current` стоит `is_server = true`.
|
||||||
|
|
||||||
@@ -147,7 +149,11 @@
|
|||||||
"status": 200,
|
"status": 200,
|
||||||
"ok": true,
|
"ok": true,
|
||||||
"payload": {
|
"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`.
|
- `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.
|
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-состояние его блокчейна |
|
| `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 |
|
| `ResolveLoginForAuth` | `02_Authentication_API.md` | проверка login перед входом: LOCAL / REMOTE / NOT_FOUND / NO_ACCESS_SERVER + URL правильного access server |
|
||||||
| `AuthChallenge` | `02_Authentication_API.md` | challenge для создания новой сессии |
|
| `AuthChallenge` | `02_Authentication_API.md` | challenge для создания новой сессии |
|
||||||
| `CreateAuthSession` | `02_Authentication_API.md` | создание новой авторизованной сессии |
|
| `CreateAuthSession` | `02_Authentication_API.md` | создание новой авторизованной сессии |
|
||||||
|
|||||||
@@ -65,19 +65,55 @@ SHA256(received bytes) == sha256 из URL
|
|||||||
|
|
||||||
Если корректный объект уже существует и размер совпадает, PUT идемпотентно отвечает `alreadyExists=true`.
|
Если корректный объект уже существует и размер совпадает, 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
|
Для `GET` с одним диапазоном:
|
||||||
Cache-Control: public, max-age=31536000, immutable
|
|
||||||
ETag: "<sha256>"
|
```http
|
||||||
Content-Type: application/octet-stream
|
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`
|
## 5. Связь с `S:att`
|
||||||
|
|
||||||
@@ -101,4 +137,6 @@ https://<current-access-server>/files/<sha256>
|
|||||||
|
|
||||||
## 6. Preview
|
## 6. Preview
|
||||||
|
|
||||||
|
В UI видео со storage=server получает прямую ссылку `/files/<sha256>` (без полного `fetch` в Blob): браузер сам запрашивает диапазоны, читает длительность и загружает стартовый кадр. Размер берётся из `sz` вложения. Для Arweave частичная загрузка зависит от gateway.
|
||||||
|
|
||||||
Отдельных preview-файлов сейчас нет. `preAr`, `preSha256`, `previewAr`, `previewSha256` не являются частью текущего протокола.
|
Отдельных preview-файлов сейчас нет. `preAr`, `preSha256`, `previewAr`, `previewSha256` не являются частью текущего протокола.
|
||||||
|
|||||||
@@ -228,6 +228,24 @@ DeleteMessage принимает type=5/6. DeleteConversation принимает
|
|||||||
|
|
||||||
Это правило не меняет wire/API-формат DM и не меняет байтовый формат tombstone.
|
Это правило не меняет 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 тоже понимает.
|
||||||
|
- Ошибка отправки: временное сообщение («часики») убирается из ленты, текст возвращается в поле ввода, а тост называет причину и предлагает «Повторить» (отправить тот же текст ещё раз). Для вложений, уже загруженных на сервер, «Повторить» отправляет только DM с ключами, без новой загрузки файлов. Пузыри «Ошибка отправки: …» от имени пользователя в ленту больше не добавляются; при неудачной пересылке временное сообщение в целевом чате тоже убирается.
|
||||||
|
|
||||||
|
|
||||||
## 15. Файлы в личных сообщениях
|
## 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())
|
rel = Path(translated).relative_to(Path.cwd())
|
||||||
return str(ROOT / rel)
|
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):
|
def do_GET(self):
|
||||||
file_path = Path(self.translate_path(self.path.split("?", 1)[0]))
|
file_path = Path(self.translate_path(self.path.split("?", 1)[0]))
|
||||||
if file_path.exists() and file_path.is_file():
|
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) => {
|
self.addEventListener('push', (event) => {
|
||||||
let body = '';
|
let body = '';
|
||||||
let rawText = '';
|
let rawText = '';
|
||||||
@@ -130,7 +155,7 @@ self.addEventListener('push', (event) => {
|
|||||||
: 'SHiNE: входящее сообщение');
|
: 'SHiNE: входящее сообщение');
|
||||||
|
|
||||||
const notifyPromise = shouldNotify
|
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}` : 'Новое сообщение'),
|
body: body || (fromLogin ? `Новое сообщение от ${fromLogin}` : 'Новое сообщение'),
|
||||||
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
|
tag: callId || (kind === 'test_push' ? 'shine-test-push' : 'shine-direct-message'),
|
||||||
renotify: true,
|
renotify: true,
|
||||||
@@ -152,7 +177,7 @@ self.addEventListener('push', (event) => {
|
|||||||
{ action: 'decline', title: 'Сбросить' },
|
{ action: 'decline', title: 'Сбросить' },
|
||||||
]
|
]
|
||||||
: [],
|
: [],
|
||||||
})
|
})))
|
||||||
: Promise.resolve();
|
: Promise.resolve();
|
||||||
|
|
||||||
const closeOnStopPromise = kind === 'stop_call' && callId
|
const closeOnStopPromise = kind === 'stop_call' && callId
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 191 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 201 KiB |
+46
-12
@@ -39,32 +39,59 @@
|
|||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
window.__SHINE_BUILD_HASH__ = '20261007230300';
|
window.__SHINE_BUILD_HASH__ = '20261015230000';
|
||||||
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
|
||||||
</script>
|
</script>
|
||||||
<script>
|
<script>
|
||||||
(function attachStylesWithBuildHash() {
|
(function attachStylesWithBuildHash() {
|
||||||
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
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) => {
|
cssFiles.forEach((file) => {
|
||||||
const link = document.createElement('link');
|
const link = document.createElement('link');
|
||||||
link.rel = 'stylesheet';
|
link.rel = 'stylesheet';
|
||||||
link.href = `${file}?v=${v}`;
|
link.href = `${file}?v=${v}`;
|
||||||
|
link.onload = settle;
|
||||||
|
link.onerror = settle;
|
||||||
document.head.appendChild(link);
|
document.head.appendChild(link);
|
||||||
});
|
});
|
||||||
|
setTimeout(reveal, 4000);
|
||||||
}());
|
}());
|
||||||
</script>
|
</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>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="initial-splash" class="initial-splash" aria-label="Сияние">
|
<!-- Заставка повторяет верх экрана входа (те же классы и раскладка): смена на него незаметна. -->
|
||||||
<div class="initial-splash__logo-wrap">
|
<div id="initial-splash" class="initial-splash">
|
||||||
<img
|
<div class="initial-splash__frame">
|
||||||
class="initial-splash__logo"
|
<section class="auth-screen auth-screen--welcome">
|
||||||
src="./img/shine-logo-transparent-final.png"
|
<div class="auth-logo-wrap">
|
||||||
alt="Логотип Сияние"
|
<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>
|
||||||
<div class="initial-splash__brand">Сияние</div>
|
<script>
|
||||||
|
document.getElementById('initial-splash-host').textContent = window.location.host || 'shineup.me';
|
||||||
|
</script>
|
||||||
</div>
|
</div>
|
||||||
<div class="app-shell">
|
<div class="app-shell">
|
||||||
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
<div id="topbar-slot" class="topbar-slot" hidden></div>
|
||||||
@@ -445,11 +472,18 @@ window.__SHINE_BUILD_HASH__ = '20261007230300';
|
|||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
<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 v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
|
||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
script.type = 'module';
|
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);
|
document.body.appendChild(script);
|
||||||
}());
|
}());
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
+118
-16
@@ -3,6 +3,7 @@ import {
|
|||||||
getRoute,
|
getRoute,
|
||||||
PRE_AUTH_PAGES,
|
PRE_AUTH_PAGES,
|
||||||
syncTrackedRouteHistory,
|
syncTrackedRouteHistory,
|
||||||
|
consumeHistoryLayerPop,
|
||||||
} from './router.js';
|
} from './router.js';
|
||||||
import { renderToolbar } from './components/toolbar.js';
|
import { renderToolbar } from './components/toolbar.js';
|
||||||
import {
|
import {
|
||||||
@@ -16,6 +17,7 @@ import { initPwaInstallPromptHandling } from './services/pwa-install-service.js'
|
|||||||
import { initPwaPush } from './services/pwa-push-service.js';
|
import { initPwaPush } from './services/pwa-push-service.js';
|
||||||
import { initCallUiOverlay } from './services/call-ui-service.js';
|
import { initCallUiOverlay } from './services/call-ui-service.js';
|
||||||
import { showToast } from './services/channels-ux.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 { KeyRotationClient } from './services/key-rotation-service.js';
|
||||||
import {
|
import {
|
||||||
handleCallPushAction,
|
handleCallPushAction,
|
||||||
@@ -50,6 +52,8 @@ import {
|
|||||||
markOutgoingDeliveryState,
|
markOutgoingDeliveryState,
|
||||||
markOutgoingReadByBaseKey,
|
markOutgoingReadByBaseKey,
|
||||||
normalizeDmChatId,
|
normalizeDmChatId,
|
||||||
|
applyUrlServerLoginOverrideIfNeeded,
|
||||||
|
hasUrlEntrySettingsOverride,
|
||||||
setContacts,
|
setContacts,
|
||||||
} from './state.js';
|
} 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 loginPasswordView from './pages/login-password-view.js?v=202606201650';
|
||||||
import * as publicSupportQueueView from './pages/public-support-queue-view.js';
|
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 profileEditView from './pages/profile-edit-view.js';
|
||||||
import * as profilesView from './pages/profiles-view.js';
|
import * as profilesView from './pages/profiles-view.js';
|
||||||
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
import * as walletView from './pages/wallet-view.js?v=202609260900';
|
||||||
import * as settingsView from './pages/settings-view.js';
|
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 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 keyRotationView from './pages/key-rotation-view.js';
|
||||||
import * as accessServersView from './pages/access-servers-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 developerSettingsView from './pages/developer-settings-view.js';
|
||||||
import * as advancedSettingsView from './pages/advanced-settings-view.js';
|
import * as advancedSettingsView from './pages/advanced-settings-view.js';
|
||||||
import * as serverSettingsView from './pages/server-settings-view.js?v=202609260900';
|
import * as serverSettingsView from './pages/server-settings-view.js?v=202609260900';
|
||||||
@@ -90,25 +97,33 @@ import * as deviceCameraView from './pages/device-camera-view.js';
|
|||||||
import * as showKeysView from './pages/show-keys-view.js';
|
import * as showKeysView from './pages/show-keys-view.js';
|
||||||
import * as clientSessionView from './pages/device-session-view.js?v=202606131435';
|
import * as clientSessionView from './pages/device-session-view.js?v=202606131435';
|
||||||
import * as languageView from './pages/language-view.js';
|
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 appLogView from './pages/app-log-view.js';
|
||||||
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
||||||
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||||
import * as solanaRpcCheckView from './pages/solana-rpc-check-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 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 { confirmDialog } from './components/confirm-dialog.js';
|
||||||
import * as userProfileView from './pages/user-profile-view.js';
|
import * as userProfileView from './pages/user-profile-view.js';
|
||||||
import * as userProfileListView from './pages/user-profile-list-view.js';
|
import * as userProfileListView from './pages/user-profile-list-view.js';
|
||||||
import * as userRelationManageView from './pages/user-relation-manage-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 channelView from './pages/channel-view.js';
|
||||||
import * as channelAboutView from './pages/channel-about-view.js';
|
import * as channelAboutView from './pages/channel-about-view.js';
|
||||||
import * as channelDonateView from './pages/channel-donate-view.js';
|
import * as channelDonateView from './pages/channel-donate-view.js';
|
||||||
import * as channelThreadView from './pages/channel-thread-view.js';
|
import * as channelThreadView from './pages/channel-thread-view.js';
|
||||||
import * as addChannelView from './pages/add-channel-view.js';
|
import * as addChannelView from './pages/add-channel-view.js';
|
||||||
import * as addPersonalPublicChatView from './pages/add-personal-public-chat-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 networkView from './pages/network-view.js?v=202610130200';
|
||||||
import * as notificationsView from './pages/notifications-view.js?v=202609260900';
|
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||||
|
|
||||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||||
@@ -141,9 +156,12 @@ const routes = {
|
|||||||
'profiles-view': profilesView,
|
'profiles-view': profilesView,
|
||||||
'wallet-view': walletView,
|
'wallet-view': walletView,
|
||||||
'settings-view': settingsView,
|
'settings-view': settingsView,
|
||||||
|
'access-keys-view': accessKeysView,
|
||||||
'my-blockchain-view': myBlockchainView,
|
'my-blockchain-view': myBlockchainView,
|
||||||
|
'my-blockchain-history-view': myBlockchainHistoryView,
|
||||||
'key-rotation-view': keyRotationView,
|
'key-rotation-view': keyRotationView,
|
||||||
'access-servers-view': accessServersView,
|
'access-servers-view': accessServersView,
|
||||||
|
'settings-servers-view': settingsServersView,
|
||||||
'developer-settings-view': developerSettingsView,
|
'developer-settings-view': developerSettingsView,
|
||||||
'advanced-settings-view': advancedSettingsView,
|
'advanced-settings-view': advancedSettingsView,
|
||||||
'server-settings-view': serverSettingsView,
|
'server-settings-view': serverSettingsView,
|
||||||
@@ -158,6 +176,8 @@ const routes = {
|
|||||||
'show-keys-view': showKeysView,
|
'show-keys-view': showKeysView,
|
||||||
'device-session-view': clientSessionView,
|
'device-session-view': clientSessionView,
|
||||||
'language-view': languageView,
|
'language-view': languageView,
|
||||||
|
'appearance-view': appearanceView,
|
||||||
|
'notification-settings-view': notificationSettingsView,
|
||||||
'app-log-view': appLogView,
|
'app-log-view': appLogView,
|
||||||
'pwa-diagnostics-view': pwaDiagnosticsView,
|
'pwa-diagnostics-view': pwaDiagnosticsView,
|
||||||
'solana-users-init-view': solanaUsersInitView,
|
'solana-users-init-view': solanaUsersInitView,
|
||||||
@@ -165,10 +185,12 @@ const routes = {
|
|||||||
'messages-list': messagesList,
|
'messages-list': messagesList,
|
||||||
'contact-search-view': contactSearchView,
|
'contact-search-view': contactSearchView,
|
||||||
'chat-view': chatView,
|
'chat-view': chatView,
|
||||||
|
'chat-media-view': chatMediaView,
|
||||||
user: userProfileView,
|
user: userProfileView,
|
||||||
'user-profile-list-view': userProfileListView,
|
'user-profile-list-view': userProfileListView,
|
||||||
'user-relation-manage-view': userRelationManageView,
|
'user-relation-manage-view': userRelationManageView,
|
||||||
'channels-list': channelsList,
|
'channels-list': channelsList,
|
||||||
|
'search-view': searchView,
|
||||||
'channel-view': channelView,
|
'channel-view': channelView,
|
||||||
'channel-about-view': channelAboutView,
|
'channel-about-view': channelAboutView,
|
||||||
'channel-donate-view': channelDonateView,
|
'channel-donate-view': channelDonateView,
|
||||||
@@ -196,6 +218,35 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
|||||||
let currentCleanup = null;
|
let currentCleanup = null;
|
||||||
let pingIntervalId = null;
|
let pingIntervalId = null;
|
||||||
let reconnectIntervalId = 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 sessionRuntimeStarted = false;
|
||||||
let connectionState = '';
|
let connectionState = '';
|
||||||
let connectionStatusText = '';
|
let connectionStatusText = '';
|
||||||
@@ -220,6 +271,11 @@ const SCROLL_TO_BOTTOM_PAGE_IDS = new Set([
|
|||||||
'channel-thread-view',
|
'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([
|
const FILLED_ACTION_BUTTON_PAGE_IDS = new Set([
|
||||||
...PRE_AUTH_PAGES.filter((pageId) => pageId !== 'entry-settings-view'),
|
...PRE_AUTH_PAGES.filter((pageId) => pageId !== 'entry-settings-view'),
|
||||||
'settings-view',
|
'settings-view',
|
||||||
@@ -228,6 +284,7 @@ const FILLED_ACTION_BUTTON_PAGE_IDS = new Set([
|
|||||||
|
|
||||||
const SETTINGS_BORDERED_ACTION_PAGE_IDS = new Set([
|
const SETTINGS_BORDERED_ACTION_PAGE_IDS = new Set([
|
||||||
'access-servers-view',
|
'access-servers-view',
|
||||||
|
'settings-servers-view',
|
||||||
'server-settings-view',
|
'server-settings-view',
|
||||||
'arweave-uploads-view',
|
'arweave-uploads-view',
|
||||||
'developer-settings-view',
|
'developer-settings-view',
|
||||||
@@ -253,6 +310,7 @@ const GUEST_ALLOWED_PAGES = new Set([
|
|||||||
'language-view',
|
'language-view',
|
||||||
'network-view',
|
'network-view',
|
||||||
'channels-list',
|
'channels-list',
|
||||||
|
'search-view',
|
||||||
'channel-view',
|
'channel-view',
|
||||||
'channel-about-view',
|
'channel-about-view',
|
||||||
'channel-thread-view',
|
'channel-thread-view',
|
||||||
@@ -263,6 +321,8 @@ const GUEST_ALLOWED_PAGES = new Set([
|
|||||||
|
|
||||||
setClientErrorTransport((payload) => authService.reportClientUiError(payload));
|
setClientErrorTransport((payload) => authService.reportClientUiError(payload));
|
||||||
setClientErrorSentNotifier((payload) => {
|
setClientErrorSentNotifier((payload) => {
|
||||||
|
// Технические подробности – только с включёнными инструментами разработчика.
|
||||||
|
if (!isDeveloperToolsEnabled()) return;
|
||||||
const login = String(state.session.login || 'guest').trim();
|
const login = String(state.session.login || 'guest').trim();
|
||||||
const isoTs = new Date(Number(payload?.clientTs || Date.now())).toISOString();
|
const isoTs = new Date(Number(payload?.clientTs || Date.now())).toISOString();
|
||||||
showToast(`Ошибка отправлена на сервер · ${login} · ${isoTs}`);
|
showToast(`Ошибка отправлена на сервер · ${login} · ${isoTs}`);
|
||||||
@@ -601,6 +661,8 @@ async function unlockHiddenDmAudio() {
|
|||||||
|
|
||||||
async function playDmSignal({ extended = false } = {}) {
|
async function playDmSignal({ extended = false } = {}) {
|
||||||
try {
|
try {
|
||||||
|
// «Звук в открытом приложении» выключен в настройках уведомлений.
|
||||||
|
if (getDevicePref('dmSound', true) === false) return false;
|
||||||
if (!hiddenDmAudioUnlocked || !hiddenDmAudioContext) return false;
|
if (!hiddenDmAudioUnlocked || !hiddenDmAudioContext) return false;
|
||||||
if (hiddenDmAudioContext.state === 'suspended') {
|
if (hiddenDmAudioContext.state === 'suspended') {
|
||||||
await hiddenDmAudioContext.resume();
|
await hiddenDmAudioContext.resume();
|
||||||
@@ -886,7 +948,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
|||||||
const currentLogin = String(state.session.login || '').trim();
|
const currentLogin = String(state.session.login || '').trim();
|
||||||
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
if (!targetLogin || targetLogin.toLowerCase() === currentLogin.toLowerCase()) return true;
|
||||||
if (!savedProfileExists(targetLogin)) {
|
if (!savedProfileExists(targetLogin)) {
|
||||||
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`);
|
showToast(`Уведомление пришло профилю ${targetLogin}, который не сохранён на этом устройстве.`, { kind: 'info' });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -894,7 +956,8 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
|||||||
const question = kind === 'incoming_call'
|
const question = kind === 'incoming_call'
|
||||||
? `Входящий звонок для профиля «${targetLogin}». Переключиться на этот профиль?`
|
? `Входящий звонок для профиля «${targetLogin}». Переключиться на этот профиль?`
|
||||||
: `Это сообщение пришло профилю «${targetLogin}». Переключиться, чтобы открыть его?`;
|
: `Это сообщение пришло профилю «${targetLogin}». Переключиться, чтобы открыть его?`;
|
||||||
if (!window.confirm(question)) return false;
|
const confirmed = await confirmDialog({ title: 'Переключить профиль?', text: question, confirmLabel: 'Переключить' });
|
||||||
|
if (!confirmed) return false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await switchToSavedProfile(targetLogin);
|
await switchToSavedProfile(targetLogin);
|
||||||
@@ -906,7 +969,7 @@ async function ensurePushTargetProfile(payload = {}, { action = '' } = {}) {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showToast(`Не удалось переключить профиль: ${error?.message || 'unknown'}`);
|
showToast(toUserMessage(error, 'Не удалось переключить профиль.'), { kind: 'error' });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1236,7 +1299,17 @@ async function ensureSessionAfterWsReconnect() {
|
|||||||
return wsSessionRestoreInFlight;
|
return wsSessionRestoreInFlight;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Без инструментов разработчика – спокойное сообщение вместо окна со стеком вызовов,
|
||||||
|
// не чаще раза в полминуты (ошибка уже записана в журнал и отправлена на сервер).
|
||||||
|
let lastCrashNoticeAt = 0;
|
||||||
function showGlobalErrorAlert(title, details = {}) {
|
function showGlobalErrorAlert(title, details = {}) {
|
||||||
|
if (!isDeveloperToolsEnabled()) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastCrashNoticeAt < 30000) return;
|
||||||
|
lastCrashNoticeAt = now;
|
||||||
|
showToast('Что-то пошло не так. Сведения об ошибке уже отправлены разработчикам – попробуйте ещё раз.', { kind: 'error' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
const lines = [title];
|
const lines = [title];
|
||||||
if (details.message) lines.push(`Сообщение: ${details.message}`);
|
if (details.message) lines.push(`Сообщение: ${details.message}`);
|
||||||
if (details.pageId) lines.push(`Экран: ${details.pageId}`);
|
if (details.pageId) lines.push(`Экран: ${details.pageId}`);
|
||||||
@@ -1395,6 +1468,14 @@ async function redirectToActiveKeyRotationIfNeeded() {
|
|||||||
function renderApp() {
|
function renderApp() {
|
||||||
syncTrackedRouteHistory(window.location.pathname || '/');
|
syncTrackedRouteHistory(window.location.pathname || '/');
|
||||||
const route = getRoute();
|
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');
|
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)) {
|
if (!state.session.isAuthorized && !PRE_AUTH_PAGES.includes(pageId) && !GUEST_ALLOWED_PAGES.has(pageId)) {
|
||||||
@@ -1433,7 +1514,7 @@ function renderApp() {
|
|||||||
try {
|
try {
|
||||||
const chrome = createChromeController(showAppChrome, page.pageMeta?.shellMode);
|
const chrome = createChromeController(showAppChrome, page.pageMeta?.shellMode);
|
||||||
currentChromeCleanup = () => chrome.dispose();
|
currentChromeCleanup = () => chrome.dispose();
|
||||||
// В переписке нижняя панель прячется (pageMeta.hideToolbar), чтобы не отнимать место у сообщений.
|
// Нижняя панель видна везде, кроме экранов с pageMeta.hideToolbar (например, смена ключей).
|
||||||
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
if (showAppChrome && !page.pageMeta?.hideToolbar) {
|
||||||
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
mountSlot(toolbarEl, '--toolbar-height', renderToolbar(page.pageMeta.id, navigate));
|
||||||
toolbarHeightObserver?.sync?.();
|
toolbarHeightObserver?.sync?.();
|
||||||
@@ -1513,12 +1594,15 @@ async function ensureSessionRuntimeStarted() {
|
|||||||
if (!state.session.isAuthorized || sessionRuntimeStarted) return;
|
if (!state.session.isAuthorized || sessionRuntimeStarted) return;
|
||||||
sessionRuntimeStarted = true;
|
sessionRuntimeStarted = true;
|
||||||
|
|
||||||
await initPwaPush({
|
if (!isLocalPreviewHost()) {
|
||||||
authService,
|
await initPwaPush({
|
||||||
onLog: (entry) => addAppLogEntry(entry),
|
authService,
|
||||||
});
|
onLog: (entry) => addAppLogEntry(entry),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
startConnectionMonitor();
|
startConnectionMonitor();
|
||||||
|
startChannelsPrefetch();
|
||||||
|
|
||||||
if (reconnectIntervalId) {
|
if (reconnectIntervalId) {
|
||||||
window.clearInterval(reconnectIntervalId);
|
window.clearInterval(reconnectIntervalId);
|
||||||
@@ -1570,6 +1654,7 @@ async function init() {
|
|||||||
|
|
||||||
setSessionResetHandler(() => {
|
setSessionResetHandler(() => {
|
||||||
sessionRuntimeStarted = false;
|
sessionRuntimeStarted = false;
|
||||||
|
stopChannelsPrefetch();
|
||||||
startConnectionMonitor();
|
startConnectionMonitor();
|
||||||
clearKeepAliveEntries();
|
clearKeepAliveEntries();
|
||||||
if (reconnectIntervalId) {
|
if (reconnectIntervalId) {
|
||||||
@@ -1759,7 +1844,8 @@ async function init() {
|
|||||||
if (added && isIncomingForCurrent) {
|
if (added && isIncomingForCurrent) {
|
||||||
shouldRefreshToolbarUnread = true;
|
shouldRefreshToolbarUnread = true;
|
||||||
}
|
}
|
||||||
if (added && isIncomingForCurrent && !payload.backlog) {
|
// Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления.
|
||||||
|
if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) {
|
||||||
const parsedText = parseDmTechBlocks(text);
|
const parsedText = parseDmTechBlocks(text);
|
||||||
const displayText = String(parsedText.displayText || '');
|
const displayText = String(parsedText.displayText || '');
|
||||||
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
|
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
|
||||||
@@ -1941,6 +2027,19 @@ async function init() {
|
|||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
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();
|
await tryAutoLogin();
|
||||||
if (initialNotificationOpenPayload) {
|
if (initialNotificationOpenPayload) {
|
||||||
await handleNotificationClick(initialNotificationOpenPayload);
|
await handleNotificationClick(initialNotificationOpenPayload);
|
||||||
@@ -1956,7 +2055,10 @@ async function init() {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
window.addEventListener('popstate', renderApp);
|
window.addEventListener('popstate', (event) => {
|
||||||
|
if (event.isTrusted && consumeHistoryLayerPop()) return;
|
||||||
|
renderApp();
|
||||||
|
});
|
||||||
document.addEventListener('pointerdown', () => {
|
document.addEventListener('pointerdown', () => {
|
||||||
void unlockHiddenDmAudio();
|
void unlockHiddenDmAudio();
|
||||||
}, { passive: true });
|
}, { passive: true });
|
||||||
|
|||||||
@@ -591,7 +591,7 @@ export function openArweaveAttachmentManager({
|
|||||||
</div>
|
</div>
|
||||||
${turboMode
|
${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">
|
<div class="form-field">
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export function openChannelAttachmentManager({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="public-attachment-manager__arweave" data-panel="arweave" hidden>
|
<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 class="public-attachment-manager__arweave-loading meta-muted">Открываем настройки Arweave…</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { state } from '../state.js';
|
|||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import { renderUserAvatar } from './avatar-image.js';
|
import { renderUserAvatar } from './avatar-image.js';
|
||||||
import { openAuthRequiredModal } from '../services/auth-required-modal.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();
|
const drafts = new Map();
|
||||||
|
|
||||||
@@ -14,6 +16,24 @@ function draftKey(key) {
|
|||||||
return `${login}:${String(key || 'editor')}`;
|
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) {
|
function attachmentLabel(item) {
|
||||||
const name = String(item?.name || 'Файл');
|
const name = String(item?.name || 'Файл');
|
||||||
const size = Number(item?.size || 0);
|
const size = Number(item?.size || 0);
|
||||||
@@ -36,6 +56,7 @@ export function openChannelEditor({
|
|||||||
allowEmptyText = false,
|
allowEmptyText = false,
|
||||||
allowAttachments = true,
|
allowAttachments = true,
|
||||||
rawText = false,
|
rawText = false,
|
||||||
|
openAttachOnStart = false,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
isActive = () => true,
|
isActive = () => true,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
@@ -87,12 +108,45 @@ export function openChannelEditor({
|
|||||||
const draftMark = document.createElement('span');
|
const draftMark = document.createElement('span');
|
||||||
draftMark.className = 'channel-editor__draft';
|
draftMark.className = 'channel-editor__draft';
|
||||||
draftMark.textContent = 'Черновик';
|
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');
|
const body = document.createElement('div');
|
||||||
body.className = 'channel-editor__body';
|
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');
|
const contextBox = document.createElement('div');
|
||||||
contextBox.className = 'channel-editor__context';
|
contextBox.className = 'channel-editor__context';
|
||||||
const contextTitle = document.createElement('strong');
|
const contextTitle = document.createElement('strong');
|
||||||
@@ -115,6 +169,7 @@ export function openChannelEditor({
|
|||||||
|
|
||||||
const textarea = document.createElement('textarea');
|
const textarea = document.createElement('textarea');
|
||||||
textarea.className = 'channel-editor__input';
|
textarea.className = 'channel-editor__input';
|
||||||
|
textarea.rows = 1;
|
||||||
textarea.maxLength = 2000;
|
textarea.maxLength = 2000;
|
||||||
textarea.placeholder = placeholder;
|
textarea.placeholder = placeholder;
|
||||||
textarea.setAttribute('aria-label', placeholder);
|
textarea.setAttribute('aria-label', placeholder);
|
||||||
@@ -131,7 +186,7 @@ export function openChannelEditor({
|
|||||||
const clearButton = document.createElement('button');
|
const clearButton = document.createElement('button');
|
||||||
clearButton.type = 'button';
|
clearButton.type = 'button';
|
||||||
clearButton.className = 'text-btn channel-editor__clear';
|
clearButton.className = 'text-btn channel-editor__clear';
|
||||||
clearButton.textContent = 'Очистить черновик';
|
clearButton.textContent = 'Очистить';
|
||||||
|
|
||||||
const author = document.createElement('div');
|
const author = document.createElement('div');
|
||||||
author.className = 'channel-editor__author';
|
author.className = 'channel-editor__author';
|
||||||
@@ -147,17 +202,24 @@ export function openChannelEditor({
|
|||||||
authorText.append(where);
|
authorText.append(where);
|
||||||
}
|
}
|
||||||
author.append(authorText);
|
author.append(authorText);
|
||||||
|
if (chain.length) author.classList.add('is-chained');
|
||||||
body.append(author);
|
body.append(author);
|
||||||
body.append(textarea, attachmentsBox, error, clearButton);
|
|
||||||
|
|
||||||
const footer = document.createElement('footer');
|
const footer = document.createElement('footer');
|
||||||
footer.className = 'channel-editor__footer';
|
footer.className = 'channel-editor__footer';
|
||||||
const attachButton = document.createElement('button');
|
const attachButton = document.createElement('button');
|
||||||
attachButton.type = 'button';
|
attachButton.type = 'button';
|
||||||
attachButton.className = 'secondary-btn channel-editor__attach';
|
attachButton.className = 'icon-btn channel-editor__attach';
|
||||||
attachButton.innerHTML = `${iconHtml('clip')}<span class="sr-only">Прикрепить</span>`;
|
attachButton.innerHTML = `${iconHtml('image')}<span class="sr-only">Прикрепить фото, видео или файл</span>`;
|
||||||
attachButton.title = 'Прикрепить файл';
|
attachButton.title = 'Фото, видео или файл';
|
||||||
attachButton.hidden = !allowAttachments;
|
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');
|
const counter = document.createElement('span');
|
||||||
counter.className = 'channel-editor__counter';
|
counter.className = 'channel-editor__counter';
|
||||||
const submitButton = document.createElement('button');
|
const submitButton = document.createElement('button');
|
||||||
@@ -184,15 +246,42 @@ export function openChannelEditor({
|
|||||||
|
|
||||||
const sync = () => {
|
const sync = () => {
|
||||||
textarea.style.height = 'auto';
|
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;
|
const length = textarea.value.length;
|
||||||
counter.textContent = `${length} / 2000`;
|
counter.textContent = `${length} / 2000`;
|
||||||
counter.classList.toggle('is-near-limit', length >= 1800);
|
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);
|
submitButton.disabled = inFlight || picking || length > textarea.maxLength || (!allowEmptyText && !textarea.value.trim() && attachments.length === 0);
|
||||||
dialog.setAttribute('aria-busy', String(inFlight || picking));
|
dialog.setAttribute('aria-busy', String(inFlight || picking));
|
||||||
clearButton.hidden = !textarea.value && attachments.length === 0;
|
clearButton.hidden = !textarea.value && attachments.length === 0;
|
||||||
|
draftMark.hidden = !clearButton.hidden;
|
||||||
attachmentsBox.replaceChildren();
|
attachmentsBox.replaceChildren();
|
||||||
attachments.forEach((item, index) => {
|
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');
|
const card = document.createElement('div');
|
||||||
card.className = 'channel-editor__attachment';
|
card.className = 'channel-editor__attachment';
|
||||||
const label = document.createElement('span');
|
const label = document.createElement('span');
|
||||||
@@ -213,19 +302,13 @@ export function openChannelEditor({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const openedUrl = location.href;
|
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
|
||||||
const historyId = `${Date.now()}:${Math.random()}`;
|
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
|
||||||
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
|
|
||||||
const viewport = window.visualViewport;
|
const viewport = window.visualViewport;
|
||||||
const updateViewport = () => {
|
const updateViewport = () => {
|
||||||
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
|
||||||
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}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(() => {
|
const observer = new MutationObserver(() => {
|
||||||
if (!overlay.isConnected) close({ restoreFocus: false });
|
if (!overlay.isConnected) close({ restoreFocus: false });
|
||||||
});
|
});
|
||||||
@@ -239,14 +322,8 @@ export function openChannelEditor({
|
|||||||
viewport?.removeEventListener('resize', updateViewport);
|
viewport?.removeEventListener('resize', updateViewport);
|
||||||
viewport?.removeEventListener('scroll', updateViewport);
|
viewport?.removeEventListener('scroll', updateViewport);
|
||||||
window.removeEventListener('resize', updateViewport);
|
window.removeEventListener('resize', updateViewport);
|
||||||
window.removeEventListener('popstate', onBack, true);
|
|
||||||
overlay.remove();
|
overlay.remove();
|
||||||
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
|
if (!fromHistory) historyLayer.close();
|
||||||
window.addEventListener('popstate', (event) => {
|
|
||||||
if (location.href === openedUrl) event.stopImmediatePropagation();
|
|
||||||
}, { capture: true, once: true });
|
|
||||||
history.back();
|
|
||||||
}
|
|
||||||
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
|
||||||
};
|
};
|
||||||
overlay.cleanup = () => close({ restoreFocus: false });
|
overlay.cleanup = () => close({ restoreFocus: false });
|
||||||
@@ -362,7 +439,6 @@ export function openChannelEditor({
|
|||||||
});
|
});
|
||||||
submitButton.addEventListener('click', () => void submit());
|
submitButton.addEventListener('click', () => void submit());
|
||||||
document.addEventListener('keydown', onDocumentKeydown);
|
document.addEventListener('keydown', onDocumentKeydown);
|
||||||
window.addEventListener('popstate', onBack, true);
|
|
||||||
viewport?.addEventListener('resize', updateViewport);
|
viewport?.addEventListener('resize', updateViewport);
|
||||||
viewport?.addEventListener('scroll', updateViewport);
|
viewport?.addEventListener('scroll', updateViewport);
|
||||||
window.addEventListener('resize', updateViewport);
|
window.addEventListener('resize', updateViewport);
|
||||||
@@ -375,7 +451,9 @@ export function openChannelEditor({
|
|||||||
const expand = overlay.querySelector('.channel-editor__context-toggle');
|
const expand = overlay.querySelector('.channel-editor__context-toggle');
|
||||||
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
|
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
|
||||||
sync();
|
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);
|
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
|
||||||
});
|
});
|
||||||
return { close };
|
return { close };
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Вложения личных сообщений: превью картинок и видео после расшифровки и карточка файла со «Скачать».
|
||||||
|
// Общие для ленты чата и экрана «Медиа и файлы».
|
||||||
|
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';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.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(actionErrorText('Не удалось скачать файл', error), { kind: 'error' });
|
||||||
|
} 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;
|
let activeDropdown = null;
|
||||||
|
|
||||||
function normalizeItems(items) {
|
function normalizeItems(items) {
|
||||||
@@ -73,8 +75,29 @@ export function createDropdownMenu({
|
|||||||
menuEl.style.top = `${Math.round(top)}px`;
|
menuEl.style.top = `${Math.round(top)}px`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const appendItems = () => {
|
// Пункт с submenu не закрывает меню, а показывает вложенный список на том же месте
|
||||||
normalizeItems(items).forEach((item) => {
|
// (сверху – «назад»): так выбирают, например, срок «без звука».
|
||||||
|
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) {
|
if (item.divider) {
|
||||||
const divider = document.createElement('div');
|
const divider = document.createElement('div');
|
||||||
divider.className = 'dropdown-menu__divider';
|
divider.className = 'dropdown-menu__divider';
|
||||||
@@ -105,11 +128,33 @@ export function createDropdownMenu({
|
|||||||
|
|
||||||
const label = document.createElement('span');
|
const label = document.createElement('span');
|
||||||
label.textContent = String(item.label || '');
|
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) => {
|
button.addEventListener('click', async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (button.disabled) return;
|
if (button.disabled) return;
|
||||||
|
if (item.submenu) {
|
||||||
|
showLevel(item.submenu, String(item.submenuTitle || item.label || ''));
|
||||||
|
return;
|
||||||
|
}
|
||||||
close({ focusAnchor: true });
|
close({ focusAnchor: true });
|
||||||
await item.action?.();
|
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 = () => {
|
const open = () => {
|
||||||
if (destroyed || !anchorEl || portal) return;
|
if (destroyed || !anchorEl || portal) return;
|
||||||
if (activeDropdown && activeDropdown !== api) activeDropdown.close();
|
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,108 @@
|
|||||||
|
// Строка человека в списках (связи, поиск людей, списки профиля): аватар, имя, строка под
|
||||||
|
// ним и действия справа. Вид совпадает со строками списка чатов.
|
||||||
|
import { renderUserAvatar } from './avatar-image.js';
|
||||||
|
import { iconHtml } from './ui-icon.js';
|
||||||
|
import { createSpinner } from './feedback.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,primary?:boolean,busy?:boolean}>} [opts.actions]
|
||||||
|
* primary – главное действие строки (цветом), busy – идёт сохранение (спиннер, кнопка неактивна)
|
||||||
|
*/
|
||||||
|
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${action.primary ? ' person-row__action--primary' : ''}`;
|
||||||
|
if (action.busy) {
|
||||||
|
button.disabled = true;
|
||||||
|
button.append(createSpinner({ size: 'sm', label: action.label }));
|
||||||
|
} else {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
// data-profile-list / data-self-profile-action / data-profile-action обрабатывают profile-view.js и user-profile-view.js.
|
// data-profile-list / data-self-profile-action / data-profile-action обрабатывают profile-view.js и user-profile-view.js.
|
||||||
import { iconHtml } from './ui-icon.js';
|
import { iconHtml } from './ui-icon.js';
|
||||||
|
import { displayCity } from '../services/cities.js';
|
||||||
|
|
||||||
export function escapeProfileHtml(text) {
|
export function escapeProfileHtml(text) {
|
||||||
return String(text || '')
|
return String(text || '')
|
||||||
@@ -12,25 +13,19 @@ export function escapeProfileHtml(text) {
|
|||||||
|
|
||||||
const esc = escapeProfileHtml;
|
const esc = escapeProfileHtml;
|
||||||
|
|
||||||
function statusCardHtml({ kind, title, received, given }) {
|
// Карточка статуса у аватара: кто подтвердил этот аккаунт и кого подтвердил он сам.
|
||||||
const receivedCount = Number(received || 0);
|
function statusSideHtml({ kind, title, active, received, given, verb }) {
|
||||||
const givenCount = Number(given || 0);
|
|
||||||
const isOfficial = kind === 'primary';
|
const isOfficial = kind === 'primary';
|
||||||
const receivedKind = isOfficial ? 'primary_received' : 'shine_received';
|
const receivedKind = isOfficial ? 'primary_received' : 'shine_received';
|
||||||
const givenKind = isOfficial ? 'primary_given' : 'shine_given';
|
const givenKind = isOfficial ? 'primary_given' : 'shine_given';
|
||||||
const receivedTitle = isOfficial ? 'Кто подтвердил этот официальный аккаунт' : 'Кто подтвердил, что этот аккаунт сияющий';
|
|
||||||
const givenTitle = isOfficial ? 'Какие официальные аккаунты подтвердил этот пользователь' : 'Кого этот пользователь подтвердил как сияющего';
|
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<section class="pf-status-card pf-status-card--${esc(kind)}" aria-label="${esc(title)}">
|
<section class="pf-sc pf-sc--${esc(kind)}${active ? ' is-active' : ' is-empty'}" aria-label="${esc(title)}">
|
||||||
<div class="pf-status-card-title">${esc(title)}</div>
|
<div class="pf-sc__title">${esc(title)}</div>
|
||||||
<button type="button" class="pf-status-card-count" data-profile-list="${receivedKind}"
|
<button type="button" class="pf-sc__row" data-profile-list="${receivedKind}" aria-label="${esc(title)}: подтвердили ${Number(received || 0)}">
|
||||||
aria-label="${esc(receivedTitle)}: ${receivedCount}" title="${esc(receivedTitle)}">
|
<strong>${Number(received || 0)}</strong><span>подтвердили</span>
|
||||||
<strong>${receivedCount}</strong><span>подтвердили</span>
|
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="pf-status-card-count" data-profile-list="${givenKind}"
|
<button type="button" class="pf-sc__row" data-profile-list="${givenKind}" aria-label="${esc(title)}: ${esc(verb)} ${Number(given || 0)}">
|
||||||
aria-label="${esc(givenTitle)}: ${givenCount}" title="${esc(givenTitle)}">
|
<strong>${Number(given || 0)}</strong><span>${esc(verb)}</span>
|
||||||
<strong>${givenCount}</strong><span>подтвердил</span>
|
|
||||||
</button>
|
</button>
|
||||||
</section>`;
|
</section>`;
|
||||||
}
|
}
|
||||||
@@ -71,6 +66,7 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
|||||||
const official = card?.accountRole === 'primary';
|
const official = card?.accountRole === 'primary';
|
||||||
const shining = card?.shineStatus === 'shining';
|
const shining = card?.shineStatus === 'shining';
|
||||||
const cardLogin = card?.login || login;
|
const cardLogin = card?.login || login;
|
||||||
|
const city = displayCity(card?.city);
|
||||||
const fullName = [card?.firstName, card?.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ');
|
const fullName = [card?.firstName, card?.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ');
|
||||||
const displayName = fullName || cardLogin || 'Профиль';
|
const displayName = fullName || cardLogin || 'Профиль';
|
||||||
const about = String(card?.about || '').trim();
|
const about = String(card?.about || '').trim();
|
||||||
@@ -91,32 +87,30 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
|||||||
const friends = Number(stats.friendsCount || 0);
|
const friends = Number(stats.friendsCount || 0);
|
||||||
const closeFriends = Number(stats.closeFriendsCount || 0);
|
const closeFriends = Number(stats.closeFriendsCount || 0);
|
||||||
|
|
||||||
const officialCard = official
|
const shineReceived = Number(stats.shineReceivedCount || 0);
|
||||||
? statusCardHtml({
|
const shineGiven = Number(stats.shineGivenCount || 0);
|
||||||
kind: 'primary',
|
const primaryReceived = Number(stats.primaryReceivedCount || 0);
|
||||||
title: 'Официальный',
|
const primaryGiven = Number(stats.primaryGivenCount || 0);
|
||||||
received: stats.primaryReceivedCount,
|
// Статусы по бокам аватара: слева «Официальный», справа «Сияние». На своём профиле – всегда
|
||||||
given: stats.primaryGivenCount,
|
// (пустая сторона бледнее), на чужом – если статус есть или уже есть подтверждения.
|
||||||
})
|
const verb = card?.gender === 'female' ? 'подтвердила' : card?.gender === 'male' ? 'подтвердил' : 'подтвердил(а)';
|
||||||
|
const officialSide = (isSelf || official || primaryReceived || primaryGiven)
|
||||||
|
? statusSideHtml({ kind: 'primary', title: 'Официальный', active: official, received: primaryReceived, given: primaryGiven, verb })
|
||||||
: '';
|
: '';
|
||||||
const shiningCard = shining
|
const shineSide = (isSelf || shining || shineReceived || shineGiven)
|
||||||
? statusCardHtml({
|
? statusSideHtml({ kind: 'shine', title: 'Сияющий', active: shining, received: shineReceived, given: shineGiven, verb })
|
||||||
kind: 'shine',
|
|
||||||
title: 'Сияющий',
|
|
||||||
received: stats.shineReceivedCount,
|
|
||||||
given: stats.shineGivenCount,
|
|
||||||
})
|
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<div class="pf-hero" aria-label="Профиль ${esc(cardLogin)}">
|
<div class="pf-hero" aria-label="Профиль ${esc(cardLogin)}">
|
||||||
<div class="pf-identity">
|
<div class="pf-identity">
|
||||||
<div class="pf-status-card-slot pf-status-card-slot--left">${officialCard}</div>
|
<div class="pf-side pf-side--left">${officialSide}</div>
|
||||||
<div class="pf-avatar user-profile-avatar-slot"></div>
|
<div class="pf-avatar user-profile-avatar-slot${shining ? ' is-shining' : ''}"></div>
|
||||||
<div class="pf-status-card-slot pf-status-card-slot--right">${shiningCard}</div>
|
<div class="pf-side pf-side--right">${shineSide}</div>
|
||||||
</div>
|
</div>
|
||||||
<h2 class="pf-name">${esc(displayName)}</h2>
|
<h2 class="pf-name">${esc(displayName)}</h2>
|
||||||
<div class="pf-login">@${esc(cardLogin)}</div>
|
<div class="pf-login">@${esc(cardLogin)}</div>
|
||||||
|
${city ? `<div class="pf-city">${iconHtml('place')}<span>${esc(city)}</span></div>` : ''}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pf-stats">
|
<div class="pf-stats">
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ export function openShareSheet({ title = 'Поделиться', kicker = '', te
|
|||||||
} catch {
|
} catch {
|
||||||
field.focus();
|
field.focus();
|
||||||
field.select();
|
field.select();
|
||||||
showToast('Выделил ссылку – скопируйте её вручную', { kind: 'error' });
|
showToast('Ссылка выделена – скопируйте её вручную', { kind: 'info' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
wrap.append(preview, label, copy);
|
wrap.append(preview, label, copy);
|
||||||
|
|||||||
@@ -116,3 +116,67 @@ export function createTopBar({
|
|||||||
|
|
||||||
return topbar;
|
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"/>',
|
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"/>',
|
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"/>',
|
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"/>',
|
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"/>',
|
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"/>',
|
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"/>',
|
check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
|
||||||
open: '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
open: '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
||||||
chevron: '<path d="m9 6 6 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"/>',
|
back: '<path d="M19 12H5M11 5l-7 7 7 7"/>',
|
||||||
down: '<path d="M12 5v14M5 12l7 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"/>',
|
edit: '<path d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16v4Z"/><path d="m13.5 6.5 4 4"/>',
|
||||||
@@ -42,9 +47,18 @@ const paths = {
|
|||||||
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>',
|
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>',
|
||||||
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
|
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
|
||||||
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
||||||
|
sparkle: '<path d="M11 4c.6 4.4 2.6 6.4 7 7-4.4.6-6.4 2.6-7 7-.6-4.4-2.6-6.4-7-7 4.4-.6 6.4-2.6 7-7Z"/><path d="M19 2.5v3M17.5 4h3"/>',
|
||||||
|
rings: '<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',
|
||||||
|
place: '<path d="M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11Z"/><circle cx="12" cy="10" r="2.4"/>',
|
||||||
|
groups: '<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><circle cx="17" cy="9.5" r="2.5"/><path d="M15.6 14.1A4.6 4.6 0 0 1 21 18.5"/>',
|
||||||
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"/>',
|
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"/>',
|
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"/>',
|
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 = '') {
|
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;
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { loadEncryptedUserSecrets } from '../services/key-vault.js';
|
|||||||
import { resolveShineServerByServerLogin } from '../services/shine-server-resolver.js';
|
import { resolveShineServerByServerLogin } from '../services/shine-server-resolver.js';
|
||||||
import { readShineUserPda, updateShineUserPdaOnSolana } from '../services/shine-user-pda-service.js';
|
import { readShineUserPda, updateShineUserPdaOnSolana } from '../services/shine-user-pda-service.js';
|
||||||
import { getTopupSiteUrl } from '../services/solana-wallet-service.js';
|
import { getTopupSiteUrl } from '../services/solana-wallet-service.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'access-servers-view', title: 'Сервер доступа' };
|
export const pageMeta = { id: 'access-servers-view', title: 'Сервер доступа' };
|
||||||
const MAX_ACCESS_SERVERS = 1;
|
const MAX_ACCESS_SERVERS = 1;
|
||||||
@@ -97,7 +98,7 @@ function createConfirmModal() {
|
|||||||
}) {
|
}) {
|
||||||
root.innerHTML = `
|
root.innerHTML = `
|
||||||
<div class="modal" id="access-servers-confirm-modal">
|
<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>
|
<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-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>
|
<p class="meta-muted" id="access-servers-dialog-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||||
@@ -166,7 +167,7 @@ function createPasswordModal() {
|
|||||||
open({ title, text, note = '' }) {
|
open({ title, text, note = '' }) {
|
||||||
root.innerHTML = `
|
root.innerHTML = `
|
||||||
<div class="modal" id="access-servers-password-modal">
|
<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>
|
<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-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>
|
<p class="meta-muted" id="access-servers-password-note"${note ? '' : ' hidden'} style="white-space:pre-wrap; line-height:1.45;"></p>
|
||||||
@@ -265,7 +266,9 @@ export function render({navigate, chrome}) {
|
|||||||
const introCard = document.createElement('div');
|
const introCard = document.createElement('div');
|
||||||
introCard.className = 'settings-intro';
|
introCard.className = 'settings-intro';
|
||||||
introCard.innerHTML = `
|
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');
|
const listCard = document.createElement('div');
|
||||||
@@ -292,7 +295,7 @@ export function render({navigate, chrome}) {
|
|||||||
addTitle.textContent = 'Сменить сервер доступа';
|
addTitle.textContent = 'Сменить сервер доступа';
|
||||||
const addHint = document.createElement('p');
|
const addHint = document.createElement('p');
|
||||||
addHint.className = 'meta-muted';
|
addHint.className = 'meta-muted';
|
||||||
addHint.textContent = 'Введите логин нового сервера или несколько первых букв, затем выберите сервер из подсказок. Новый сервер заменит текущий.';
|
addHint.textContent = 'Тестовая функция веб-версии. Для обычной смены сервера доступа необходимо открыть новый сервер и выполнить смену оттуда. Здесь можно указать новый сервер напрямую; переписка автоматически не переносится.';
|
||||||
const addInput = document.createElement('input');
|
const addInput = document.createElement('input');
|
||||||
addInput.className = 'input';
|
addInput.className = 'input';
|
||||||
addInput.type = 'text';
|
addInput.type = 'text';
|
||||||
@@ -310,6 +313,16 @@ export function render({navigate, chrome}) {
|
|||||||
addButton.textContent = 'Сменить сервер';
|
addButton.textContent = 'Сменить сервер';
|
||||||
addButton.disabled = true;
|
addButton.disabled = true;
|
||||||
addCard.append(addTitle, addHint, addInput, suggestEl, addStatus, addButton);
|
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 = () => {
|
const refreshAddButton = () => {
|
||||||
addButton.disabled = operationBusy
|
addButton.disabled = operationBusy
|
||||||
@@ -395,7 +408,7 @@ export function render({navigate, chrome}) {
|
|||||||
currentAccessServers = [];
|
currentAccessServers = [];
|
||||||
renderServerList();
|
renderServerList();
|
||||||
refreshAddButton();
|
refreshAddButton();
|
||||||
listStatus.textContent = error?.message || 'Не удалось прочитать сервер доступа.';
|
listStatus.textContent = actionErrorText('Не удалось прочитать сервер доступа', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -450,7 +463,7 @@ export function render({navigate, chrome}) {
|
|||||||
if (!disposed) {
|
if (!disposed) {
|
||||||
suggestEl.hidden = true;
|
suggestEl.hidden = true;
|
||||||
suggestEl.innerHTML = '';
|
suggestEl.innerHTML = '';
|
||||||
addStatus.textContent = error?.message || 'Не удалось получить список серверов.';
|
addStatus.textContent = actionErrorText('Не удалось получить список серверов', error);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
suggestionsLoading = false;
|
suggestionsLoading = false;
|
||||||
@@ -546,7 +559,7 @@ export function render({navigate, chrome}) {
|
|||||||
if (isInsufficientFundsForRentError(error)) {
|
if (isInsufficientFundsForRentError(error)) {
|
||||||
showTopupRequiredStatus(target, signingMaterial?.payerAddress);
|
showTopupRequiredStatus(target, signingMaterial?.payerAddress);
|
||||||
} else {
|
} else {
|
||||||
target.textContent = error?.message || 'Не удалось обновить сервер доступа.';
|
target.textContent = actionErrorText('Не удалось обновить сервер доступа', error);
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -608,17 +621,18 @@ export function render({navigate, chrome}) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
addStatus.textContent = error?.message || 'Не удалось проверить выбранный сервер.';
|
addStatus.textContent = actionErrorText('Не удалось проверить выбранный сервер', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
chrome?.setTopbar(createTopBar({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: 'Сервер доступа',
|
title: 'Мой сервер доступа',
|
||||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||||
}));
|
}));
|
||||||
screen.append(
|
screen.append(
|
||||||
introCard,
|
introCard,
|
||||||
listCard,
|
listCard,
|
||||||
|
changeServerToggle,
|
||||||
addCard,
|
addCard,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
import { authService, state } from '../state.js';
|
import { authService, state } from '../state.js';
|
||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import {
|
import {
|
||||||
@@ -46,7 +47,7 @@ function renderAvatarPreview(slot, avatar, title) {
|
|||||||
avatar,
|
avatar,
|
||||||
authorLogin: state.session.login,
|
authorLogin: state.session.login,
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'channel-profile-avatar',
|
className: 'channel-profile-avatar avatar-plain',
|
||||||
title: label,
|
title: label,
|
||||||
alt: 'Аватар канала',
|
alt: 'Аватар канала',
|
||||||
});
|
});
|
||||||
@@ -292,9 +293,9 @@ export function render({navigate, chrome}) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
avatarRemoveBtn.addEventListener('click', () => {
|
avatarRemoveBtn.addEventListener('click', async () => {
|
||||||
if (!selectedAvatar?.sha256) return;
|
if (!selectedAvatar?.sha256) return;
|
||||||
const confirmed = window.confirm('Убрать аватар и сделать канал без аватара?');
|
const confirmed = await confirmDialog({ title: 'Убрать аватар канала?', text: 'Канал будет без картинки – её можно добавить позже.', confirmLabel: 'Убрать' });
|
||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
selectedAvatar = null;
|
selectedAvatar = null;
|
||||||
avatarAvailabilityLabel = '';
|
avatarAvailabilityLabel = '';
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
import { formatBytes } from '../services/attachment-format.js';
|
import { formatBytes } from '../services/attachment-format.js';
|
||||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import { state } from '../state.js';
|
import { state } from '../state.js';
|
||||||
|
|
||||||
@@ -110,7 +111,7 @@ export function render({navigate, chrome}) {
|
|||||||
|
|
||||||
const topbar = createTopBar({
|
const topbar = createTopBar({
|
||||||
title: 'Файлы в блокчейне',
|
title: 'Файлы в блокчейне',
|
||||||
back: { onClick: () => navigate('settings-view') },
|
back: { onClick: () => navigate('my-blockchain-view') },
|
||||||
actions: [
|
actions: [
|
||||||
{
|
{
|
||||||
icon: 'plus',
|
icon: 'plus',
|
||||||
@@ -130,8 +131,8 @@ export function render({navigate, chrome}) {
|
|||||||
{ label: 'Добавить файл', action: () => uploadFile() },
|
{ label: 'Добавить файл', action: () => uploadFile() },
|
||||||
{
|
{
|
||||||
label: 'Очистить историю',
|
label: 'Очистить историю',
|
||||||
action: () => {
|
action: async () => {
|
||||||
const confirmed = window.confirm('Очистить журнал загруженных файлов этой сессии?');
|
const confirmed = await confirmDialog({ title: 'Очистить журнал?', text: 'Список загруженных в этой сессии файлов будет очищен. Сами файлы останутся в Arweave.', confirmLabel: 'Очистить', danger: true });
|
||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
clearArweaveAttachmentHistory(state.session.login);
|
clearArweaveAttachmentHistory(state.session.login);
|
||||||
renderHistory();
|
renderHistory();
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
|||||||
avatar: selectedAvatar?.sha256 ? { ar: String(selectedAvatar.ar || ''), sha256Hex: selectedAvatar.sha256 } : null,
|
avatar: selectedAvatar?.sha256 ? { ar: String(selectedAvatar.ar || ''), sha256Hex: selectedAvatar.sha256 } : null,
|
||||||
authorLogin: String(channel?.ownerLogin || state.session.login || '').trim(),
|
authorLogin: String(channel?.ownerLogin || state.session.login || '').trim(),
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'channel-about-avatar channel-profile-avatar',
|
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||||
title: title || 'Канал',
|
title: title || 'Канал',
|
||||||
alt: 'Аватар канала',
|
alt: 'Аватар канала',
|
||||||
}));
|
}));
|
||||||
@@ -157,7 +157,7 @@ function openChannelProfileEditor({ channel, selector, onSaved }) {
|
|||||||
const title = String(root.querySelector('#channel-profile-edit-title')?.value || '').trim();
|
const title = String(root.querySelector('#channel-profile-edit-title')?.value || '').trim();
|
||||||
const description = String(root.querySelector('#channel-profile-edit-description')?.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 (Array.from(title).length > 50 || Array.from(description).length > 250) {
|
||||||
if (errorEl) errorEl.textContent = 'Название — до 50 символов, описание — до 250.';
|
if (errorEl) errorEl.textContent = 'Название – до 50 символов, описание – до 250.';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
save.disabled = true;
|
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,
|
avatar: String(channel?.avaAr || channel?.avaSha256 || '').trim() ? { ar: String(channel.avaAr || '').trim(), sha256Hex: String(channel?.avaSha256 || '').trim() } : null,
|
||||||
authorLogin: ownerLogin,
|
authorLogin: ownerLogin,
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'channel-about-avatar channel-profile-avatar',
|
className: 'channel-about-avatar channel-profile-avatar avatar-plain',
|
||||||
title: cleanName,
|
title: cleanName,
|
||||||
alt: 'Аватар канала',
|
alt: 'Аватар канала',
|
||||||
});
|
});
|
||||||
@@ -648,7 +648,7 @@ export function render({ navigate, route, chrome }) {
|
|||||||
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
content.querySelector('#channel-about-owner-avatar')?.append(renderAvatar({
|
||||||
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
initials: ownerName.slice(0, 1).toUpperCase() || '?',
|
||||||
size: 'md',
|
size: 'md',
|
||||||
className: 'channel-about-owner-avatar-img',
|
className: 'channel-about-owner-avatar-img avatar-plain',
|
||||||
alt: '',
|
alt: '',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+383
-227
@@ -1,7 +1,10 @@
|
|||||||
|
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||||
import { getPreviousTrackedPath } from '../router.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 { attachMessageMenu } from '../components/message-menu.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import {
|
import {
|
||||||
@@ -14,12 +17,17 @@ import {
|
|||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
import {
|
import {
|
||||||
animatePress,
|
animatePress,
|
||||||
createSkeletonCard,
|
createLoadErrorCard,
|
||||||
|
createSkeletonRows,
|
||||||
|
SKELETON_DELAY_MS,
|
||||||
dayKey,
|
dayKey,
|
||||||
formatDayLabel,
|
formatDayLabel,
|
||||||
formatPostStamp,
|
formatPostStamp,
|
||||||
formatRelativeTime,
|
formatRelativeTime,
|
||||||
|
formatShortAge,
|
||||||
longPressFeel,
|
longPressFeel,
|
||||||
|
notifyRepostSoon,
|
||||||
|
REPOSTS_ENABLED,
|
||||||
shareOrCopyLink,
|
shareOrCopyLink,
|
||||||
showToast,
|
showToast,
|
||||||
softHaptic,
|
softHaptic,
|
||||||
@@ -41,12 +49,16 @@ import {
|
|||||||
extractLoginFromBlockchainName,
|
extractLoginFromBlockchainName,
|
||||||
makeProfileRoute,
|
makeProfileRoute,
|
||||||
makeShineMessageRoute,
|
makeShineMessageRoute,
|
||||||
|
makeShineChannelStreamRoute,
|
||||||
makeShineChannelAboutRoute,
|
makeShineChannelAboutRoute,
|
||||||
makeShineChannelDonateRoute,
|
makeShineChannelDonateRoute,
|
||||||
} from '../services/shine-routes.js';
|
} from '../services/shine-routes.js';
|
||||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.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';
|
||||||
|
import { scrollNodeIntoContainer } from '../services/scroll-utils.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_STORIES = 0;
|
||||||
const CHANNEL_TYPE_PERSONAL = 100;
|
const CHANNEL_TYPE_PERSONAL = 100;
|
||||||
const MSG_SUBTYPE_TEXT_RATING = 30;
|
const MSG_SUBTYPE_TEXT_RATING = 30;
|
||||||
@@ -236,13 +248,17 @@ function buildSelectorFromRoute(route, channelId) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildThreadRoute(messageRef, selector) {
|
function buildThreadRoute(post, selector) {
|
||||||
|
const messageRef = post?.messageRef;
|
||||||
if (!messageRef || !selector) return '';
|
if (!messageRef || !selector) return '';
|
||||||
const ownerLogin = extractLoginFromBlockchainName(selector.ownerBlockchainName);
|
const ownerLogin = extractLoginFromBlockchainName(selector.ownerBlockchainName);
|
||||||
return makeShineMessageRoute({
|
return makeShineMessageRoute({
|
||||||
ownerLogin,
|
ownerLogin,
|
||||||
messageBlockchainName: messageRef.blockchainName,
|
messageBlockchainName: messageRef.blockchainName,
|
||||||
messageBlockNumber: messageRef.blockNumber,
|
messageBlockNumber: messageRef.blockNumber,
|
||||||
|
messageOrdinal: selector.publicOrdinalUrlsAllowed ? post.localNumber : '',
|
||||||
|
channelName: selector.publicOrdinalUrlsAllowed ? selector.channelName : '',
|
||||||
|
channelOwnerBlockchainName: selector.ownerBlockchainName,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -628,7 +644,7 @@ function createChannelAvatarElement(channel, size = 96) {
|
|||||||
avatar: (txId || sha256) ? { ar: txId, sha256Hex: sha256 } : null,
|
avatar: (txId || sha256) ? { ar: txId, sha256Hex: sha256 } : null,
|
||||||
authorLogin: String(channel?.ownerLogin || '').trim(),
|
authorLogin: String(channel?.ownerLogin || '').trim(),
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'channel-profile-avatar',
|
className: 'channel-profile-avatar avatar-plain',
|
||||||
title,
|
title,
|
||||||
alt: 'Аватар канала',
|
alt: 'Аватар канала',
|
||||||
});
|
});
|
||||||
@@ -1019,7 +1035,7 @@ function flashAndScrollToMessage(messageRef) {
|
|||||||
const target = cards.find((card) => card.dataset.messageKey === key);
|
const target = cards.find((card) => card.dataset.messageKey === key);
|
||||||
if (!target) return false;
|
if (!target) return false;
|
||||||
target.classList.remove('is-focus-flash');
|
target.classList.remove('is-focus-flash');
|
||||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
scrollNodeIntoContainer(target, { behavior: 'smooth' });
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
if (target.isConnected) target.classList.add('is-focus-flash');
|
if (target.isConnected) target.classList.add('is-focus-flash');
|
||||||
}, 60);
|
}, 60);
|
||||||
@@ -1483,6 +1499,9 @@ async function loadFromApi(route, channelId) {
|
|||||||
const ownerLogin = String(payload.channel?.ownerLogin || '').trim();
|
const ownerLogin = String(payload.channel?.ownerLogin || '').trim();
|
||||||
const channelName = String(payload.channel?.channelName || '').trim();
|
const channelName = String(payload.channel?.channelName || '').trim();
|
||||||
const channelTypeCode = Number(payload.channel?.channelTypeCode ?? 1);
|
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) {
|
if (channelTypeCode === CHANNEL_TYPE_STORIES) {
|
||||||
throw new Error('Канал stories скрыт из пользовательского интерфейса.');
|
throw new Error('Канал stories скрыт из пользовательского интерфейса.');
|
||||||
}
|
}
|
||||||
@@ -1516,16 +1535,9 @@ async function loadFromApi(route, channelId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const posts = mergedMessages
|
const posts = sortedChannelPublications(
|
||||||
.map((message, index) => mapApiMessageToPost(message, selector, index + 1))
|
mergedMessages.map((message, index) => mapApiMessageToPost(message, selector, index + 1)),
|
||||||
.sort((a, b) => {
|
).map((post, index) => ({ ...post, localNumber: index + 1 }));
|
||||||
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 isOwnChannel = ownerLogin.toLowerCase() === currentSessionLogin.toLowerCase();
|
const isOwnChannel = ownerLogin.toLowerCase() === currentSessionLogin.toLowerCase();
|
||||||
const followedRows = Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : [];
|
const followedRows = Array.isArray(state.channelsFeed?.followedChannels) ? state.channelsFeed.followedChannels : [];
|
||||||
const isSubscribed = isAuthorized && followedRows.some((row) => (
|
const isSubscribed = isAuthorized && followedRows.some((row) => (
|
||||||
@@ -1564,27 +1576,12 @@ async function loadFromApi(route, channelId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderLoadError(screen, navigate, message, onRetry) {
|
function renderLoadError(screen, navigate, message, onRetry) {
|
||||||
const card = document.createElement('div');
|
screen.append(createLoadErrorCard({
|
||||||
card.className = 'card stack channels-status';
|
title: 'Не удалось загрузить канал',
|
||||||
card.innerHTML = `
|
message: message || 'Проверьте подключение и повторите попытку.',
|
||||||
<strong>Не удалось загрузить канал</strong>
|
onRetry,
|
||||||
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
|
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
|
||||||
`;
|
}));
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDemoFallback(screen, navigate, error) {
|
function renderDemoFallback(screen, navigate, error) {
|
||||||
@@ -1606,9 +1603,7 @@ function renderDemoFallback(screen, navigate, error) {
|
|||||||
|
|
||||||
function scrollChannelToBottom(screen, smooth = true) {
|
function scrollChannelToBottom(screen, smooth = true) {
|
||||||
const feed = screen.querySelector('.channel-feed');
|
const feed = screen.querySelector('.channel-feed');
|
||||||
if (feed) {
|
if (feed) scrollNodeIntoContainer(feed, { block: 'end', behavior: smooth ? 'smooth' : 'auto' });
|
||||||
feed.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto', block: 'end' });
|
|
||||||
}
|
|
||||||
const appScreen = document.getElementById('app-screen');
|
const appScreen = document.getElementById('app-screen');
|
||||||
if (appScreen) {
|
if (appScreen) {
|
||||||
appScreen.scrollTo({ top: appScreen.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
|
appScreen.scrollTo({ top: appScreen.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
|
||||||
@@ -1635,7 +1630,7 @@ function applyPendingScroll(screen, routeKey, forceBottom = false) {
|
|||||||
|
|
||||||
const element = screen.querySelector(`[data-message-key="${target}"]`);
|
const element = screen.querySelector(`[data-message-key="${target}"]`);
|
||||||
if (element) {
|
if (element) {
|
||||||
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
scrollNodeIntoContainer(element, { behavior: 'smooth' });
|
||||||
pendingScrollByRoute.delete(routeKey);
|
pendingScrollByRoute.delete(routeKey);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1715,7 +1710,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="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>
|
<button type="button" class="ui-button" data-like-tab="all">Все <span data-like-tab-count="all"></span></button>
|
||||||
</div>
|
</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>
|
<div class="channel-likes-user-list"></div>
|
||||||
</section>
|
</section>
|
||||||
`;
|
`;
|
||||||
@@ -1852,7 +1847,7 @@ function openMessageLikePopup({ anchor, post, navigate, onToggleLike }) {
|
|||||||
close();
|
close();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1868,6 +1863,7 @@ function renderPostCard(post, {
|
|||||||
onRepost,
|
onRepost,
|
||||||
onShare,
|
onShare,
|
||||||
onEdit,
|
onEdit,
|
||||||
|
channel = null,
|
||||||
isActive = () => true,
|
isActive = () => true,
|
||||||
}) {
|
}) {
|
||||||
const versionsTotal = Number(post?.versionsTotal || 1);
|
const versionsTotal = Number(post?.versionsTotal || 1);
|
||||||
@@ -1961,9 +1957,19 @@ function renderPostCard(post, {
|
|||||||
&& !isDiarySelector(selector)
|
&& !isDiarySelector(selector)
|
||||||
&& !!post.messageRef?.blockchainName
|
&& !!post.messageRef?.blockchainName
|
||||||
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
|
&& String(post.messageRef.blockchainName).trim().toLowerCase() === String(selector.ownerBlockchainName || '').trim().toLowerCase();
|
||||||
|
// Запись владельца – как пост в Threads: аватар и название канала слева сверху, текст и действия под названием.
|
||||||
|
const threadsLayout = isOwnerPost && Boolean(channel);
|
||||||
if (isOwnerPost) {
|
if (isOwnerPost) {
|
||||||
card.classList.add('channel-message-card--owner');
|
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() === 'удалено';
|
const isDeletedMessage = String(post.body || '').trim().toLowerCase() === 'удалено';
|
||||||
@@ -2024,7 +2030,7 @@ function renderPostCard(post, {
|
|||||||
}
|
}
|
||||||
const body = document.createElement('p');
|
const body = document.createElement('p');
|
||||||
body.className = 'channel-message-body';
|
body.className = 'channel-message-body';
|
||||||
body.textContent = parsedBody.text;
|
appendShineMessageLinks(body, parsedBody.text, { navigate, viewMode: 'feed' });
|
||||||
card.append(body);
|
card.append(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2066,12 +2072,22 @@ function renderPostCard(post, {
|
|||||||
try {
|
try {
|
||||||
await onToggleLike(post.messageRef, isLiked ? 'unlike' : 'like');
|
await onToggleLike(post.messageRef, isLiked ? 'unlike' : 'like');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showToast(toUserMessage(error, 'Не удалось изменить лайк.'));
|
showToast(toUserMessage(error, 'Не удалось изменить лайк.'), { kind: 'error' });
|
||||||
} finally {
|
} finally {
|
||||||
if (likeButton.isConnected) likeButton.disabled = false;
|
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');
|
const discussionButton = document.createElement('button');
|
||||||
discussionButton.type = 'button';
|
discussionButton.type = 'button';
|
||||||
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
|
discussionButton.className = 'ui-button channel-action-item channel-action-discussion';
|
||||||
@@ -2083,15 +2099,33 @@ function renderPostCard(post, {
|
|||||||
if (post.recentRepliers.length) {
|
if (post.recentRepliers.length) {
|
||||||
const faces = document.createElement('span');
|
const faces = document.createElement('span');
|
||||||
faces.className = 'channel-action-faces';
|
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);
|
discussionButton.append(faces);
|
||||||
}
|
}
|
||||||
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
|
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) => {
|
discussionButton.addEventListener('click', (event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
const route = buildThreadRoute(post.messageRef, selector);
|
openDiscussion({ withEditor: true });
|
||||||
if (route) navigate(route);
|
|
||||||
});
|
});
|
||||||
|
// Нажатие на саму запись открывает её вместе с обсуждением.
|
||||||
|
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');
|
const replyButton = document.createElement('button');
|
||||||
replyButton.type = 'button';
|
replyButton.type = 'button';
|
||||||
@@ -2105,6 +2139,7 @@ function renderPostCard(post, {
|
|||||||
replyButton.addEventListener('click', (event) => {
|
replyButton.addEventListener('click', (event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
animatePress(event.currentTarget);
|
animatePress(event.currentTarget);
|
||||||
|
if (state.session.isAuthorized) { openDiscussion({ withEditor: true }); return; }
|
||||||
openReplyModal({
|
openReplyModal({
|
||||||
onSubmit: async (text) => onReply(post.messageRef, text),
|
onSubmit: async (text) => onReply(post.messageRef, text),
|
||||||
isActive,
|
isActive,
|
||||||
@@ -2130,13 +2165,42 @@ function renderPostCard(post, {
|
|||||||
shareButton.addEventListener('click', async (event) => {
|
shareButton.addEventListener('click', async (event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
animatePress(event.currentTarget);
|
animatePress(event.currentTarget);
|
||||||
const route = buildThreadRoute(post.messageRef, selector);
|
const route = buildThreadRoute(post, selector);
|
||||||
await onShare(route);
|
await onShare(route);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
|
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа.
|
||||||
actions.append(likeButton, shareButton, discussionButton);
|
// В раскладке 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.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) {
|
if (post.msgSubType === MSG_SUBTYPE_TEXT_REPOST && post.targetRef?.blockchainName && Number.isFinite(post.targetRef?.blockNumber) && post.targetRef?.blockHash) {
|
||||||
const originalBtn = document.createElement('button');
|
const originalBtn = document.createElement('button');
|
||||||
originalBtn.type = 'button';
|
originalBtn.type = 'button';
|
||||||
@@ -2210,12 +2274,12 @@ function renderPostCard(post, {
|
|||||||
danger: true,
|
danger: true,
|
||||||
})) return;
|
})) return;
|
||||||
try { await onEdit(post.messageRef, '', { isDelete: true }); }
|
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 }) });
|
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
|
||||||
attachMessageMenu(card, headRow, menuItems);
|
attachMessageMenu(card, headRow, menuItems);
|
||||||
if (isOwnerPost) {
|
if (isOwnerPost && !threadsLayout) {
|
||||||
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
|
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
|
||||||
const meta = document.createElement('div');
|
const meta = document.createElement('div');
|
||||||
meta.className = 'channel-message-meta';
|
meta.className = 'channel-message-meta';
|
||||||
@@ -2252,7 +2316,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
|||||||
const actionButton = document.createElement('button');
|
const actionButton = document.createElement('button');
|
||||||
actionButton.type = 'button';
|
actionButton.type = 'button';
|
||||||
actionButton.className = 'primary-btn channel-main-action';
|
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');
|
const addMessageButton = document.createElement('button');
|
||||||
addMessageButton.type = 'button';
|
addMessageButton.type = 'button';
|
||||||
@@ -2323,6 +2387,7 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
|||||||
onRepost: handlers.onRepost,
|
onRepost: handlers.onRepost,
|
||||||
onShare: handlers.onShare,
|
onShare: handlers.onShare,
|
||||||
onEdit: handlers.onEdit,
|
onEdit: handlers.onEdit,
|
||||||
|
channel: channelData.channel,
|
||||||
isActive: handlers.isActive,
|
isActive: handlers.isActive,
|
||||||
});
|
});
|
||||||
const key = messageRefKey(item.post.messageRef);
|
const key = messageRefKey(item.post.messageRef);
|
||||||
@@ -2368,6 +2433,13 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
|
|||||||
screen.append(feed);
|
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 hasPendingScrollTarget = pendingScrollByRoute.has(routeKey);
|
||||||
const restorePosition = handlers.restorePosition;
|
const restorePosition = handlers.restorePosition;
|
||||||
const pendingScrollTimer = Number.isFinite(restorePosition) && !hasPendingScrollTarget ? 0 : applyPendingScroll(screen, routeKey, channelData.isOwnChannel || channelData.isDiary || unreadCount === 0);
|
const pendingScrollTimer = Number.isFinite(restorePosition) && !hasPendingScrollTarget ? 0 : applyPendingScroll(screen, routeKey, channelData.isOwnChannel || channelData.isDiary || unreadCount === 0);
|
||||||
@@ -2432,22 +2504,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) {
|
function renderSkeleton(screen) {
|
||||||
const wrap = document.createElement('div');
|
const wrap = document.createElement('div');
|
||||||
wrap.className = 'stack';
|
|
||||||
wrap.append(createSkeletonCard(), createSkeletonCard(), createSkeletonCard());
|
|
||||||
screen.append(wrap);
|
screen.append(wrap);
|
||||||
|
window.setTimeout(() => { if (wrap.isConnected) wrap.append(createSkeletonRows('post', 3)); }, SKELETON_DELAY_MS);
|
||||||
return wrap;
|
return wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function render({ navigate, route, chrome }) {
|
export function render({ navigate, route, chrome }) {
|
||||||
const channelId = route.params.channelId || '';
|
const channelId = route.params.channelId || '';
|
||||||
|
const scrollToMessageOrdinal = route.params.scrollToMessageOrdinal || '';
|
||||||
const routeSelector = buildSelectorFromRoute(route, channelId);
|
const routeSelector = buildSelectorFromRoute(route, channelId);
|
||||||
const routeKey = `${routeSelector?.ownerBlockchainName || ''}:${routeSelector?.channelRootBlockNumber || ''}:${routeSelector?.channelRootBlockHash || ''}`;
|
const routeKey = `${routeSelector?.ownerBlockchainName || ''}:${routeSelector?.channelRootBlockNumber || ''}:${routeSelector?.channelRootBlockHash || ''}`;
|
||||||
|
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack channels-screen channels-screen--channel';
|
screen.className = 'stack channels-screen channels-screen--channel';
|
||||||
const positionKey = `${state.session.login}:channel:${routeKey}`;
|
const positionKey = `${state.session.login}:channel:${routeKey}`;
|
||||||
|
// A deep link must take precedence over a saved scroll position.
|
||||||
|
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
let refreshSeq = 0;
|
let refreshSeq = 0;
|
||||||
@@ -2480,16 +2603,16 @@ export function render({ navigate, route, chrome }) {
|
|||||||
const channelHeaderButton = document.createElement('button');
|
const channelHeaderButton = document.createElement('button');
|
||||||
channelHeaderButton.type = 'button';
|
channelHeaderButton.type = 'button';
|
||||||
channelHeaderButton.className = 'topbar-identity channel-header-route-btn';
|
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;
|
channelHeaderButton.disabled = true;
|
||||||
|
|
||||||
const header = createTopBar({
|
const header = createTopBar({
|
||||||
center: channelHeaderButton,
|
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',
|
className: 'channel-view-topbar topbar--identity',
|
||||||
actions: [
|
actions: [
|
||||||
{
|
{
|
||||||
icon: 'moreVertical',
|
iconNode: createOverflowDots(),
|
||||||
title: 'Действия канала',
|
title: 'Действия канала',
|
||||||
ariaLabel: 'Открыть меню канала',
|
ariaLabel: 'Открыть меню канала',
|
||||||
className: 'channel-header-more-btn',
|
className: 'channel-header-more-btn',
|
||||||
@@ -2515,7 +2638,7 @@ export function render({ navigate, route, chrome }) {
|
|||||||
iconHtml: iconHtml('list'),
|
iconHtml: iconHtml('list'),
|
||||||
action: () => {
|
action: () => {
|
||||||
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
|
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
|
||||||
else showToast('В этом канале пока нет оглавления');
|
else showToast('В этом канале пока нет оглавления', { kind: 'info' });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!apiData?.isOwnChannel) {
|
if (!apiData?.isOwnChannel) {
|
||||||
@@ -2889,6 +3012,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 () => {
|
refresh = async () => {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
const seq = ++refreshSeq;
|
const seq = ++refreshSeq;
|
||||||
@@ -2901,181 +3186,52 @@ export function render({ navigate, route, chrome }) {
|
|||||||
? getChannelScrollRoot()?.scrollTop
|
? getChannelScrollRoot()?.scrollTop
|
||||||
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
|
||||||
if (!hadContent) clearContent();
|
if (!hadContent) clearContent();
|
||||||
activeChannelData = null;
|
|
||||||
activeOpenEntrypointHistory = null;
|
|
||||||
activeSelector = null;
|
|
||||||
showStatus('');
|
showStatus('');
|
||||||
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
|
const cacheKey = window.location.pathname;
|
||||||
channelHeaderButton.disabled = true;
|
// При возврате на канал сразу показываем прошлую загрузку, без заглушки и пустого кадра.
|
||||||
channelHeaderButton.onclick = null;
|
const cached = hadContent ? null : readPageData('channel', cacheKey);
|
||||||
if (channelMoreButton) channelMoreButton.disabled = true;
|
let shown = hadContent;
|
||||||
if (channelEntrypointButton) {
|
if (cached) {
|
||||||
channelEntrypointButton.disabled = true;
|
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
|
||||||
channelEntrypointButton.hidden = true;
|
await Promise.resolve();
|
||||||
channelEntrypointButton.onclick = null;
|
if (disposed || seq !== refreshSeq) return;
|
||||||
|
try {
|
||||||
|
paint(cached.data, restorePosition);
|
||||||
|
shown = true;
|
||||||
|
} catch (error) {
|
||||||
|
dropPageData('channel', cacheKey);
|
||||||
|
clearContent();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if (!shown) {
|
||||||
const skeleton = hadContent ? null : renderSkeleton(screen);
|
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 {
|
try {
|
||||||
const apiData = await loadFromApi(route, channelId);
|
const apiData = await loadFromApi(route, channelId);
|
||||||
if (disposed || seq !== refreshSeq) return;
|
if (disposed || seq !== refreshSeq) return;
|
||||||
activeSelector = apiData?.selector || null;
|
const signature = writePageData('channel', cacheKey, apiData);
|
||||||
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
|
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
|
||||||
const entrypointPosts = getEntrypointPosts(apiData?.posts);
|
if (cached && cached.signature === signature) return;
|
||||||
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('Не удалось найти актуальное оглавление');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
skeleton?.remove();
|
skeleton?.remove();
|
||||||
clearContent();
|
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
|
||||||
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),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (disposed || seq !== refreshSeq) return;
|
if (disposed || seq !== refreshSeq) return;
|
||||||
skeleton?.remove();
|
skeleton?.remove();
|
||||||
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
|
||||||
|
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
|
||||||
if (isChannelsDemoMode()) {
|
if (isChannelsDemoMode()) {
|
||||||
renderDemoFallback(screen, navigate, error);
|
renderDemoFallback(screen, navigate, error);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
|||||||
import { parseMessageAttachments } from '../services/attachment-format.js';
|
import { parseMessageAttachments } from '../services/attachment-format.js';
|
||||||
import {
|
import {
|
||||||
animatePress,
|
animatePress,
|
||||||
createSkeletonCard,
|
createLoadErrorCard,
|
||||||
|
createSkeletonRows,
|
||||||
|
SKELETON_DELAY_MS,
|
||||||
formatListTime,
|
formatListTime,
|
||||||
readChannelNotificationsState,
|
readChannelNotificationsState,
|
||||||
showToast,
|
showToast,
|
||||||
@@ -20,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||||
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.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' } };
|
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();
|
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() {
|
function mapMockGroups() {
|
||||||
const mapRow = (channel) => ({
|
const mapRow = (channel) => ({
|
||||||
@@ -891,6 +715,35 @@ function mapApiFeed(feed, notificationsState, diaryPayload = null) {
|
|||||||
return { ownChannels, followedUserChannels, subscribedChannels, index };
|
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) {
|
function toListModel(groups) {
|
||||||
return [
|
return [
|
||||||
...(groups.ownChannels || []),
|
...(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 ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
heading.textContent = listState.query ? 'Ничего не найдено' : listState.viewMode === CHANNELS_VIEW_DELETED ? 'Удалённых каналов нет' : listState.viewMode === CHANNELS_VIEW_FOLLOWING ? 'Пока нет подписок' : listState.viewMode === CHANNELS_VIEW_OWNED ? 'Здесь будут ваши каналы' : 'Откройте свой первый канал';
|
||||||
const text = document.createElement('p');
|
const text = document.createElement('p');
|
||||||
text.className = 'meta-muted';
|
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');
|
const action = document.createElement('button');
|
||||||
action.type = 'button';
|
action.type = 'button';
|
||||||
action.className = 'primary-btn';
|
action.className = 'primary-btn';
|
||||||
action.textContent = state.session.isAuthorized ? 'Найти по @автору' : 'Войти';
|
action.textContent = 'Найти каналы';
|
||||||
action.addEventListener('click', () => state.session.isAuthorized ? openChannelFinderModal({ navigate }) : navigate('login-view'));
|
action.addEventListener('click', () => navigate('search-view'));
|
||||||
wrap.append(heading, text, action);
|
wrap.append(heading, text, action);
|
||||||
|
|
||||||
return wrap;
|
return wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderSkeletonList(container, count = 4) {
|
function renderSkeletonList(container, count = 4) {
|
||||||
container.innerHTML = '';
|
container.replaceChildren(createSkeletonRows('list', count));
|
||||||
const list = document.createElement('div');
|
|
||||||
list.className = 'stack';
|
|
||||||
for (let i = 0; i < count; i += 1) {
|
|
||||||
list.append(createSkeletonCard());
|
|
||||||
}
|
|
||||||
container.append(list);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderErrorState(container, error, onRetry) {
|
function renderErrorState(container, error, onRetry) {
|
||||||
const errCard = document.createElement('div');
|
container.append(createLoadErrorCard({
|
||||||
errCard.className = 'card stack channels-status';
|
title: 'Не удалось загрузить каналы',
|
||||||
|
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
|
||||||
const title = document.createElement('strong');
|
onRetry,
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
|
||||||
@@ -1069,7 +903,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
|
|||||||
}
|
}
|
||||||
|
|
||||||
const list = document.createElement('div');
|
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 });
|
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 }) {
|
async function loadFeedAndRender({ screen, listState, contentEl, navigate, silent = false }) {
|
||||||
if (listState.disposed) return;
|
if (listState.disposed) return;
|
||||||
const seq = ++listState.loadSeq;
|
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) {
|
if (!state.session.isAuthorized) {
|
||||||
setChannelsFeed(null, {});
|
setChannelsFeed(null, {});
|
||||||
@@ -1226,7 +1077,7 @@ export function render({ navigate, route, chrome }) {
|
|||||||
className: 'topbar--root',
|
className: 'topbar--root',
|
||||||
actions: [
|
actions: [
|
||||||
{
|
{
|
||||||
icon: 'moreVertical',
|
iconNode: createOverflowDots(),
|
||||||
title: 'Меню каналов',
|
title: 'Меню каналов',
|
||||||
ariaLabel: 'Открыть меню каналов',
|
ariaLabel: 'Открыть меню каналов',
|
||||||
className: 'channels-menu-btn',
|
className: 'channels-menu-btn',
|
||||||
@@ -1258,8 +1109,8 @@ export function render({ navigate, route, chrome }) {
|
|||||||
const serverSearchButton = document.createElement('button');
|
const serverSearchButton = document.createElement('button');
|
||||||
serverSearchButton.type = 'button';
|
serverSearchButton.type = 'button';
|
||||||
serverSearchButton.className = 'text-btn channels-server-search';
|
serverSearchButton.className = 'text-btn channels-server-search';
|
||||||
serverSearchButton.textContent = 'По @автору';
|
serverSearchButton.textContent = 'Поиск в SHiNE';
|
||||||
serverSearchButton.addEventListener('click', () => openChannelFinderModal({ navigate }));
|
serverSearchButton.addEventListener('click', () => navigate('search-view'));
|
||||||
searchWrap.append(searchInput, serverSearchButton);
|
searchWrap.append(searchInput, serverSearchButton);
|
||||||
|
|
||||||
const tabs = document.createElement('div');
|
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;
|
||||||
|
}
|
||||||
+644
-259
File diff suppressed because it is too large
Load Diff
@@ -1,192 +1,184 @@
|
|||||||
|
// «Новый чат»: выбрать, кому написать. Пока поле пустое – свои близкие и друзья; при вводе –
|
||||||
|
// сначала свои (мгновенно, на устройстве), затем вся сеть (по имени и логину). Нажатие
|
||||||
|
// открывает переписку, профиль – кнопкой справа.
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { authService } from '../state.js';
|
import { createListSection, createPersonRow } from '../components/person-row.js';
|
||||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
import { createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
import { authService, normalizeDmChatId } from '../state.js';
|
||||||
import { makeProfileRoute } from '../services/shine-routes.js';
|
import { makeProfileRoute } from '../services/shine-routes.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'contact-search-view', title: 'Поиск контактов' };
|
export const pageMeta = { id: 'contact-search-view', title: 'Новый чат' };
|
||||||
const searchAvatarSnapshotCache = new Map();
|
|
||||||
const searchAvatarPendingByLogin = new Map();
|
|
||||||
|
|
||||||
async function loadSearchAvatarSnapshot(login) {
|
const RELATION_TEXT = { close_friend: 'близкий друг', friend: 'друг', contact: 'контакт' };
|
||||||
const cleanLogin = String(login || '').trim();
|
const RELATION_ORDER = { close_friend: 0, friend: 1, contact: 2 };
|
||||||
if (!cleanLogin) return null;
|
|
||||||
const key = cleanLogin.toLowerCase();
|
function searchText(value) {
|
||||||
if (searchAvatarSnapshotCache.has(key)) return searchAvatarSnapshotCache.get(key);
|
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function createSearchAvatar(login) {
|
function displayName(person) {
|
||||||
const cleanLogin = String(login || '').trim();
|
const full = [person.firstName, person.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
||||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
return full || String(person.displayName || '').trim() || person.login;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function render({navigate, chrome}) {
|
export function render({ navigate, chrome }) {
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack dm-screen dm-search-screen';
|
screen.className = 'stack dm-screen dm-search-screen';
|
||||||
|
let disposed = false;
|
||||||
let searchTimer = 0;
|
let searchTimer = 0;
|
||||||
let searchSeq = 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');
|
const input = document.createElement('input');
|
||||||
input.className = 'search-field__input contact-search-input';
|
input.className = 'search-field__input contact-search-input';
|
||||||
input.type = 'text';
|
input.type = 'search';
|
||||||
input.name = 'contact';
|
input.placeholder = 'Имя или логин';
|
||||||
input.placeholder = 'Логин или его начало';
|
input.setAttribute('aria-label', 'Кому написать');
|
||||||
input.setAttribute('aria-label', 'Логин для поиска');
|
|
||||||
input.enterKeyHint = 'search';
|
input.enterKeyHint = 'search';
|
||||||
input.autocomplete = 'off';
|
input.autocomplete = 'off';
|
||||||
input.maxLength = 80;
|
input.maxLength = 80;
|
||||||
|
field.append(input);
|
||||||
|
|
||||||
const resultsCard = document.createElement('section');
|
const results = document.createElement('div');
|
||||||
resultsCard.className = 'stack contact-search-results';
|
results.className = 'contact-search-results';
|
||||||
resultsCard.hidden = true;
|
|
||||||
|
|
||||||
const status = document.createElement('p');
|
const openChat = (login) => navigate(`chat/${encodeURIComponent(normalizeDmChatId(login))}`);
|
||||||
status.className = 'contact-search-results-title';
|
|
||||||
|
|
||||||
const resultsList = document.createElement('div');
|
function personRow(person, sub) {
|
||||||
resultsList.className = 'stack dm-list';
|
return createPersonRow({
|
||||||
|
login: person.login,
|
||||||
const renderResults = (matches, query) => {
|
name: displayName(person),
|
||||||
resultsList.innerHTML = '';
|
firstName: person.firstName,
|
||||||
|
lastName: person.lastName,
|
||||||
if (!query.trim()) {
|
avatar: person.avatar || (person.avatarAr ? { ar: person.avatarAr } : null),
|
||||||
status.textContent = '';
|
ring: person.relationFlag === 'close_friend' ? 'close' : '',
|
||||||
resultsCard.hidden = true;
|
sub,
|
||||||
return;
|
onClick: () => openChat(person.login),
|
||||||
}
|
actions: [{ icon: 'profile', label: 'Профиль', onClick: () => navigate(makeProfileRoute(person.login)) }],
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
const runSearch = async () => {
|
function renderResults() {
|
||||||
const query = input.value.trim();
|
if (disposed) return;
|
||||||
|
const query = searchText(input.value).replace(/^@/, '');
|
||||||
|
results.replaceChildren();
|
||||||
|
const frag = document.createDocumentFragment();
|
||||||
|
const ownMatches = mine.filter((person) => !query
|
||||||
|
|| matchesPeopleQuery(`${displayName(person)} ${person.login} ${person.firstName} ${person.lastName}`, 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;
|
const seq = ++searchSeq;
|
||||||
if (!query) {
|
if (query.length < 2) {
|
||||||
renderResults([], '');
|
remote = { query: '', items: [], loading: false, error: null };
|
||||||
|
renderResults();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
remote = { query, items: [], loading: true, error: null };
|
||||||
|
renderResults();
|
||||||
try {
|
try {
|
||||||
const logins = await authService.searchUsers(query);
|
const users = await authService.searchPeople(query, { limit: 20 });
|
||||||
if (seq !== searchSeq) return;
|
if (disposed || seq !== searchSeq) return;
|
||||||
renderResults((logins || []).slice(0, 5), query);
|
remote = { query, items: Array.isArray(users) ? users : [], loading: false, error: null };
|
||||||
} catch (e) {
|
} catch (error) {
|
||||||
if (seq !== searchSeq) return;
|
if (disposed || seq !== searchSeq) return;
|
||||||
status.textContent = `Ошибка поиска: ${e.message || 'unknown'}`;
|
remote = { query, items: [], loading: false, error };
|
||||||
resultsCard.hidden = false;
|
|
||||||
resultsList.innerHTML = '';
|
|
||||||
}
|
}
|
||||||
};
|
renderResults();
|
||||||
|
}
|
||||||
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();
|
|
||||||
});
|
|
||||||
|
|
||||||
input.addEventListener('input', () => {
|
input.addEventListener('input', () => {
|
||||||
scheduleSearch();
|
renderResults();
|
||||||
|
if (searchTimer) window.clearTimeout(searchTimer);
|
||||||
|
searchTimer = window.setTimeout(() => { searchTimer = 0; void runRemote(); }, 300);
|
||||||
});
|
});
|
||||||
input.addEventListener('keydown', (event) => {
|
input.addEventListener('keydown', (event) => {
|
||||||
if (event.key !== 'Enter') return;
|
if (event.key !== 'Enter') return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
searchButton.click();
|
results.querySelector('.person-row__main')?.click();
|
||||||
});
|
});
|
||||||
|
|
||||||
const formCard = document.createElement('label');
|
// Свои связи – из того же ответа, что и список чатов.
|
||||||
formCard.className = 'search-field contact-search-field';
|
async function loadMine() {
|
||||||
formCard.innerHTML = `<span class="search-field__icon" aria-hidden="true">${iconHtml('search')}</span>`;
|
try {
|
||||||
formCard.append(input, searchButton);
|
const payload = await authService.listContacts();
|
||||||
|
if (disposed) return;
|
||||||
resultsCard.append(status, resultsList);
|
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({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: 'Найти человека',
|
title: 'Новый чат',
|
||||||
back: { label: '←', onClick: () => navigate('messages-list') },
|
back: { onClick: () => navigate('messages-list') },
|
||||||
}));
|
}));
|
||||||
screen.append(
|
screen.append(field, results);
|
||||||
formCard,
|
results.append(createLoadingState({ label: 'Загружаю связи' }));
|
||||||
resultsCard,
|
void loadMine();
|
||||||
);
|
window.requestAnimationFrame(() => { if (!disposed) input.focus(); });
|
||||||
|
|
||||||
screen.cleanup = () => {
|
screen.cleanup = () => {
|
||||||
|
disposed = true;
|
||||||
|
searchSeq += 1;
|
||||||
if (searchTimer) window.clearTimeout(searchTimer);
|
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 { createTopBar } from '../components/topbar.js';
|
||||||
import { addAppLogEntry, authService, state } from '../state.js';
|
import { addAppLogEntry, authService, state } from '../state.js';
|
||||||
import {
|
import {
|
||||||
@@ -258,6 +260,7 @@ export function render({navigate, chrome}) {
|
|||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'nav-list settings-developer-card';
|
card.className = 'nav-list settings-developer-card';
|
||||||
card.innerHTML = `
|
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-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-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>
|
<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>
|
<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 appLogBtn = card.querySelector('#settings-app-log');
|
||||||
const diagnosticsBtn = card.querySelector('#settings-pwa-diagnostics');
|
const diagnosticsBtn = card.querySelector('#settings-pwa-diagnostics');
|
||||||
const pwaInstallBtn = card.querySelector('#settings-pwa-install');
|
const pwaInstallBtn = card.querySelector('#settings-pwa-install');
|
||||||
|
|||||||
@@ -169,10 +169,17 @@ export function render({navigate, chrome}) {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const instructionCard = document.createElement('div');
|
const instructionCard = document.createElement('div');
|
||||||
instructionCard.className = 'card stack';
|
instructionCard.className = 'card stack pairing-guide-card';
|
||||||
instructionCard.innerHTML = `
|
instructionCard.innerHTML = `
|
||||||
<p class="field-label">Как подключить другое устройство</p>
|
<div class="pairing-guide__heading">
|
||||||
<p class="meta-muted">На другом устройстве введите логин и нажмите «Войти через другое устройство». Затем обновите здесь список и нажмите «Подключить» у нужной заявки. Дополнительный пароль вводить не нужно.</p>
|
<span class="pairing-guide__eyebrow">Подключение устройства</span>
|
||||||
|
<p class="field-label pairing-guide__title">Как подключить другое устройство</p>
|
||||||
|
</div>
|
||||||
|
<ol class="pairing-guide__steps">
|
||||||
|
<li><span class="pairing-guide__step-number">1</span><span>На другом устройстве введите логин и нажмите «Войти через другое устройство».</span></li>
|
||||||
|
<li><span class="pairing-guide__step-number">2</span><span>На этом устройстве нажмите «Обновить список».</span></li>
|
||||||
|
<li><span class="pairing-guide__step-number">3</span><span>Сверьте код заявки на обоих устройствах и нажмите «Подключить» у нужной заявки.</span></li>
|
||||||
|
</ol>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// UNUSED FOR NOW: UI настройки дополнительного пароля сохранён ниже в коде,
|
// UNUSED FOR NOW: UI настройки дополнительного пароля сохранён ниже в коде,
|
||||||
@@ -196,7 +203,6 @@ export function render({navigate, chrome}) {
|
|||||||
<span class="field-label">Активные заявки</span>
|
<span class="field-label">Активные заявки</span>
|
||||||
<button class="ghost-btn" type="button" id="refresh-pairing-requests">Обновить список</button>
|
<button class="ghost-btn" type="button" id="refresh-pairing-requests">Обновить список</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="meta-muted">Показываются все активные заявки. Для wallet-заявки выпускается отдельная session-only сессия без передачи постоянных ключей.</p>
|
|
||||||
<div class="stack" id="pairing-requests-list"></div>
|
<div class="stack" id="pairing-requests-list"></div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -612,7 +618,7 @@ export function render({navigate, chrome}) {
|
|||||||
await reloadRequests({ silent: true });
|
await reloadRequests({ silent: true });
|
||||||
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
|
cleanupEvent = authService.onEvent('IncomingTrustedDeviceLoginRequest', () => {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
showToast('Пришла новая заявка на вход через доверенное устройство');
|
showToast('Пришла новая заявка на вход через доверенное устройство', { kind: 'info' });
|
||||||
void reloadRequests({ silent: true });
|
void reloadRequests({ silent: true });
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
makeKeyTransferText,
|
makeKeyTransferText,
|
||||||
renderQrSvg,
|
renderQrSvg,
|
||||||
} from '../services/qr-key-transfer-service.js';
|
} from '../services/qr-key-transfer-service.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'device-qr-view', title: 'Показать QR-код' };
|
export const pageMeta = { id: 'device-qr-view', title: 'Показать QR-код' };
|
||||||
|
|
||||||
@@ -56,7 +57,7 @@ export function render({navigate, chrome}) {
|
|||||||
qrEl.textContent = '';
|
qrEl.textContent = '';
|
||||||
loginEl.textContent = 'Логин: нет данных';
|
loginEl.textContent = 'Логин: нет данных';
|
||||||
keysEl.textContent = 'Ключи: нет данных';
|
keysEl.textContent = 'Ключи: нет данных';
|
||||||
statusEl.textContent = error?.message || 'Не удалось подготовить QR-код.';
|
statusEl.textContent = actionErrorText('Не удалось подготовить QR-код', error);
|
||||||
statusEl.style.display = '';
|
statusEl.style.display = '';
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import {
|
import {
|
||||||
authService,
|
authService,
|
||||||
isSessionInvalidError,
|
isSessionInvalidError,
|
||||||
@@ -72,9 +75,9 @@ export function render({navigate, route, chrome}) {
|
|||||||
|
|
||||||
actionBtn.addEventListener('click', async () => {
|
actionBtn.addEventListener('click', async () => {
|
||||||
const isCurrentSession = session.sessionId === state.session.sessionId;
|
const isCurrentSession = session.sessionId === state.session.sessionId;
|
||||||
const confirmed = window.confirm(
|
const confirmed = await confirmDialog(isCurrentSession
|
||||||
isCurrentSession ? 'Хотите завершить текущую сессию?' : 'Хотите завершить этот сеанс?',
|
? { title: 'Выйти на этом устройстве?', text: 'Чтобы снова пользоваться приложением здесь, придётся войти заново.', confirmLabel: 'Выйти', danger: true }
|
||||||
);
|
: { title: 'Завершить сеанс?', text: 'Это устройство выйдет из аккаунта.', confirmLabel: 'Завершить', danger: true });
|
||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -90,7 +93,7 @@ export function render({navigate, route, chrome}) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isSessionInvalidError(error)) {
|
if (!isSessionInvalidError(error)) {
|
||||||
setAuthError(error.message);
|
setAuthError(error.message);
|
||||||
window.alert(error.message);
|
showToast(toUserMessage(error, 'Не удалось завершить сеанс.'), { kind: 'error' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isCurrentSession) {
|
if (isCurrentSession) {
|
||||||
@@ -112,7 +115,7 @@ export function render({navigate, route, chrome}) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
setAuthError(error.message);
|
||||||
window.alert(error.message);
|
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { showToast } from '../services/channels-ux.js';
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
import {
|
import {
|
||||||
authService,
|
authService,
|
||||||
isSessionInvalidError,
|
isSessionInvalidError,
|
||||||
refreshSessions,
|
refreshSessions,
|
||||||
setAuthError,
|
|
||||||
setAuthInfo,
|
setAuthInfo,
|
||||||
state,
|
state,
|
||||||
terminateCurrentSession,
|
terminateCurrentSession,
|
||||||
@@ -81,11 +82,9 @@ export function render({navigate, chrome}) {
|
|||||||
actions.className = 'nav-list';
|
actions.className = 'nav-list';
|
||||||
actions.innerHTML = `
|
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="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('#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');
|
const sessionsBlock = document.createElement('div');
|
||||||
sessionsBlock.className = 'stack device-sessions';
|
sessionsBlock.className = 'stack device-sessions';
|
||||||
@@ -153,7 +152,13 @@ export function render({navigate, chrome}) {
|
|||||||
closeAll.type = 'button';
|
closeAll.type = 'button';
|
||||||
closeAll.textContent = 'Закрыть все остальные сеансы';
|
closeAll.textContent = 'Закрыть все остальные сеансы';
|
||||||
closeAll.addEventListener('click', async () => {
|
closeAll.addEventListener('click', async () => {
|
||||||
if (!window.confirm('Все остальные активные сеансы будут закрыты. Продолжить?')) return;
|
const confirmed = await confirmDialog({
|
||||||
|
title: 'Закрыть остальные сеансы?',
|
||||||
|
text: 'Все другие устройства выйдут из аккаунта. Это устройство останется.',
|
||||||
|
confirmLabel: 'Закрыть',
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!confirmed) return;
|
||||||
closeAll.disabled = true;
|
closeAll.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await authService.closeOtherSessions();
|
const result = await authService.closeOtherSessions();
|
||||||
@@ -166,8 +171,7 @@ export function render({navigate, chrome}) {
|
|||||||
await terminateCurrentSession({ infoMessage: 'Сессия на этом устройстве уже завершена. Выполните вход заново.' });
|
await terminateCurrentSession({ infoMessage: 'Сессия на этом устройстве уже завершена. Выполните вход заново.' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
showToast(actionErrorText('Не удалось закрыть сеансы', error), { kind: 'error' });
|
||||||
showToast(error.message, { kind: 'error' });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const othersList = document.createElement('div');
|
const othersList = document.createElement('div');
|
||||||
@@ -190,8 +194,7 @@ export function render({navigate, chrome}) {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
showToast(actionErrorText('Не удалось обновить список сеансов', error), { kind: 'error' });
|
||||||
showToast(error.message, { kind: 'error' });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import {
|
import {
|
||||||
authorizeLocalDemoSession,
|
authorizeLocalDemoSession,
|
||||||
isLocalDemoAvailable,
|
isLocalDemoAvailable,
|
||||||
@@ -180,7 +182,7 @@ export function render({ navigate }) {
|
|||||||
await saveEntrySettings(draft);
|
await saveEntrySettings(draft);
|
||||||
navigate('start-view');
|
navigate('start-view');
|
||||||
} catch (error) {
|
} 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}){
|
export function render({navigate,chrome}){
|
||||||
const screen=document.createElement('section');screen.className='stack';
|
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 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 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();
|
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;}});
|
}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{
|
continueButton.addEventListener('click',async()=>{continueButton.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||||
const next=await client.continueRotation({walletMigrationStatus:'COMPLETE'});
|
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();
|
await refresh();
|
||||||
}catch(e){err.textContent=e?.message||String(e);continueButton.disabled=false;refreshBalance.disabled=false;}});
|
}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{
|
skip.addEventListener('click',async()=>{skip.disabled=true;transfer.disabled=true;refreshBalance.disabled=true;err.textContent='';try{
|
||||||
const next=await client.continueRotation({walletMigrationStatus:'SKIPPED'});
|
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();
|
await refresh();
|
||||||
}catch(e){err.textContent=e?.message||String(e);skip.disabled=false;transfer.disabled=!oldWallet;refreshBalance.disabled=false;}});
|
}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({});
|
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();
|
await refresh();
|
||||||
};
|
};
|
||||||
go.addEventListener('click',()=>void run().catch(e=>{err.textContent=e?.message||String(e);go.disabled=false;}));
|
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;});
|
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;
|
void refresh();screen.cleanup=()=>{disposed=true;if(timer)clearTimeout(timer);};return screen;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
describeTransferKeys,
|
describeTransferKeys,
|
||||||
parseKeyTransferText,
|
parseKeyTransferText,
|
||||||
} from '../services/qr-key-transfer-service.js';
|
} from '../services/qr-key-transfer-service.js';
|
||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'login-camera-view', title: 'Войти по QR-коду', showAppChrome: false };
|
export const pageMeta = { id: 'login-camera-view', title: 'Войти по QR-коду', showAppChrome: false };
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ export function render({ navigate }) {
|
|||||||
await video.play?.();
|
await video.play?.();
|
||||||
scanLoop();
|
scanLoop();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
cameraError.textContent = error?.message || 'Не удалось открыть камеру. Проверьте разрешения браузера.';
|
cameraError.textContent = actionErrorText('Не удалось открыть камеру. Проверьте разрешения браузера', error);
|
||||||
cameraError.style.display = '';
|
cameraError.style.display = '';
|
||||||
setStatus(status, cameraError.textContent, 'error');
|
setStatus(status, cameraError.textContent, 'error');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,29 @@ import {
|
|||||||
getChatMessages,
|
getChatMessages,
|
||||||
isSessionInvalidError,
|
isSessionInvalidError,
|
||||||
normalizeDmChatId,
|
normalizeDmChatId,
|
||||||
|
rememberDmPeer,
|
||||||
setContacts,
|
setContacts,
|
||||||
state,
|
state,
|
||||||
terminateCurrentSession,
|
terminateCurrentSession,
|
||||||
} from '../state.js';
|
} from '../state.js';
|
||||||
import { renderUserAvatar } from '../components/avatar-image.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 { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||||
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
|
||||||
import { formatListTime } from '../services/channels-ux.js';
|
import { formatListTime } from '../services/channels-ux.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||||
|
import { createErrorState, createLoadingState, createStateMessage } from '../components/feedback.js';
|
||||||
|
import { openHistoryLayer } from '../router.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
export const pageMeta = { id: 'messages-list', title: 'Личные сообщения' };
|
||||||
const PREVIEW_MAX_LEN = 200;
|
const PREVIEW_MAX_LEN = 200;
|
||||||
@@ -48,7 +62,9 @@ async function loadDmAvatarSnapshot(login) {
|
|||||||
return pending;
|
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 cleanLogin = String(login || '').trim();
|
||||||
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
const title = cleanLogin ? `Профиль ${cleanLogin}` : '';
|
||||||
const avatarEl = renderUserAvatar({
|
const avatarEl = renderUserAvatar({
|
||||||
@@ -61,10 +77,13 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
|||||||
className,
|
className,
|
||||||
});
|
});
|
||||||
if (!cleanLogin || avatar?.ar || avatar?.sha256Hex) return avatarEl;
|
if (!cleanLogin || avatar?.ar || avatar?.sha256Hex) return avatarEl;
|
||||||
void loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
const upgrade = () => loadDmAvatarSnapshot(cleanLogin).then((snapshot) => {
|
||||||
if (!avatarEl.isConnected) return;
|
// Фото нет – оставляем инициалы имени как есть (раньше подменялись на букву логина).
|
||||||
|
if (!avatarEl.isConnected || !snapshot?.avatar?.source) return;
|
||||||
const upgraded = renderUserAvatar({
|
const upgraded = renderUserAvatar({
|
||||||
login: cleanLogin,
|
login: cleanLogin,
|
||||||
|
firstName: String(firstName || '').trim(),
|
||||||
|
lastName: String(lastName || '').trim(),
|
||||||
avatar: snapshot?.avatar?.source
|
avatar: snapshot?.avatar?.source
|
||||||
? {
|
? {
|
||||||
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
ar: String(snapshot.avatar.txId || snapshot.avatar.ar || '').trim(),
|
||||||
@@ -78,6 +97,8 @@ function createDmAvatar(login, { className = '', avatar = null, firstName = '',
|
|||||||
upgraded.classList.add('avatar');
|
upgraded.classList.add('avatar');
|
||||||
avatarEl.replaceWith(upgraded);
|
avatarEl.replaceWith(upgraded);
|
||||||
});
|
});
|
||||||
|
if (typeof whenVisible === 'function') whenVisible(avatarEl, upgrade);
|
||||||
|
else void upgrade();
|
||||||
return avatarEl;
|
return avatarEl;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,12 +133,13 @@ function clipPreviewText(text, maxLen = PREVIEW_MAX_LEN) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DM_PREVIEW_ENCRYPTED = 'Зашифрованное сообщение';
|
const DM_PREVIEW_ENCRYPTED = 'Зашифрованное сообщение';
|
||||||
|
const DM_PREVIEW_EMPTY = 'Нет сообщений';
|
||||||
|
|
||||||
async function resolveDialogPreview(dialog) {
|
async function resolveDialogPreview(dialog) {
|
||||||
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
const localText = clipPreviewText(String(dialog?.lastMessageText || '').trim());
|
||||||
if (localText) return localText;
|
if (localText) return localText;
|
||||||
const blobB64 = String(dialog?.lastMessageBlobB64 || '').trim();
|
const blobB64 = String(dialog?.lastMessageBlobB64 || '').trim();
|
||||||
if (!blobB64) return 'Диалог пока пуст.';
|
if (!blobB64) return DM_PREVIEW_EMPTY;
|
||||||
|
|
||||||
const cacheKey = [
|
const cacheKey = [
|
||||||
blobB64,
|
blobB64,
|
||||||
@@ -181,6 +203,10 @@ function latestLocalDialogMessage(peerLogin) {
|
|||||||
return { text, timeMs: resolveLocalMessageTimeMs(latest) };
|
return { text, timeMs: resolveLocalMessageTimeMs(latest) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Последний загруженный список чатов (в памяти вкладки): при возврате на «Чаты» он рисуется
|
||||||
|
// сразу, без пустого кадра, и тихо обновляется с сервера.
|
||||||
|
let lastChatList = null; // { login, items }
|
||||||
|
|
||||||
function formatChatRowTime(ts) {
|
function formatChatRowTime(ts) {
|
||||||
return formatListTime(ts);
|
return formatListTime(ts);
|
||||||
}
|
}
|
||||||
@@ -198,6 +224,7 @@ export function render({ navigate, chrome }) {
|
|||||||
const login = String(state.session.login || '').trim();
|
const login = String(state.session.login || '').trim();
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack dm-screen dm-list-screen';
|
screen.className = 'stack dm-screen dm-list-screen';
|
||||||
|
let disposed = false;
|
||||||
let currentChatFilter = 'all';
|
let currentChatFilter = 'all';
|
||||||
const CHAT_FILTERS = [
|
const CHAT_FILTERS = [
|
||||||
['all', 'Все'],
|
['all', 'Все'],
|
||||||
@@ -237,23 +264,122 @@ export function render({ navigate, chrome }) {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Шапка: поиск по своим чатам и контактам (мгновенно, на устройстве) и «Новый чат».
|
||||||
|
let chatQuery = '';
|
||||||
|
let chatSearch = null;
|
||||||
const head = createTopBar({
|
const head = createTopBar({
|
||||||
title: 'Чаты',
|
title: 'Чаты',
|
||||||
className: 'topbar--root',
|
className: 'topbar--root',
|
||||||
actions: [
|
actions: [
|
||||||
{
|
{
|
||||||
icon: 'search',
|
icon: 'search',
|
||||||
title: 'Найти человека',
|
title: 'Поиск по чатам',
|
||||||
ariaLabel: 'Найти человека',
|
ariaLabel: 'Поиск по чатам',
|
||||||
className: 'messages-search-btn',
|
className: 'messages-search-btn',
|
||||||
|
onClick: () => openChatsSearch(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: 'compose',
|
||||||
|
title: 'Новый чат',
|
||||||
|
ariaLabel: 'Новый чат',
|
||||||
|
className: 'messages-compose-btn',
|
||||||
onClick: () => navigate('contact-search-view'),
|
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');
|
const list = document.createElement('div');
|
||||||
list.className = 'stack dm-list';
|
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) {
|
function renderRow(item) {
|
||||||
const row = document.createElement('article');
|
const row = document.createElement('article');
|
||||||
row.className = 'list-item dm-dialog-card';
|
row.className = 'list-item dm-dialog-card';
|
||||||
@@ -263,6 +389,7 @@ function renderRow(item) {
|
|||||||
avatar: item.avatar,
|
avatar: item.avatar,
|
||||||
firstName: item.firstName,
|
firstName: item.firstName,
|
||||||
lastName: item.lastName,
|
lastName: item.lastName,
|
||||||
|
whenVisible,
|
||||||
});
|
});
|
||||||
avatarEl.classList.add('avatar');
|
avatarEl.classList.add('avatar');
|
||||||
const avatarWrap = document.createElement('div');
|
const avatarWrap = document.createElement('div');
|
||||||
@@ -273,6 +400,7 @@ function renderRow(item) {
|
|||||||
<div class="dm-row-main">
|
<div class="dm-row-main">
|
||||||
<div class="dm-row-titleline dm-row-titlewrap">
|
<div class="dm-row-titleline dm-row-titlewrap">
|
||||||
<strong class="dm-row-title"></strong>
|
<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>` : ''}
|
${relationBadge ? `<span class="dm-contact-note dm-contact-note--${relationFlag}">${relationBadge}</span>` : ''}
|
||||||
</div>
|
</div>
|
||||||
<p class="dm-row-last-message"></p>
|
<p class="dm-row-last-message"></p>
|
||||||
@@ -281,7 +409,11 @@ function renderRow(item) {
|
|||||||
<div class="dm-row-meta-line">
|
<div class="dm-row-meta-line">
|
||||||
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
${item.lastMessageTimeMs ? '<span class="dm-row-time"></span>' : '<span class="dm-row-time dm-row-time--empty"></span>'}
|
||||||
</div>
|
</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>
|
</div>
|
||||||
`;
|
`;
|
||||||
const titleEl = row.querySelector('.dm-row-title');
|
const titleEl = row.querySelector('.dm-row-title');
|
||||||
@@ -291,18 +423,146 @@ function renderRow(item) {
|
|||||||
const fullName = [String(item.firstName || '').trim(), String(item.lastName || '').trim()].filter(Boolean).join(' ');
|
const fullName = [String(item.firstName || '').trim(), String(item.lastName || '').trim()].filter(Boolean).join(' ');
|
||||||
titleEl.textContent = fullName || String(item.peerLogin || '');
|
titleEl.textContent = fullName || String(item.peerLogin || '');
|
||||||
}
|
}
|
||||||
if (previewEl) previewEl.textContent = 'Загрузка…';
|
|
||||||
if (timeEl) timeEl.textContent = formatChatRowTime(item.lastMessageTimeMs);
|
if (timeEl) timeEl.textContent = formatChatRowTime(item.lastMessageTimeMs);
|
||||||
row.prepend(avatarWrap);
|
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-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;
|
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) {
|
||||||
|
return matchesPeopleQuery(`${item.firstName || ''} ${item.lastName || ''} ${item.peerLogin || ''}`, 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() {
|
async function loadList() {
|
||||||
if (state.session.isLocalDemo) {
|
if (state.session.isLocalDemo) {
|
||||||
const empty = document.createElement('div');
|
const empty = document.createElement('div');
|
||||||
@@ -311,16 +571,19 @@ function renderRow(item) {
|
|||||||
list.replaceChildren(empty);
|
list.replaceChildren(empty);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const seq = ++loadSeq;
|
||||||
|
// Первый показ – спиннер, но только если ждать заметно (без мелькания).
|
||||||
|
if (!lastItems && !list.childElementCount) list.replaceChildren(createLoadingState({ label: 'Загружаю чаты' }));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = await authService.listContacts();
|
const payload = await authService.listContacts();
|
||||||
|
if (disposed || seq !== loadSeq) return;
|
||||||
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
||||||
const contacts = dialogs
|
const contacts = dialogs
|
||||||
.filter((dialog) => normalizeRelationFlag(dialog?.relationFlag) !== 'none')
|
.filter((dialog) => normalizeRelationFlag(dialog?.relationFlag) !== 'none')
|
||||||
.map((dialog) => String(dialog?.peerLogin || '').trim())
|
.map((dialog) => String(dialog?.peerLogin || '').trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
setContacts(contacts);
|
setContacts(contacts);
|
||||||
list.innerHTML = '';
|
|
||||||
|
|
||||||
const byPeer = new Map();
|
const byPeer = new Map();
|
||||||
dialogs.forEach((dialog) => {
|
dialogs.forEach((dialog) => {
|
||||||
@@ -361,33 +624,34 @@ function renderRow(item) {
|
|||||||
byPeer.set(key, newest);
|
byPeer.set(key, newest);
|
||||||
});
|
});
|
||||||
|
|
||||||
const rows = Array.from(byPeer.values())
|
byPeer.forEach((item) => rememberDmPeer({
|
||||||
// Технический tombstone очистки истории сам по себе не создаёт видимый диалог.
|
login: item.peerLogin,
|
||||||
// Пустые друзья/контакты остаются, а пользователь без связи исчезает после очистки.
|
relationType: item.relationFlag,
|
||||||
.filter((item) => normalizeRelationFlag(item.relationFlag) !== 'none' || Boolean(item.hasDialog))
|
firstName: item.firstName,
|
||||||
.filter((item) => currentChatFilter === 'all' || normalizeRelationFlag(item.relationFlag) === currentChatFilter)
|
lastName: item.lastName,
|
||||||
.sort((a, b) => {
|
avatar: item.avatar,
|
||||||
const orderA = relationOrder(a.relationFlag);
|
shineStatus: item.shineStatus,
|
||||||
const orderB = relationOrder(b.relationFlag);
|
}));
|
||||||
if (orderA !== orderB) return orderA - orderB;
|
|
||||||
return compareChatRows(a, b);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!rows.length) {
|
const pinnedOrder = getPinnedDmChats();
|
||||||
const empty = document.createElement('div');
|
byPeer.forEach((item) => {
|
||||||
empty.className = 'empty-note';
|
const id = normalizeDmChatId(item.peerLogin);
|
||||||
empty.textContent = 'Пока нет переписок. Найдите человека через поиск вверху.';
|
item.pinned = pinnedOrder.includes(id);
|
||||||
list.append(empty);
|
item.muted = isDmChatMuted(id);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
rows.forEach((item) => {
|
|
||||||
list.append(renderRow(item));
|
|
||||||
});
|
});
|
||||||
|
// Технический 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) {
|
} catch (error) {
|
||||||
|
if (disposed || seq !== loadSeq) return;
|
||||||
if (isSessionInvalidError(error)) {
|
if (isSessionInvalidError(error)) {
|
||||||
list.innerHTML = '';
|
list.innerHTML = '';
|
||||||
|
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'card stack';
|
card.className = 'card stack';
|
||||||
|
|
||||||
@@ -413,22 +677,45 @@ function renderRow(item) {
|
|||||||
list.append(card);
|
list.append(card);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Уже показанный список не стираем из-за неудачного обновления.
|
||||||
list.innerHTML = '';
|
if (lastItems) return;
|
||||||
const fail = document.createElement('div');
|
list.replaceChildren(createErrorState({
|
||||||
fail.className = 'card meta-muted';
|
title: 'Не удалось загрузить чаты',
|
||||||
fail.textContent = `Не удалось загрузить сообщения: ${error.message || 'unknown'}`;
|
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||||
list.append(fail);
|
onRetry: () => { list.replaceChildren(); void loadList(); },
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadForFilter = () => { void loadList(); };
|
// Фильтр перерисовывает уже загруженный список мгновенно и тихо обновляет его с сервера.
|
||||||
|
reloadForFilter = () => {
|
||||||
|
startExpanded = false;
|
||||||
|
renderList();
|
||||||
|
void loadList();
|
||||||
|
};
|
||||||
|
|
||||||
chrome?.setTopbar(head);
|
chrome?.setTopbar(head);
|
||||||
screen.append(filterRow, list);
|
screen.append(filterRow, list, rowMenuAnchor);
|
||||||
|
if (lastItems) renderList();
|
||||||
loadList();
|
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;
|
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 });
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { authService } from '../state.js';
|
|||||||
import { KeyRotationClient } from '../services/key-rotation-service.js';
|
import { KeyRotationClient } from '../services/key-rotation-service.js';
|
||||||
import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js';
|
import { inspectBlockchainDataItem } from '../services/blockchain-entry-inspector.js';
|
||||||
import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
import { makeProfileRoute, makeShineChannelRoute, makeShineMessageRoute } from '../services/shine-routes.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'my-blockchain-view', title: 'Мой блокчейн' };
|
export const pageMeta = { id: 'my-blockchain-view', title: 'Мой блокчейн' };
|
||||||
|
|
||||||
@@ -481,24 +482,40 @@ function createEntryCard({ item, inspection, parseError, channelNames, blockchai
|
|||||||
return card;
|
return card;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function render({ navigate, chrome }) {
|
export function render({ navigate, chrome }, { historyOnly = false } = {}) {
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack my-blockchain-screen';
|
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');
|
if (!historyOnly) {
|
||||||
intro.className = 'card stack';
|
const intro = document.createElement('div');
|
||||||
intro.innerHTML = '<strong>История ваших действий</strong><span class="meta-muted">Это текущая активная версия вашего блокчейна. Хэши записей сохраняют логическую идентичность при fork.</span>';
|
intro.className = 'card stack';
|
||||||
const rotate = document.createElement('button');
|
const historyButton = document.createElement('button');
|
||||||
rotate.type = 'button';
|
historyButton.type = 'button';
|
||||||
rotate.className = 'primary-btn';
|
historyButton.className = 'nav-row';
|
||||||
rotate.textContent = 'Сменить пароль / ключи';
|
historyButton.textContent = 'Показать историю моего блокчейна';
|
||||||
rotate.addEventListener('click', () => navigate('key-rotation-view'));
|
historyButton.addEventListener('click', () => navigate('my-blockchain-history-view'));
|
||||||
intro.append(rotate);
|
const filesButton = document.createElement('button');
|
||||||
screen.append(intro);
|
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');
|
const list = document.createElement('div');
|
||||||
list.className = 'stack my-blockchain-list';
|
list.className = 'stack my-blockchain-list';
|
||||||
|
list.hidden = false;
|
||||||
screen.append(list);
|
screen.append(list);
|
||||||
const more = document.createElement('button');
|
const more = document.createElement('button');
|
||||||
more.type = 'button';
|
more.type = 'button';
|
||||||
@@ -593,7 +610,7 @@ export function render({ navigate, chrome }) {
|
|||||||
if (disposed || seq !== loadSeq) return;
|
if (disposed || seq !== loadSeq) return;
|
||||||
const err = document.createElement('div');
|
const err = document.createElement('div');
|
||||||
err.className = 'card';
|
err.className = 'card';
|
||||||
err.textContent = `Не удалось загрузить блокчейн: ${error?.message || error}`;
|
err.textContent = actionErrorText('Не удалось загрузить блокчейн', error);
|
||||||
list.append(err);
|
list.append(err);
|
||||||
} finally {
|
} finally {
|
||||||
if (seq === loadSeq) {
|
if (seq === loadSeq) {
|
||||||
|
|||||||
+2286
-1122
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,17 @@
|
|||||||
// Адаптер реальных данных → нейтральная модель движка force-графа.
|
// Ответ сервера (после buildGraphModel в network-view.js) → люди и нити для карты связей.
|
||||||
//
|
// Сервер не трогаем – только чтение.
|
||||||
// Источник — результат buildGraphModel() из network-view.js (он уже нормализует ответ
|
|
||||||
// authService.getUserConnectionsGraph в роли/направления/метки). Здесь только конвертация
|
|
||||||
// в форму, которую понимает движок ({ focusId, nodes[] }). Сервер не трогаем — это чтение.
|
|
||||||
|
|
||||||
function normLogin(value) {
|
function normLogin(value) {
|
||||||
return String(value || '').trim();
|
return String(value || '').trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normKey(value) {
|
||||||
|
return normLogin(value).toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||||
|
|
||||||
function relationTypeFromRelation(relation) {
|
export function relationTypeFromRelation(relation) {
|
||||||
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
|
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
|
||||||
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
|
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
|
||||||
const role = relation?.role;
|
const role = relation?.role;
|
||||||
@@ -19,60 +20,43 @@ function relationTypeFromRelation(relation) {
|
|||||||
return 'contact';
|
return 'contact';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сила связи (0..1) → радиус орбиты в движке. Реальный API пока не отдаёт численную силу,
|
function personFromMark(login, mark) {
|
||||||
// поэтому выводим её эвристически из роли и направления связи:
|
return {
|
||||||
// - родственники держим ближе всего, контакты — дальше всего;
|
id: normKey(login),
|
||||||
// - взаимные дружеские связи ближе односторонних.
|
login,
|
||||||
function deriveStrength(relation) {
|
name: mark?.displayName || login,
|
||||||
if (relation.isRelative) return 0.9;
|
firstName: mark?.firstName || '',
|
||||||
if (relation?.mark?.relationType === 'close_friend') return 0.9;
|
lastName: mark?.lastName || '',
|
||||||
if (relation.role === 'contact') return 0.4;
|
avatar: mark?.avatar || null,
|
||||||
if (relation.forward && relation.backward) return 0.8;
|
shining: Boolean(mark?.shine),
|
||||||
return 0.55;
|
official: Boolean(mark?.official),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{centerLogin:string, centerMark:object|null, relations:Array}} graphModel
|
* @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) {
|
export function peopleFromGraphModel(graphModel) {
|
||||||
const focusLogin = normLogin(graphModel?.centerLogin);
|
const centerLogin = normLogin(graphModel?.centerLogin);
|
||||||
const centerMark = graphModel?.centerMark || null;
|
const center = personFromMark(centerLogin, graphModel?.centerMark || null);
|
||||||
|
const seen = new Set([center.id]);
|
||||||
const focusNode = {
|
const peers = [];
|
||||||
id: focusLogin,
|
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
|
||||||
login: focusLogin,
|
const login = normLogin(relation?.login);
|
||||||
name: centerMark?.displayName || centerMark?.login || focusLogin,
|
const key = normKey(login);
|
||||||
avatar: centerMark?.avatar || null,
|
if (!login || seen.has(key)) continue;
|
||||||
relationType: 'self',
|
seen.add(key);
|
||||||
strength: 1,
|
const forward = Boolean(relation?.forward);
|
||||||
shining: Boolean(centerMark?.shine),
|
const backward = Boolean(relation?.backward);
|
||||||
official: Boolean(centerMark?.official),
|
peers.push({
|
||||||
tier: 1,
|
person: personFromMark(login, relation?.mark || null),
|
||||||
};
|
relationType: relationTypeFromRelation(relation),
|
||||||
|
// Пунктир на карте – связь только с одной стороны.
|
||||||
const relations = Array.isArray(graphModel?.relations) ? graphModel.relations : [];
|
mutual: forward && backward,
|
||||||
const seen = new Set();
|
// Со стороны центра: взаимно, только центр (out) или только этот человек (in – «ждёт ответа»).
|
||||||
const nodes = relations
|
direction: forward && backward ? 'mutual' : (forward ? 'out' : 'in'),
|
||||||
.map((r) => {
|
});
|
||||||
const login = normLogin(r?.login);
|
}
|
||||||
const key = login.toLowerCase();
|
return { center, peers };
|
||||||
// исключаем сам фокус (не должно быть линии на собственный ник) и дубли
|
|
||||||
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] };
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,659 @@
|
|||||||
|
// Группы людей на карте связей: «Компании» (кто с кем знаком), «Интересы» (кто на что подписан)
|
||||||
|
// и «Города» (кто где живёт).
|
||||||
|
//
|
||||||
|
// Компании ищутся по знакомствам между людьми первого круга – из их собственных графов связей.
|
||||||
|
// Метод Лувена (максимум модулярности) собирает вместе тех, кто плотно знаком между собой:
|
||||||
|
// школа кунг-фу знакома внутри себя, коллеги – внутри себя, а между ними редкие мостики.
|
||||||
|
// Всё считается на устройстве за миллисекунды и детерминированно: те же данные – та же картина.
|
||||||
|
//
|
||||||
|
// Названия: своё (дал владелец карты) → по каналу, который читает большинство компании и
|
||||||
|
// заметно реже остальные → по самому связанному человеку («Илья С. и др.»).
|
||||||
|
//
|
||||||
|
// Раскладка «островами»: внутри компании люди стоят сотами (ровный шаг, подписи не
|
||||||
|
// налезают), в середине – самые связанные, знакомые – рядом. Острова упаковываются вокруг
|
||||||
|
// человека в центре: крупные ближе, связанные между собой – по соседству.
|
||||||
|
|
||||||
|
export const REST_GROUP = 'rest';
|
||||||
|
export const ISLAND_COLORS = 8; // цветов подложек; сами цвета – в движке карты (зависят от темы)
|
||||||
|
|
||||||
|
// Вес знакомства по виду связи: близкие сближают сильнее контактов.
|
||||||
|
const TIE_WEIGHT = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||||
|
const RELATION_RANK = { close_friend: 0, family: 1, friend: 2, contact: 3 };
|
||||||
|
|
||||||
|
export function tieWeight(type, mutual = true) {
|
||||||
|
return (TIE_WEIGHT[type] || 1) * (mutual ? 1 : 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
function byName(a, b) {
|
||||||
|
return String(a.name || a.id).localeCompare(String(b.name || b.id), 'ru');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Короткое имя для подписей: «Илья С.»; без фамилии – как есть.
|
||||||
|
export function shortPersonName(person) {
|
||||||
|
const first = String(person?.firstName || '').trim();
|
||||||
|
const last = String(person?.lastName || '').trim();
|
||||||
|
const text = first && last ? `${first} ${last[0]}.` : String(person?.name || person?.login || person?.id || '');
|
||||||
|
return text.length > 18 ? `${text.slice(0, 17)}…` : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function jaccard(a, b) {
|
||||||
|
if (!a.size || !b.size) return 0;
|
||||||
|
let common = 0;
|
||||||
|
const [small, big] = a.size <= b.size ? [a, b] : [b, a];
|
||||||
|
small.forEach((id) => { if (big.has(id)) common += 1; });
|
||||||
|
return common / (a.size + b.size - common);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Сообщества -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Метод Лувена: узлы переходят в соседнее сообщество, пока это повышает модулярность,
|
||||||
|
* затем сообщества сворачиваются в узлы, и всё повторяется уровнем выше.
|
||||||
|
* @param {string[]} ids
|
||||||
|
* @param {Map<string, Map<string, number>>} weights – веса знакомств (можно несимметрично)
|
||||||
|
* @returns {string[][]} сообщества (одиночки – тоже сообщества)
|
||||||
|
*/
|
||||||
|
export function detectCommunities(ids, weights, { resolution = 1 } = {}) {
|
||||||
|
const order = [...new Set(ids)].sort();
|
||||||
|
if (!order.length) return [];
|
||||||
|
const index = new Map(order.map((id, i) => [id, i]));
|
||||||
|
// Неориентированный граф: у пары – наибольший из весов в обе стороны.
|
||||||
|
const pairs = new Map();
|
||||||
|
weights.forEach((near, a) => {
|
||||||
|
const i = index.get(a);
|
||||||
|
if (i === undefined) return;
|
||||||
|
near.forEach((w, b) => {
|
||||||
|
const j = index.get(b);
|
||||||
|
if (j === undefined || j === i || !(w > 0)) return;
|
||||||
|
const key = i < j ? i * order.length + j : j * order.length + i;
|
||||||
|
pairs.set(key, Math.max(pairs.get(key) || 0, w));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let adj = order.map(() => new Map());
|
||||||
|
let loops = new Float64Array(order.length);
|
||||||
|
let total = 0;
|
||||||
|
pairs.forEach((w, key) => {
|
||||||
|
const i = Math.floor(key / order.length);
|
||||||
|
const j = key % order.length;
|
||||||
|
adj[i].set(j, w);
|
||||||
|
adj[j].set(i, w);
|
||||||
|
total += w;
|
||||||
|
});
|
||||||
|
if (total <= 0) return order.map((id) => [id]);
|
||||||
|
|
||||||
|
let membership = order.map((_, i) => i); // исходный человек → узел текущего уровня
|
||||||
|
for (let level = 0; level < 16; level += 1) {
|
||||||
|
const n = adj.length;
|
||||||
|
const degree = new Float64Array(n);
|
||||||
|
for (let i = 0; i < n; i += 1) {
|
||||||
|
let k = 2 * loops[i];
|
||||||
|
adj[i].forEach((w) => { k += w; });
|
||||||
|
degree[i] = k;
|
||||||
|
}
|
||||||
|
const m2 = 2 * total;
|
||||||
|
const comm = Int32Array.from({ length: n }, (_, i) => i);
|
||||||
|
const tot = Float64Array.from(degree);
|
||||||
|
let improved = false;
|
||||||
|
for (let pass = 0; pass < 40; pass += 1) {
|
||||||
|
let moved = 0;
|
||||||
|
for (let i = 0; i < n; i += 1) {
|
||||||
|
const own = comm[i];
|
||||||
|
const links = new Map();
|
||||||
|
adj[i].forEach((w, j) => { links.set(comm[j], (links.get(comm[j]) || 0) + w); });
|
||||||
|
tot[own] -= degree[i];
|
||||||
|
let best = own;
|
||||||
|
let bestGain = (links.get(own) || 0) - (resolution * tot[own] * degree[i]) / m2;
|
||||||
|
links.forEach((w, c) => {
|
||||||
|
if (c === own) return;
|
||||||
|
const gain = w - (resolution * tot[c] * degree[i]) / m2;
|
||||||
|
if (gain > bestGain + 1e-12) { best = c; bestGain = gain; }
|
||||||
|
else if (best !== own && Math.abs(gain - bestGain) <= 1e-12 && c < best) best = c;
|
||||||
|
});
|
||||||
|
tot[best] += degree[i];
|
||||||
|
if (best !== own) { comm[i] = best; moved += 1; }
|
||||||
|
}
|
||||||
|
if (!moved) break;
|
||||||
|
improved = true;
|
||||||
|
}
|
||||||
|
if (!improved) break;
|
||||||
|
const renum = new Map();
|
||||||
|
for (let i = 0; i < n; i += 1) if (!renum.has(comm[i])) renum.set(comm[i], renum.size);
|
||||||
|
if (renum.size === n) break;
|
||||||
|
const nextAdj = Array.from({ length: renum.size }, () => new Map());
|
||||||
|
const nextLoops = new Float64Array(renum.size);
|
||||||
|
for (let i = 0; i < n; i += 1) {
|
||||||
|
const ci = renum.get(comm[i]);
|
||||||
|
nextLoops[ci] += loops[i];
|
||||||
|
adj[i].forEach((w, j) => {
|
||||||
|
const cj = renum.get(comm[j]);
|
||||||
|
if (ci === cj) {
|
||||||
|
if (i < j) nextLoops[ci] += w;
|
||||||
|
} else {
|
||||||
|
nextAdj[ci].set(cj, (nextAdj[ci].get(cj) || 0) + w);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
membership = membership.map((node) => renum.get(comm[node]));
|
||||||
|
adj = nextAdj;
|
||||||
|
loops = nextLoops;
|
||||||
|
}
|
||||||
|
const groups = new Map();
|
||||||
|
membership.forEach((c, i) => {
|
||||||
|
if (!groups.has(c)) groups.set(c, []);
|
||||||
|
groups.get(c).push(order[i]);
|
||||||
|
});
|
||||||
|
return [...groups.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Самый связанный внутри группы: по нему компания узнаётся («Илья С. и др.»).
|
||||||
|
// При равенстве – тот, кто ближе вам, затем по имени.
|
||||||
|
function hubOf(members, weights, byId) {
|
||||||
|
const inside = new Set(members);
|
||||||
|
const rows = members.map((id) => {
|
||||||
|
let score = 0;
|
||||||
|
weights.get(id)?.forEach((w, other) => { if (inside.has(other)) score += w; });
|
||||||
|
const person = byId.get(id) || { id };
|
||||||
|
return { id, score, rank: RELATION_RANK[person.relationType] ?? 9, person };
|
||||||
|
});
|
||||||
|
rows.sort((a, b) => b.score - a.score || a.rank - b.rank || byName(a.person, b.person));
|
||||||
|
return rows[0]?.id || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// «Илья С. и др.»: число людей подпись покажет отдельно («· 26»), как у названных компаний.
|
||||||
|
function autoLabel(members, hubId, byId) {
|
||||||
|
const hub = shortPersonName(byId.get(hubId) || { id: hubId });
|
||||||
|
return members.length > 1 ? `${hub} и др.` : hub;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Названия по подпискам: канал, который читает заметная часть группы и заметно чаще,
|
||||||
|
* чем все остальные. Каждый канал – одной группе (с самым сильным перевесом).
|
||||||
|
* @returns {Map<string, string>} id группы → ключ канала
|
||||||
|
*/
|
||||||
|
function channelNames(groups, subs, everyone) {
|
||||||
|
const out = new Map();
|
||||||
|
if (!subs?.of?.size) return out;
|
||||||
|
const total = new Map();
|
||||||
|
let known = 0;
|
||||||
|
for (const id of everyone) {
|
||||||
|
const list = subs.of.get(id);
|
||||||
|
if (!list) continue;
|
||||||
|
known += 1;
|
||||||
|
list.forEach((key) => total.set(key, (total.get(key) || 0) + 1));
|
||||||
|
}
|
||||||
|
if (!known) return out;
|
||||||
|
const candidates = [];
|
||||||
|
for (const group of groups) {
|
||||||
|
const n = group.members.length;
|
||||||
|
if (n < 3) continue;
|
||||||
|
const counts = new Map();
|
||||||
|
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => counts.set(key, (counts.get(key) || 0) + 1)));
|
||||||
|
counts.forEach((count, key) => {
|
||||||
|
const share = count / n;
|
||||||
|
const lift = share / ((total.get(key) || count) / known);
|
||||||
|
if (count >= 3 && share >= 0.34 && lift >= 1.3) candidates.push({ group: group.id, key, score: count * lift });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
candidates.sort((a, b) => b.score - a.score || (a.key < b.key ? -1 : 1));
|
||||||
|
const usedChannels = new Set();
|
||||||
|
for (const row of candidates) {
|
||||||
|
if (out.has(row.group) || usedChannels.has(row.key)) continue;
|
||||||
|
out.set(row.group, row.key);
|
||||||
|
usedChannels.add(row.key);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Цвета островов: свои (сохранённые) остаются; остальным – свободный цвет, а когда свободных
|
||||||
|
// нет – тот, что у наименее связанных с этой группой (на карте связанные стоят рядом,
|
||||||
|
// и одинаковые цвета соседей сливались бы).
|
||||||
|
function assignColors(groups, savedColors, weights = null) {
|
||||||
|
const used = new Map(); // цвет → группы
|
||||||
|
const take = (group, color) => {
|
||||||
|
group.color = color;
|
||||||
|
if (!used.has(color)) used.set(color, []);
|
||||||
|
used.get(color).push(group);
|
||||||
|
};
|
||||||
|
groups.forEach((group) => {
|
||||||
|
const color = savedColors.get(group.id);
|
||||||
|
if (group.kind !== 'rest' && Number.isInteger(color) && color >= 0 && color < ISLAND_COLORS && !used.has(color)) take(group, color);
|
||||||
|
});
|
||||||
|
const affinity = (g1, g2) => {
|
||||||
|
if (!weights) return 0;
|
||||||
|
const inside = new Set(g2.members);
|
||||||
|
let sum = 0;
|
||||||
|
g1.members.forEach((id) => weights.get(id)?.forEach((w, other) => { if (inside.has(other)) sum += w; }));
|
||||||
|
return sum;
|
||||||
|
};
|
||||||
|
groups.forEach((group) => {
|
||||||
|
if (group.kind === 'rest' || Number.isInteger(group.color)) return;
|
||||||
|
// Свой цвет у группы – от её id (у компании это её самый связанный человек): перенос
|
||||||
|
// одного человека или новые знакомые не перекрашивают всю карту.
|
||||||
|
const own = hashColor(group.id);
|
||||||
|
let pick = -1;
|
||||||
|
for (let k = 0; k < ISLAND_COLORS; k += 1) {
|
||||||
|
const c = (own + k) % ISLAND_COLORS;
|
||||||
|
if (!used.has(c)) { pick = c; break; }
|
||||||
|
}
|
||||||
|
if (pick < 0) {
|
||||||
|
let best = Infinity;
|
||||||
|
for (let c = 0; c < ISLAND_COLORS; c += 1) {
|
||||||
|
const clash = used.get(c).reduce((sum, other) => sum + 1 + affinity(group, other), 0);
|
||||||
|
if (clash < best) { best = clash; pick = c; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
take(group, pick);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashColor(text) {
|
||||||
|
let h = 2166136261;
|
||||||
|
for (let i = 0; i < text.length; i += 1) {
|
||||||
|
h ^= text.charCodeAt(i);
|
||||||
|
h = Math.imul(h, 16777619);
|
||||||
|
}
|
||||||
|
return (h >>> 0) % ISLAND_COLORS;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortGroups(groups) {
|
||||||
|
return groups.sort((a, b) => (a.kind === 'rest') - (b.kind === 'rest')
|
||||||
|
|| b.members.length - a.members.length
|
||||||
|
|| String(a.label).localeCompare(String(b.label), 'ru'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Компании первого круга.
|
||||||
|
* @param {Object} o
|
||||||
|
* @param {Array<{id:string, name:string, firstName?:string, lastName?:string, relationType:string}>} o.people
|
||||||
|
* @param {Map<string, Map<string, number>>} o.weights – веса знакомств
|
||||||
|
* @param {{ groups: Array<{id:string, name:string, members:string[], color?:number}>, assign: Map<string,string> }} o.saved
|
||||||
|
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> } | null} [o.subs] – подписки для названий
|
||||||
|
* @returns {{ groups: Array<object>, byPerson: Map<string,string>, snapshots: Array<{id:string, members:string[]}> }}
|
||||||
|
*/
|
||||||
|
export function buildCompanies({ people, weights, saved, subs = null }) {
|
||||||
|
const byId = new Map(people.map((person) => [person.id, person]));
|
||||||
|
const ids = people.map((person) => person.id);
|
||||||
|
const assign = new Map([...(saved?.assign || new Map())].filter(([id]) => byId.has(id)));
|
||||||
|
const savedGroups = (saved?.groups || []).filter((group) => group && group.id);
|
||||||
|
const savedById = new Map(savedGroups.map((group) => [group.id, group]));
|
||||||
|
|
||||||
|
const communities = detectCommunities(ids, weights)
|
||||||
|
.map((members) => members.filter((id) => !assign.has(id)))
|
||||||
|
.filter((members) => members.length);
|
||||||
|
|
||||||
|
// Сохранённые компании узнаются по составу: наибольшее совпадение, не меньше трети.
|
||||||
|
const scores = [];
|
||||||
|
communities.forEach((members, ci) => {
|
||||||
|
const set = new Set(members);
|
||||||
|
savedGroups.forEach((group) => {
|
||||||
|
const score = jaccard(set, new Set((group.members || []).filter((id) => byId.has(id) && !assign.has(id))));
|
||||||
|
if (score >= 0.3) scores.push({ ci, id: group.id, score });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
scores.sort((a, b) => b.score - a.score || a.ci - b.ci || (a.id < b.id ? -1 : 1));
|
||||||
|
const matchedCommunity = new Map();
|
||||||
|
const matchedSaved = new Set();
|
||||||
|
for (const row of scores) {
|
||||||
|
if (matchedCommunity.has(row.ci) || matchedSaved.has(row.id)) continue;
|
||||||
|
matchedCommunity.set(row.ci, row.id);
|
||||||
|
matchedSaved.add(row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const groups = new Map();
|
||||||
|
const rest = [];
|
||||||
|
communities.forEach((members, ci) => {
|
||||||
|
const savedId = matchedCommunity.get(ci);
|
||||||
|
if (savedId) {
|
||||||
|
groups.set(savedId, { id: savedId, kind: 'company', members: [...members], saved: true });
|
||||||
|
} else if (members.length >= 3) {
|
||||||
|
const hub = hubOf(members, weights, byId);
|
||||||
|
const id = `a:${hub}`;
|
||||||
|
groups.set(id, { id, kind: 'company', members: [...members], saved: false });
|
||||||
|
} else {
|
||||||
|
rest.push(...members);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Перенесённые вручную – в свою компанию (даже если её состав сейчас не узнан).
|
||||||
|
assign.forEach((groupId, personId) => {
|
||||||
|
if (groupId === REST_GROUP) { rest.push(personId); return; }
|
||||||
|
let group = groups.get(groupId);
|
||||||
|
if (!group && savedById.has(groupId)) {
|
||||||
|
group = { id: groupId, kind: 'company', members: [], saved: true };
|
||||||
|
groups.set(groupId, group);
|
||||||
|
}
|
||||||
|
if (group) group.members.push(personId);
|
||||||
|
else rest.push(personId);
|
||||||
|
});
|
||||||
|
|
||||||
|
const list = [...groups.values()].filter((group) => group.members.length);
|
||||||
|
const named = channelNames(list.filter((group) => !savedById.get(group.id)?.name), subs, ids);
|
||||||
|
for (const group of list) {
|
||||||
|
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
group.hubId = hubOf(group.members, weights, byId);
|
||||||
|
const own = savedById.get(group.id);
|
||||||
|
group.name = String(own?.name || '').trim();
|
||||||
|
group.channel = named.get(group.id) || '';
|
||||||
|
group.autoLabel = group.channel ? (subs.info.get(group.channel)?.name || '') : '';
|
||||||
|
if (!group.autoLabel) group.autoLabel = autoLabel(group.members, group.hubId, byId);
|
||||||
|
group.label = group.name || group.autoLabel;
|
||||||
|
// Коротко – для подписи на мелкой карте: без «и др.».
|
||||||
|
group.shortLabel = group.name || (group.channel ? group.autoLabel : shortPersonName(byId.get(group.hubId) || { id: group.hubId }));
|
||||||
|
}
|
||||||
|
if (rest.length) {
|
||||||
|
rest.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
list.push({ id: REST_GROUP, kind: 'rest', members: rest, name: '', autoLabel: 'Без компании', label: 'Без компании', shortLabel: 'Без компании', hubId: '' });
|
||||||
|
}
|
||||||
|
sortGroups(list);
|
||||||
|
assignColors(list, new Map(savedGroups.map((group) => [group.id, group.color])), weights);
|
||||||
|
|
||||||
|
// Состав узнанных компаний обновляется, чтобы их узнавать и дальше, когда люди прибавятся.
|
||||||
|
const snapshots = [];
|
||||||
|
list.forEach((group) => {
|
||||||
|
const own = savedById.get(group.id);
|
||||||
|
if (!own) return;
|
||||||
|
const now = group.members.filter((id) => !assign.has(id));
|
||||||
|
if (jaccard(new Set(now), new Set(own.members || [])) < 0.85 || own.color !== group.color) {
|
||||||
|
snapshots.push({ id: group.id, members: now, color: group.color });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const byPerson = new Map();
|
||||||
|
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||||
|
return { groups: list, byPerson, snapshots };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Интересы: люди собираются у каналов, на которые подписаны. Каждый – у одного канала, самого
|
||||||
|
* «своего»: из читаемых им каналов – того, что реже всего встречается среди этих людей (общие
|
||||||
|
* «Новости района» читают все, а «Ушу» – только свои). Канал, у которого так набирается
|
||||||
|
* меньше minSize человек, группой не считается – его читатели переходят к следующему.
|
||||||
|
* @param {Object} o
|
||||||
|
* @param {Array<{id:string, name:string}>} o.people
|
||||||
|
* @param {{ of: Map<string,string[]>, info: Map<string,{name:string}> }} o.subs
|
||||||
|
*/
|
||||||
|
export function buildInterestGroups({ people, subs }) {
|
||||||
|
const byId = new Map(people.map((person) => [person.id, person]));
|
||||||
|
const followers = new Map();
|
||||||
|
people.forEach((person) => subs?.of?.get(person.id)?.forEach((key) => {
|
||||||
|
if (!followers.has(key)) followers.set(key, []);
|
||||||
|
followers.get(key).push(person.id);
|
||||||
|
}));
|
||||||
|
const minSize = people.length > 30 ? 3 : 2;
|
||||||
|
const eligible = new Set([...followers.entries()].filter(([, ids]) => ids.length >= minSize).map(([key]) => key));
|
||||||
|
let assignment = new Map();
|
||||||
|
for (let round = 0; round < 12; round += 1) {
|
||||||
|
assignment = new Map();
|
||||||
|
for (const person of people) {
|
||||||
|
let best = '';
|
||||||
|
for (const key of subs?.of?.get(person.id) || []) {
|
||||||
|
if (!eligible.has(key)) continue;
|
||||||
|
const n = followers.get(key).length;
|
||||||
|
if (!best || n < followers.get(best).length || (n === followers.get(best).length && key < best)) best = key;
|
||||||
|
}
|
||||||
|
if (best) assignment.set(person.id, best);
|
||||||
|
}
|
||||||
|
const sizes = new Map();
|
||||||
|
assignment.forEach((key) => sizes.set(key, (sizes.get(key) || 0) + 1));
|
||||||
|
let dropped = false;
|
||||||
|
eligible.forEach((key) => {
|
||||||
|
if ((sizes.get(key) || 0) < minSize) { eligible.delete(key); dropped = true; }
|
||||||
|
});
|
||||||
|
if (!dropped) break;
|
||||||
|
}
|
||||||
|
const byChannel = new Map();
|
||||||
|
assignment.forEach((key, id) => {
|
||||||
|
if (!byChannel.has(key)) byChannel.set(key, []);
|
||||||
|
byChannel.get(key).push(id);
|
||||||
|
});
|
||||||
|
const list = [...byChannel.entries()].map(([key, members]) => {
|
||||||
|
const name = String(subs.info.get(key)?.name || key);
|
||||||
|
return { id: `c:${key}`, kind: 'interest', channel: key, members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||||
|
});
|
||||||
|
const remaining = new Set(people.map((person) => person.id).filter((id) => !assignment.has(id)));
|
||||||
|
for (const group of list) {
|
||||||
|
group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
// Что ещё читают в этой группе – для карточки группы.
|
||||||
|
const counts = new Map();
|
||||||
|
group.members.forEach((id) => subs.of.get(id)?.forEach((key) => {
|
||||||
|
if (key !== group.channel) counts.set(key, (counts.get(key) || 0) + 1);
|
||||||
|
}));
|
||||||
|
group.alsoRead = [...counts.entries()]
|
||||||
|
.filter(([, count]) => count >= 2)
|
||||||
|
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
||||||
|
.slice(0, 3)
|
||||||
|
.map(([key, count]) => ({ key, count, name: String(subs.info.get(key)?.name || key) }));
|
||||||
|
}
|
||||||
|
if (remaining.size) {
|
||||||
|
const members = [...remaining].sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
list.push({ id: REST_GROUP, kind: 'rest', members, name: '', autoLabel: 'Без общих подписок', label: 'Без общих подписок', shortLabel: 'Без подписок', hubId: '' });
|
||||||
|
}
|
||||||
|
sortGroups(list);
|
||||||
|
assignColors(list, new Map());
|
||||||
|
const byPerson = new Map();
|
||||||
|
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||||
|
return { groups: list, byPerson, snapshots: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Города: кто где живёт (по полю «Город» в профиле). Разные написания одного города – одна
|
||||||
|
* группа (cities.js). Когда городов много, города с одним человеком собираются в «Другие города».
|
||||||
|
* @param {Object} o
|
||||||
|
* @param {Array<{id:string, name:string}>} o.people
|
||||||
|
* @param {{ of: Map<string,string> }} o.cities
|
||||||
|
* @param {(value:string) => string} o.cityKey
|
||||||
|
* @param {(key:string, spellings:string[]) => string} o.cityLabel
|
||||||
|
*/
|
||||||
|
export function buildCityGroups({ people, cities, cityKey, cityLabel }) {
|
||||||
|
const byId = new Map(people.map((person) => [person.id, person]));
|
||||||
|
const byCity = new Map();
|
||||||
|
const unknown = [];
|
||||||
|
for (const person of people) {
|
||||||
|
const raw = cities?.of?.get(person.id) || '';
|
||||||
|
const key = raw ? cityKey(raw) : '';
|
||||||
|
if (!key) { unknown.push(person.id); continue; }
|
||||||
|
if (!byCity.has(key)) byCity.set(key, { members: [], spellings: [] });
|
||||||
|
byCity.get(key).members.push(person.id);
|
||||||
|
byCity.get(key).spellings.push(raw);
|
||||||
|
}
|
||||||
|
let list = [...byCity.entries()].map(([key, row]) => {
|
||||||
|
const name = cityLabel(key, row.spellings);
|
||||||
|
return { id: `city:${key}`, kind: 'city', city: key, members: row.members, name: '', autoLabel: name, label: name, shortLabel: name, hubId: '' };
|
||||||
|
});
|
||||||
|
const singles = list.filter((group) => group.members.length === 1);
|
||||||
|
if (list.length > 14 && singles.length > 1) {
|
||||||
|
list = list.filter((group) => group.members.length > 1);
|
||||||
|
const members = singles.flatMap((group) => group.members);
|
||||||
|
list.push({ id: 'city:*', kind: 'city', city: '', members, name: '', autoLabel: 'Другие города', label: 'Другие города', shortLabel: 'Другие города', hubId: '' });
|
||||||
|
}
|
||||||
|
for (const group of list) group.members.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
if (unknown.length) {
|
||||||
|
unknown.sort((a, b) => byName(byId.get(a) || { id: a }, byId.get(b) || { id: b }));
|
||||||
|
list.push({ id: REST_GROUP, kind: 'rest', members: unknown, name: '', autoLabel: 'Город не указан', label: 'Город не указан', shortLabel: 'Не указан', hubId: '' });
|
||||||
|
}
|
||||||
|
sortGroups(list);
|
||||||
|
assignColors(list, new Map());
|
||||||
|
const byPerson = new Map();
|
||||||
|
list.forEach((group) => group.members.forEach((id) => byPerson.set(id, group.id)));
|
||||||
|
return { groups: list, byPerson, snapshots: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Раскладка островами --------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const ISLAND_STEP = 74; // шаг сот: точка и подпись под ней не налезают на соседей
|
||||||
|
export const ISLAND_PAD = 30; // от края точек до края острова (для упаковки)
|
||||||
|
const ISLAND_GAP = 62; // между островами: над каждым – его подпись
|
||||||
|
const NODE_RADIUS = 22; // точка первого круга (как в движке карты)
|
||||||
|
|
||||||
|
// Места на шестиугольной сетке, ближайшие к середине: остров получается круглым при любом
|
||||||
|
// числе людей (а не шестиугольником с недостроенным краем). При равном расстоянии – по углу.
|
||||||
|
function hexSlots(count) {
|
||||||
|
const size = ISLAND_STEP / Math.sqrt(3);
|
||||||
|
const rings = Math.ceil(Math.sqrt(count / 3)) + 2;
|
||||||
|
const all = [];
|
||||||
|
for (let q = -rings; q <= rings; q += 1) {
|
||||||
|
for (let r = Math.max(-rings, -q - rings); r <= Math.min(rings, -q + rings); r += 1) {
|
||||||
|
const x = size * Math.sqrt(3) * (q + r / 2);
|
||||||
|
const y = size * 1.5 * r;
|
||||||
|
all.push({ x, y, d: Math.round(Math.hypot(x, y) * 100), a: Math.atan2(y, x) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all.sort((p, s) => p.d - s.d || p.a - s.a);
|
||||||
|
return all.slice(0, count).map(({ x, y }) => ({ x, y }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Люди острова по сотам: самые связанные – в середине, знакомые – рядом. Начальная
|
||||||
|
* расстановка по спирали, затем жадные обмены местами, пока они сокращают сумму длин
|
||||||
|
* знакомств (с весом) и держат связанных ближе к середине.
|
||||||
|
*/
|
||||||
|
function islandSlots(members, weights, rankOf) {
|
||||||
|
const n = members.length;
|
||||||
|
const slots = hexSlots(n);
|
||||||
|
const index = new Map(members.map((id, i) => [id, i]));
|
||||||
|
const links = members.map(() => []);
|
||||||
|
const strength = new Float64Array(n);
|
||||||
|
members.forEach((a, i) => {
|
||||||
|
weights.get(a)?.forEach((w, b) => {
|
||||||
|
const j = index.get(b);
|
||||||
|
if (j === undefined || j === i) return;
|
||||||
|
links[i].push([j, w]);
|
||||||
|
strength[i] += w;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Начало: по связанности, при равенстве – ближе к вам, затем по имени (порядок members).
|
||||||
|
const order = members.map((_, i) => i).sort((a, b) => strength[b] - strength[a] || rankOf(members[a]) - rankOf(members[b]) || a - b);
|
||||||
|
const at = new Int32Array(n); // человек → номер места
|
||||||
|
order.forEach((person, k) => { at[person] = k; });
|
||||||
|
const radius = slots.map((p) => Math.hypot(p.x, p.y));
|
||||||
|
const centerPull = 0.35;
|
||||||
|
const dist = (s, t) => Math.hypot(slots[s].x - slots[t].x, slots[s].y - slots[t].y);
|
||||||
|
const costAt = (i, s, skip) => {
|
||||||
|
let c = centerPull * strength[i] * radius[s] + 4 * rankOf(members[i]) * radius[s] / ISLAND_STEP;
|
||||||
|
for (const [j, w] of links[i]) if (j !== skip) c += w * dist(s, at[j]);
|
||||||
|
return c;
|
||||||
|
};
|
||||||
|
if (n > 2 && n <= 260) {
|
||||||
|
for (let pass = 0; pass < 8; pass += 1) {
|
||||||
|
let swapped = 0;
|
||||||
|
for (let i = 0; i < n; i += 1) {
|
||||||
|
for (let j = i + 1; j < n; j += 1) {
|
||||||
|
const si = at[i];
|
||||||
|
const sj = at[j];
|
||||||
|
const before = costAt(i, si, j) + costAt(j, sj, i);
|
||||||
|
const after = costAt(i, sj, j) + costAt(j, si, i);
|
||||||
|
if (after < before - 1e-6) {
|
||||||
|
at[i] = sj;
|
||||||
|
at[j] = si;
|
||||||
|
swapped += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!swapped) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out = new Map();
|
||||||
|
members.forEach((id, i) => out.set(id, { x: slots[at[i]].x, y: slots[at[i]].y }));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Острова вокруг центра. Каждый следующий – туда, где он ближе всего к центру (с учётом
|
||||||
|
* растяжения под экран), но рядом с теми островами, с кем у него больше знакомств.
|
||||||
|
* Положение по каждому направлению считается точно: для каждого уже стоящего острова
|
||||||
|
* запретный отрезок расстояний – корни квадратного уравнения.
|
||||||
|
*/
|
||||||
|
function packIslands(islands, affinity, focusRadius, stretch) {
|
||||||
|
const placed = [];
|
||||||
|
const centers = new Map();
|
||||||
|
const ANGLES = 96;
|
||||||
|
for (const island of islands) {
|
||||||
|
let best = null;
|
||||||
|
for (let k = 0; k < ANGLES; k += 1) {
|
||||||
|
const theta = -Math.PI / 2 + (k * Math.PI * 2) / ANGLES;
|
||||||
|
const ux = Math.cos(theta) * stretch.x;
|
||||||
|
const uy = Math.sin(theta) * stretch.y;
|
||||||
|
const uu = ux * ux + uy * uy;
|
||||||
|
const intervals = [];
|
||||||
|
const keep = focusRadius + island.r + ISLAND_GAP;
|
||||||
|
intervals.push([-Infinity, keep / Math.sqrt(uu)]);
|
||||||
|
for (const other of placed) {
|
||||||
|
const reach = island.r + other.r + ISLAND_GAP;
|
||||||
|
const b = -2 * (ux * other.x + uy * other.y);
|
||||||
|
const c = other.x * other.x + other.y * other.y - reach * reach;
|
||||||
|
const disc = b * b - 4 * uu * c;
|
||||||
|
if (disc <= 0) continue;
|
||||||
|
const sq = Math.sqrt(disc);
|
||||||
|
intervals.push([(-b - sq) / (2 * uu), (-b + sq) / (2 * uu)]);
|
||||||
|
}
|
||||||
|
intervals.sort((p, q) => p[0] - q[0]);
|
||||||
|
let d = 0;
|
||||||
|
for (let guard = 0; guard < intervals.length + 2; guard += 1) {
|
||||||
|
let moved = false;
|
||||||
|
for (const [d1, d2] of intervals) {
|
||||||
|
if (d1 < d + 1e-6 && d < d2 - 1e-6) { d = d2; moved = true; }
|
||||||
|
}
|
||||||
|
if (!moved) break;
|
||||||
|
}
|
||||||
|
const x = ux * d;
|
||||||
|
const y = uy * d;
|
||||||
|
let pull = 0;
|
||||||
|
let pullW = 0;
|
||||||
|
affinity.get(island.id)?.forEach((w, otherId) => {
|
||||||
|
const c = centers.get(otherId);
|
||||||
|
if (!c) return;
|
||||||
|
pull += w * Math.hypot(x - c.x, y - c.y);
|
||||||
|
pullW += w;
|
||||||
|
});
|
||||||
|
const cost = d + (pullW ? (0.55 * pull) / pullW : 0) + k * 1e-6;
|
||||||
|
if (!best || cost < best.cost) best = { x, y, cost };
|
||||||
|
}
|
||||||
|
const spot = { id: island.id, x: best.x, y: best.y, r: island.r };
|
||||||
|
placed.push(spot);
|
||||||
|
centers.set(island.id, spot);
|
||||||
|
}
|
||||||
|
return centers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Координаты людей первого круга островами.
|
||||||
|
* @param {Object} o
|
||||||
|
* @param {Array<{id:string, kind:string, members:string[]}>} o.groups – по порядку (крупные первыми)
|
||||||
|
* @param {Map<string, Map<string, number>>} o.weights
|
||||||
|
* @param {(id:string) => number} o.rankOf – близость к центру (0 – близкий … 3 – контакт)
|
||||||
|
* @param {number} o.focusRadius – сколько места оставить вокруг человека в центре
|
||||||
|
* @param {{x:number, y:number}} o.stretch
|
||||||
|
* @returns {{ positions: Map<string,{x:number,y:number}>, islands: Map<string,{x:number,y:number,r:number}> }}
|
||||||
|
*/
|
||||||
|
export function layoutIslands({ groups, weights, rankOf, focusRadius = 70, stretch = { x: 1, y: 1 } }) {
|
||||||
|
const local = new Map();
|
||||||
|
const islands = [];
|
||||||
|
for (const group of groups) {
|
||||||
|
if (!group.members.length) continue;
|
||||||
|
const slots = islandSlots(group.members, weights, rankOf);
|
||||||
|
let r = 0;
|
||||||
|
slots.forEach((p) => { r = Math.max(r, Math.hypot(p.x, p.y)); });
|
||||||
|
local.set(group.id, slots);
|
||||||
|
islands.push({ id: group.id, r: r + NODE_RADIUS + ISLAND_PAD });
|
||||||
|
}
|
||||||
|
// Сколько знакомств между островами – соседями становятся самые связанные.
|
||||||
|
const groupOf = new Map();
|
||||||
|
groups.forEach((group) => group.members.forEach((id) => groupOf.set(id, group.id)));
|
||||||
|
const affinity = new Map();
|
||||||
|
weights.forEach((near, a) => {
|
||||||
|
const ga = groupOf.get(a);
|
||||||
|
if (!ga) return;
|
||||||
|
near.forEach((w, b) => {
|
||||||
|
const gb = groupOf.get(b);
|
||||||
|
if (!gb || gb === ga) return;
|
||||||
|
if (!affinity.has(ga)) affinity.set(ga, new Map());
|
||||||
|
affinity.get(ga).set(gb, (affinity.get(ga).get(gb) || 0) + w);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const centers = packIslands(islands, affinity, focusRadius, stretch);
|
||||||
|
const positions = new Map();
|
||||||
|
local.forEach((slots, groupId) => {
|
||||||
|
const c = centers.get(groupId);
|
||||||
|
slots.forEach((p, id) => positions.set(id, { x: c.x + p.x, y: c.y + p.y }));
|
||||||
|
});
|
||||||
|
return { positions, islands: centers };
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
// Компании карты связей на этом устройстве: свои названия и кого куда перенесли вручную.
|
||||||
|
// Отдельно для аккаунта и для каждой карты (человека в центре). Сами компании каждый раз
|
||||||
|
// находятся заново по знакомствам (communities.js); здесь – только то, что владелец решил сам:
|
||||||
|
// названная компания узнаётся по составу, перенесённый человек остаётся там, куда его поставили.
|
||||||
|
import { state } from '../../state.js';
|
||||||
|
import { REST_GROUP } from './communities.js';
|
||||||
|
|
||||||
|
const PREFIX = 'shine-network-companies-v1:';
|
||||||
|
const MAX_MAPS = 20;
|
||||||
|
const MAX_NAME = 40;
|
||||||
|
|
||||||
|
function ownerLogin() {
|
||||||
|
return String(state.session?.login || '').trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function readAll() {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner) return {};
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(localStorage.getItem(PREFIX + owner) || '{}');
|
||||||
|
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeAll(all) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner) return;
|
||||||
|
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]; });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
localStorage.setItem(PREFIX + owner, JSON.stringify(all));
|
||||||
|
} catch {
|
||||||
|
// Нет места или приватный режим – названия проживут до закрытия экрана.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyEntry() {
|
||||||
|
return { groups: {}, assign: {}, updatedAt: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryOf(all, centerKey) {
|
||||||
|
const entry = all[centerKey];
|
||||||
|
if (!entry || typeof entry !== 'object') return emptyEntry();
|
||||||
|
return {
|
||||||
|
groups: entry.groups && typeof entry.groups === 'object' ? entry.groups : {},
|
||||||
|
assign: entry.assign && typeof entry.assign === 'object' ? entry.assign : {},
|
||||||
|
updatedAt: Number(entry.updatedAt) || 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function save(centerKey, entry) {
|
||||||
|
if (!centerKey) return;
|
||||||
|
const all = readAll();
|
||||||
|
// Компания без названия и без перенесённых в неё людей больше ничего не значит.
|
||||||
|
const used = new Set(Object.values(entry.assign));
|
||||||
|
Object.keys(entry.groups).forEach((id) => {
|
||||||
|
if (!String(entry.groups[id]?.name || '').trim() && !used.has(id)) delete entry.groups[id];
|
||||||
|
});
|
||||||
|
if (!Object.keys(entry.groups).length && !Object.keys(entry.assign).length) delete all[centerKey];
|
||||||
|
else all[centerKey] = { ...entry, updatedAt: Date.now() };
|
||||||
|
writeAll(all);
|
||||||
|
}
|
||||||
|
|
||||||
|
function newId() {
|
||||||
|
return `u${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Что владелец решил сам: { groups: [{ id, name, members, color }], assign: Map(человек → компания) }. */
|
||||||
|
export function getCompanySettings(centerKey) {
|
||||||
|
const entry = entryOf(readAll(), centerKey);
|
||||||
|
return {
|
||||||
|
groups: Object.entries(entry.groups).map(([id, group]) => ({
|
||||||
|
id,
|
||||||
|
name: String(group?.name || '').slice(0, MAX_NAME),
|
||||||
|
members: Array.isArray(group?.members) ? group.members.map(String) : [],
|
||||||
|
color: Number.isInteger(group?.color) ? group.color : undefined,
|
||||||
|
})),
|
||||||
|
assign: new Map(Object.entries(entry.assign).map(([id, group]) => [id, String(group)])),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Снимок для «Отменить»: вернуть всё как было – restoreCompanySettings. */
|
||||||
|
export function snapshotCompanySettings(centerKey) {
|
||||||
|
return JSON.parse(JSON.stringify(entryOf(readAll(), centerKey)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreCompanySettings(centerKey, snapshot) {
|
||||||
|
if (!snapshot) return;
|
||||||
|
save(centerKey, entryOf({ [centerKey]: snapshot }, centerKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Компания, найденная автоматически, становится «своей» (с постоянным id), как только ей
|
||||||
|
// дали название или перенесли в неё человека: дальше её узнают по составу.
|
||||||
|
function ensureSaved(entry, group) {
|
||||||
|
if (entry.groups[group.id]) return group.id;
|
||||||
|
const id = newId();
|
||||||
|
entry.groups[id] = {
|
||||||
|
name: '',
|
||||||
|
members: group.members.filter((personId) => !entry.assign[personId]),
|
||||||
|
color: Number.isInteger(group.color) && group.color >= 0 ? group.color : undefined,
|
||||||
|
};
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Название компании (пустое – вернуть автоматическое). Возвращает id компании. */
|
||||||
|
export function setCompanyName(centerKey, group, name) {
|
||||||
|
const entry = entryOf(readAll(), centerKey);
|
||||||
|
const id = ensureSaved(entry, group);
|
||||||
|
entry.groups[id].name = String(name || '').trim().slice(0, MAX_NAME);
|
||||||
|
save(centerKey, entry);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Перенести человека в компанию (group – из buildCompanies или { id: REST_GROUP }). */
|
||||||
|
export function assignToCompany(centerKey, personId, group) {
|
||||||
|
const entry = entryOf(readAll(), centerKey);
|
||||||
|
if (group.id === REST_GROUP) {
|
||||||
|
entry.assign[personId] = REST_GROUP;
|
||||||
|
} else {
|
||||||
|
const id = ensureSaved(entry, group);
|
||||||
|
entry.assign[personId] = id;
|
||||||
|
}
|
||||||
|
save(centerKey, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Новая компания с одним человеком. Возвращает её id. */
|
||||||
|
export function createCompany(centerKey, name, personId) {
|
||||||
|
const entry = entryOf(readAll(), centerKey);
|
||||||
|
const id = newId();
|
||||||
|
entry.groups[id] = { name: String(name || '').trim().slice(0, MAX_NAME), members: [], color: undefined };
|
||||||
|
entry.assign[personId] = id;
|
||||||
|
save(centerKey, entry);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Обновить состав и цвет узнанных компаний (чтобы узнавать их и дальше). */
|
||||||
|
export function updateCompanySnapshots(centerKey, snapshots) {
|
||||||
|
if (!snapshots?.length) return;
|
||||||
|
const entry = entryOf(readAll(), centerKey);
|
||||||
|
let changed = false;
|
||||||
|
for (const row of snapshots) {
|
||||||
|
const group = entry.groups[row.id];
|
||||||
|
if (!group) continue;
|
||||||
|
group.members = row.members;
|
||||||
|
if (Number.isInteger(row.color)) group.color = row.color;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed) save(centerKey, entry);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,173 @@
|
|||||||
|
// Раскладки карты связей – на этом устройстве, отдельно для аккаунта.
|
||||||
|
// Автоматические раскладки (rings – по близости, companies – компании по знакомствам,
|
||||||
|
// interests – по подпискам, cities – по городам) считаются заново при каждом открытии.
|
||||||
|
// Прежние «по группам», «Подсолнух» и «Мандала» убраны: это была та же близость другой
|
||||||
|
// формой; сохранённые с ними карты открываются «по близости».
|
||||||
|
// «Своя» (manual) – расстановка людей, сохранённая для каждой карты отдельно: координаты
|
||||||
|
// относительно человека в центре плюс базовая автоматическая раскладка, по которой встают
|
||||||
|
// люди, появившиеся на карте позже.
|
||||||
|
import { state } from '../../state.js';
|
||||||
|
|
||||||
|
const LAYOUT_PREFIX = 'shine-network-layout-v1:';
|
||||||
|
const VIEW_PREFIX = 'shine-network-view-v1:';
|
||||||
|
const MAX_MAPS = 40; // старые раскладки вытесняются, чтобы хранилище не росло бесконечно
|
||||||
|
|
||||||
|
export const AUTO_LAYOUT_MODES = ['rings', 'companies', 'interests', 'cities'];
|
||||||
|
const LAYOUT_MODES = [...AUTO_LAYOUT_MODES, 'manual'];
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// Нет места или приватный режим – раскладка проживёт до закрытия экрана.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function autoMode(value) {
|
||||||
|
return AUTO_LAYOUT_MODES.includes(value) ? value : 'rings';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Раньше перетащенные точки действовали в любой раскладке. Чтобы после обновления карта
|
||||||
|
// выглядела как прежде, такие карты считаются «своей раскладкой» поверх прежнего режима.
|
||||||
|
function migrateLegacy(owner) {
|
||||||
|
const view = readJson(VIEW_PREFIX + owner);
|
||||||
|
if (view.layoutV === 2) return;
|
||||||
|
const all = readJson(LAYOUT_PREFIX + owner);
|
||||||
|
const previousMode = autoMode(view.mode);
|
||||||
|
let legacy = false;
|
||||||
|
Object.values(all).forEach((entry) => {
|
||||||
|
if (entry && typeof entry === 'object' && !entry.base) {
|
||||||
|
entry.base = previousMode;
|
||||||
|
legacy = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (legacy) {
|
||||||
|
writeJson(LAYOUT_PREFIX + owner, all);
|
||||||
|
view.autoMode = previousMode;
|
||||||
|
view.mode = 'manual';
|
||||||
|
}
|
||||||
|
view.layoutV = 2;
|
||||||
|
writeJson(VIEW_PREFIX + owner, view);
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryOf(centerKey) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner || !centerKey) return null;
|
||||||
|
const entry = readJson(LAYOUT_PREFIX + owner)[centerKey];
|
||||||
|
return entry && typeof entry === 'object' && entry.points && Object.keys(entry.points).length ? entry : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasManualLayout(centerKey) {
|
||||||
|
return Boolean(entryOf(centerKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getManualLayout(centerKey) {
|
||||||
|
const out = new Map();
|
||||||
|
const points = entryOf(centerKey)?.points || {};
|
||||||
|
for (const [id, point] of Object.entries(points)) {
|
||||||
|
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 getManualBase(centerKey) {
|
||||||
|
return autoMode(entryOf(centerKey)?.base);
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeEntry(centerKey, entry) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner || !centerKey) return;
|
||||||
|
const all = readJson(LAYOUT_PREFIX + owner);
|
||||||
|
if (entry) all[centerKey] = entry;
|
||||||
|
else delete all[centerKey];
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Сохраняет всю расстановку как «свою»; возвращает прежнюю (для «Отменить») или null. */
|
||||||
|
export function saveManualLayout(centerKey, points, base) {
|
||||||
|
const previous = entryOf(centerKey);
|
||||||
|
const stored = {};
|
||||||
|
points.forEach((point, id) => { stored[id] = [Math.round(point.x), Math.round(point.y)]; });
|
||||||
|
writeEntry(centerKey, { points: stored, base: autoMode(base), updatedAt: Date.now() });
|
||||||
|
return previous;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setManualPoint(centerKey, id, point) {
|
||||||
|
if (!id) return;
|
||||||
|
const entry = entryOf(centerKey) || { points: {}, base: 'rings' };
|
||||||
|
entry.points[id] = [Math.round(point.x), Math.round(point.y)];
|
||||||
|
entry.updatedAt = Date.now();
|
||||||
|
writeEntry(centerKey, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Удаляет свою раскладку карты; возвращает удалённую (для «Вернуть») или null. */
|
||||||
|
export function clearManualLayout(centerKey) {
|
||||||
|
const previous = entryOf(centerKey);
|
||||||
|
writeEntry(centerKey, null);
|
||||||
|
return previous;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Возвращает раскладку, снятую clearManualLayout / saveManualLayout (null – удалить). */
|
||||||
|
export function restoreManualLayout(centerKey, entry) {
|
||||||
|
writeEntry(centerKey, entry && entry.points ? entry : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLayoutMode() {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner) return 'rings';
|
||||||
|
migrateLegacy(owner);
|
||||||
|
const mode = readJson(VIEW_PREFIX + owner).mode;
|
||||||
|
return LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Последняя выбранная автоматическая – для карт, у которых своей раскладки нет.
|
||||||
|
export function getAutoLayoutMode() {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
const view = readJson(VIEW_PREFIX + owner);
|
||||||
|
return autoMode(AUTO_LAYOUT_MODES.includes(view.mode) ? view.mode : view.autoMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setLayoutMode(mode) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner) return;
|
||||||
|
const view = readJson(VIEW_PREFIX + owner);
|
||||||
|
view.mode = LAYOUT_MODES.includes(mode) ? mode : 'rings';
|
||||||
|
if (AUTO_LAYOUT_MODES.includes(view.mode)) view.autoMode = view.mode;
|
||||||
|
view.layoutV = 2;
|
||||||
|
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,142 @@
|
|||||||
|
// Кто с кем знаком, кто на что подписан и кто где живёт – данные для «Компаний», «Интересов»
|
||||||
|
// и «Городов».
|
||||||
|
// Собираются по одному запросу на человека, поэтому не перезапрашиваются при каждом открытии:
|
||||||
|
// для своей карты лежат на устройстве, для чужих – в памяти, пока открыто приложение.
|
||||||
|
// Сервер не трогаем: знакомства – из графа связей каждого человека, подписки – из списка
|
||||||
|
// «Подписки» его профиля (публичные каналы), город – из параметра city его профиля.
|
||||||
|
import { state } from '../../state.js';
|
||||||
|
|
||||||
|
const PREFIX = { ties: 'shine-network-ties-v1:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
|
||||||
|
export const PEOPLE_DATA_FRESH_MS = 12 * 60 * 60 * 1000; // старше – освежаются в фоне
|
||||||
|
const TYPE_CODE = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||||
|
const CODE_TYPE = { 3: 'close_friend', 2: 'friend', 1: 'contact' };
|
||||||
|
|
||||||
|
const memory = new Map(); // `${kind}|${owner}|${center}` → запись
|
||||||
|
|
||||||
|
function ownerLogin() {
|
||||||
|
return String(state.session?.login || '').trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function persistent(centerKey) {
|
||||||
|
return Boolean(centerKey) && centerKey === ownerLogin();
|
||||||
|
}
|
||||||
|
|
||||||
|
function readStored(kind, centerKey) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner || !persistent(centerKey)) return null;
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(localStorage.getItem(PREFIX[kind] + owner) || 'null');
|
||||||
|
return raw && typeof raw === 'object' ? raw : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeStored(kind, centerKey, value) {
|
||||||
|
const owner = ownerLogin();
|
||||||
|
if (!owner || !persistent(centerKey)) return;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(PREFIX[kind] + owner, JSON.stringify(value));
|
||||||
|
} catch {
|
||||||
|
// Нет места – данные останутся в памяти до закрытия приложения.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Знакомства: { at, people: Map(человек → Map(знакомый → { type, mutual })) }.
|
||||||
|
* people хранит только тех, у кого граф уже загружен (в том числе пустой).
|
||||||
|
*/
|
||||||
|
export function getTies(centerKey) {
|
||||||
|
const key = `ties|${ownerLogin()}|${centerKey}`;
|
||||||
|
if (memory.has(key)) return memory.get(key);
|
||||||
|
const raw = readStored('ties', centerKey);
|
||||||
|
if (!raw || typeof raw.people !== 'object') return null;
|
||||||
|
const people = new Map();
|
||||||
|
for (const [id, list] of Object.entries(raw.people)) {
|
||||||
|
const near = new Map();
|
||||||
|
if (Array.isArray(list)) {
|
||||||
|
list.forEach((row) => {
|
||||||
|
if (Array.isArray(row) && row[0]) near.set(String(row[0]), { type: CODE_TYPE[row[1]] || 'contact', mutual: row[2] !== 0 });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
people.set(id, near);
|
||||||
|
}
|
||||||
|
const entry = { at: Number(raw.at) || 0, people };
|
||||||
|
memory.set(key, entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveTies(centerKey, entry) {
|
||||||
|
memory.set(`ties|${ownerLogin()}|${centerKey}`, entry);
|
||||||
|
const people = {};
|
||||||
|
entry.people.forEach((near, id) => {
|
||||||
|
people[id] = [...near.entries()].map(([other, tie]) => [other, TYPE_CODE[tie.type] || 1, tie.mutual ? 1 : 0]);
|
||||||
|
});
|
||||||
|
writeStored('ties', centerKey, { at: entry.at, people });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подписки: { at, of: Map(человек → [ключ канала]), info: Map(ключ → { name, owner, slug, bch, root, hash }) }.
|
||||||
|
*/
|
||||||
|
export function getSubs(centerKey) {
|
||||||
|
const key = `subs|${ownerLogin()}|${centerKey}`;
|
||||||
|
if (memory.has(key)) return memory.get(key);
|
||||||
|
const raw = readStored('subs', centerKey);
|
||||||
|
if (!raw || typeof raw.of !== 'object' || typeof raw.info !== 'object') return null;
|
||||||
|
const of = new Map(Object.entries(raw.of).map(([id, list]) => [id, Array.isArray(list) ? list.map(String) : []]));
|
||||||
|
const info = new Map(Object.entries(raw.info).map(([channel, row]) => [channel, {
|
||||||
|
name: String(row?.n || channel),
|
||||||
|
owner: String(row?.o || ''),
|
||||||
|
slug: String(row?.s || ''),
|
||||||
|
bch: String(row?.b || ''),
|
||||||
|
root: Number(row?.r) || 0,
|
||||||
|
hash: String(row?.h || ''),
|
||||||
|
}]));
|
||||||
|
const entry = { at: Number(raw.at) || 0, of, info };
|
||||||
|
memory.set(key, entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSubs(centerKey, entry) {
|
||||||
|
memory.set(`subs|${ownerLogin()}|${centerKey}`, entry);
|
||||||
|
// Каналы, которые больше никто не читает, не храним.
|
||||||
|
const used = new Set();
|
||||||
|
entry.of.forEach((list) => list.forEach((channel) => used.add(channel)));
|
||||||
|
const info = {};
|
||||||
|
entry.info.forEach((row, channel) => {
|
||||||
|
if (used.has(channel)) info[channel] = { n: row.name, o: row.owner, s: row.slug, b: row.bch, r: row.root, h: row.hash };
|
||||||
|
});
|
||||||
|
writeStored('subs', centerKey, { at: entry.at, of: Object.fromEntries(entry.of), info });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Города: { at, of: Map(человек → город как написан; '' – не указан) }. */
|
||||||
|
export function getCities(centerKey) {
|
||||||
|
const key = `cities|${ownerLogin()}|${centerKey}`;
|
||||||
|
if (memory.has(key)) return memory.get(key);
|
||||||
|
const raw = readStored('cities', centerKey);
|
||||||
|
if (!raw || typeof raw.of !== 'object') return null;
|
||||||
|
const entry = { at: Number(raw.at) || 0, of: new Map(Object.entries(raw.of).map(([id, city]) => [id, String(city || '')])) };
|
||||||
|
memory.set(key, entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveCities(centerKey, entry) {
|
||||||
|
memory.set(`cities|${ownerLogin()}|${centerKey}`, entry);
|
||||||
|
writeStored('cities', centerKey, { at: entry.at, of: Object.fromEntries(entry.of) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ключ канала: владелец и короткое имя – одинаковые у всех подписчиков.
|
||||||
|
export function channelKey(row) {
|
||||||
|
return `${String(row?.ownerLogin || '').trim().toLowerCase()}/${String(row?.slug || '').trim().toLowerCase()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function channelInfo(row) {
|
||||||
|
return {
|
||||||
|
name: String(row?.displayName || row?.slug || '').trim() || channelKey(row),
|
||||||
|
owner: String(row?.ownerLogin || ''),
|
||||||
|
slug: String(row?.slug || ''),
|
||||||
|
bch: String(row?.ownerBlockchainName || ''),
|
||||||
|
root: Number(row?.rootBlockNumber) || 0,
|
||||||
|
hash: String(row?.rootBlockHashHex || ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 { authService, state } from '../state.js';
|
||||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||||
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.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';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
|
|
||||||
const CONNECTION_CLOSE_FRIEND = 10;
|
const CONNECTION_CLOSE_FRIEND = 10;
|
||||||
@@ -19,23 +21,39 @@ const CONNECTION_OFFICIAL_UNCONFIRMED = 81;
|
|||||||
const profileSnapshotCache = new Map();
|
const profileSnapshotCache = new Map();
|
||||||
const profileSnapshotPending = new Map();
|
const profileSnapshotPending = new Map();
|
||||||
|
|
||||||
function connectionActionLabel(typeCode) {
|
// Глагол по полу из профиля автора («Добавила вас в друзья»); пока профиль не пришёл или пол
|
||||||
|
// не указан – нейтральное «Добавил(а)».
|
||||||
|
function byGender(gender, male, female, neutral) {
|
||||||
|
if (gender === 'male') return male;
|
||||||
|
if (gender === 'female') return female;
|
||||||
|
return neutral;
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectionActionLabel(typeCode, gender = '') {
|
||||||
|
const verb = (male, female) => byGender(gender, male, female, `${male}(а)`);
|
||||||
switch (Number(typeCode)) {
|
switch (Number(typeCode)) {
|
||||||
case CONNECTION_CLOSE_FRIEND: return 'Добавил(а) вас в близкие друзья';
|
case CONNECTION_CLOSE_FRIEND: return `${verb('Добавил', 'Добавила')} вас в близкие друзья`;
|
||||||
case CONNECTION_UNCLOSE_FRIEND: return 'Убрал(а) вас из близких друзей';
|
case CONNECTION_UNCLOSE_FRIEND: return `${verb('Убрал', 'Убрала')} вас из близких друзей`;
|
||||||
case CONNECTION_FRIEND: return 'Добавил(а) вас в друзья';
|
case CONNECTION_FRIEND: return `${verb('Добавил', 'Добавила')} вас в друзья`;
|
||||||
case CONNECTION_UNFRIEND: return 'Убрал(а) вас из друзей';
|
case CONNECTION_UNFRIEND: return `${verb('Убрал', 'Убрала')} вас из друзей`;
|
||||||
case CONNECTION_SHINE_CONFIRMED: return 'Подтвердил(а), что вы сияющий';
|
case CONNECTION_SHINE_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')}, что вы сияющий`;
|
||||||
case CONNECTION_SHINE_UNCONFIRMED: return 'Снял(а) подтверждение «сияющий»';
|
case CONNECTION_SHINE_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение «сияющий»`;
|
||||||
case CONNECTION_OFFICIAL_CONFIRMED: return 'Подтвердил(а) официальный статус аккаунта';
|
case CONNECTION_OFFICIAL_CONFIRMED: return `${verb('Подтвердил', 'Подтвердила')} официальный статус аккаунта`;
|
||||||
case CONNECTION_OFFICIAL_UNCONFIRMED: return 'Снял(а) подтверждение официального статуса';
|
case CONNECTION_OFFICIAL_UNCONFIRMED: return `${verb('Снял', 'Сняла')} подтверждение официального статуса`;
|
||||||
default: return 'Изменил(а) связь с вами';
|
default: return `${verb('Изменил', 'Изменила')} связь с вами`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function eventActionLabel(typeCode) {
|
function eventActionLabel(typeCode, gender = '') {
|
||||||
if (Number(typeCode) === CONNECTION_UNFOLLOW) return 'Отписался(-ась) от вашего канала';
|
if (Number(typeCode) === CONNECTION_UNFOLLOW) return `${byGender(gender, 'Отписался', 'Отписалась', 'Отписался(-ась)')} от вашего канала`;
|
||||||
return 'Подписался(-ась) на ваш канал';
|
return `${byGender(gender, 'Подписался', 'Подписалась', 'Подписался(-ась)')} на ваш канал`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function actionLabel(item, activeTab) {
|
||||||
|
const gender = String(item.profile?.gender || '');
|
||||||
|
return activeTab === 'connections'
|
||||||
|
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType, gender)
|
||||||
|
: eventActionLabel(item.sourceMsgSubType, gender);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
|
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
|
||||||
@@ -137,15 +155,15 @@ async function enrichItem(item, activeTab) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderEmpty(activeTab) {
|
function renderEmpty(activeTab) {
|
||||||
const card = document.createElement('article');
|
return createStateMessage({
|
||||||
card.className = 'stack notification-empty-state';
|
icon: activeTab === 'events' ? 'channels' : activeTab === 'connections' ? 'network' : 'reply',
|
||||||
const title = document.createElement('strong');
|
title: activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет новостей о связях' : 'Пока нет ответов',
|
||||||
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
|
text: activeTab === 'events'
|
||||||
const text = document.createElement('p');
|
? 'Подписки и отписки от ваших каналов появятся здесь.'
|
||||||
text.className = 'meta-muted';
|
: activeTab === 'connections'
|
||||||
text.textContent = activeTab === 'events' ? 'Подписки и отписки от ваших каналов появятся здесь.' : activeTab === 'connections' ? 'Изменения дружбы и подтверждений появятся здесь.' : 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.';
|
? 'Когда вас добавят в друзья или подтвердят статус, это появится здесь.'
|
||||||
card.append(title, text);
|
: 'Когда кто-то ответит на ваше сообщение в канале или обсуждении, ответ появится здесь.',
|
||||||
return card;
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderAvatar(item) {
|
function renderAvatar(item) {
|
||||||
@@ -270,9 +288,7 @@ function renderItem(item, activeTab, navigate) {
|
|||||||
} else {
|
} else {
|
||||||
const action = document.createElement('p');
|
const action = document.createElement('p');
|
||||||
action.className = 'notification-card__action';
|
action.className = 'notification-card__action';
|
||||||
action.textContent = activeTab === 'connections'
|
action.textContent = actionLabel(item, activeTab);
|
||||||
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType)
|
|
||||||
: eventActionLabel(item.sourceMsgSubType, item);
|
|
||||||
body.append(action);
|
body.append(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,6 +296,23 @@ function renderItem(item, activeTab, navigate) {
|
|||||||
return row;
|
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;
|
||||||
|
const action = row.querySelector('.notification-card__action');
|
||||||
|
if (action && activeTab !== 'replies') action.textContent = actionLabel(item, activeTab);
|
||||||
|
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 } = {}) {
|
export function render({ navigate, chrome } = {}) {
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack notifications-screen';
|
screen.className = 'stack notifications-screen';
|
||||||
@@ -289,10 +322,20 @@ export function render({ navigate, chrome } = {}) {
|
|||||||
tabs.setAttribute('role', 'radiogroup');
|
tabs.setAttribute('role', 'radiogroup');
|
||||||
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
tabs.setAttribute('aria-label', 'Категория уведомлений');
|
||||||
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
const tabDefs = [['replies','Ответы'],['connections','Связи'],['events','События']];
|
||||||
chrome?.setTopbar(createTopBar({
|
const topbar = createTopBar({
|
||||||
title: 'Уведомления',
|
title: 'Уведомления',
|
||||||
className: 'topbar--root notifications-topbar',
|
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);
|
screen.append(tabs);
|
||||||
|
|
||||||
const list = document.createElement('div');
|
const list = document.createElement('div');
|
||||||
@@ -314,6 +357,7 @@ export function render({ navigate, chrome } = {}) {
|
|||||||
function updateToolbarBadge(payload) {
|
function updateToolbarBadge(payload) {
|
||||||
const c = countsFromPayload(payload);
|
const c = countsFromPayload(payload);
|
||||||
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
state.notificationUnreadTotal = c.replies + c.connections + c.events;
|
||||||
|
if (readAllBtn) readAllBtn.disabled = state.notificationUnreadTotal <= 0;
|
||||||
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
const btn = document.querySelector('[data-toolbar-page="notifications-view"]');
|
||||||
if (!btn) return;
|
if (!btn) return;
|
||||||
let badge = btn.querySelector('.notification-toolbar-badge');
|
let badge = btn.querySelector('.notification-toolbar-badge');
|
||||||
@@ -363,32 +407,148 @@ export function render({ navigate, chrome } = {}) {
|
|||||||
}, 350);
|
}, 350);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let renderSeq = 0;
|
||||||
async function renderCurrent() {
|
async function renderCurrent() {
|
||||||
|
const seq = ++renderSeq;
|
||||||
observer?.disconnect(); observer=null; renderTabs(payloadCache || {});
|
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 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 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 unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
|
||||||
const nodes=[];
|
const nodes=[];
|
||||||
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
|
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}`));
|
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('Ранее'));
|
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){
|
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]});
|
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));
|
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() {
|
async function load() {
|
||||||
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
|
const seq=++requestSeq;
|
||||||
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
|
const login = state.session.login;
|
||||||
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 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';
|
if (!['replies','connections','events'].includes(state.notificationsTab)) state.notificationsTab='replies';
|
||||||
screen.cleanup = () => {
|
screen.cleanup = () => {
|
||||||
|
renderSeq += 1; // фоновая догрузка профилей больше не трогает экран
|
||||||
|
requestSeq += 1;
|
||||||
observer?.disconnect();
|
observer?.disconnect();
|
||||||
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
Object.values(pendingSeenTimers).forEach((timer) => clearTimeout(timer));
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import { profile } from '../mock-data.js';
|
import { profile } from '../mock-data.js';
|
||||||
import { authService, state } from '../state.js';
|
import { authService, state } from '../state.js';
|
||||||
import {
|
import {
|
||||||
@@ -34,10 +37,10 @@ function shineStatusLabel(value) {
|
|||||||
return 'Не указано';
|
return 'Не указано';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ошибка – понятным сообщением внизу экрана, а не окном со стеком вызовов
|
||||||
|
// (подробности остаются в журнале приложения).
|
||||||
function showLocalErrorAlert(prefix, error) {
|
function showLocalErrorAlert(prefix, error) {
|
||||||
const message = error?.message || 'Неизвестная ошибка';
|
showToast(`${prefix}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`, { kind: 'error' });
|
||||||
const stack = error?.stack ? `\n\nStack:\n${error.stack}` : '';
|
|
||||||
window.alert(`${prefix}: ${message}${stack}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function genderLabel(value) {
|
function genderLabel(value) {
|
||||||
@@ -241,7 +244,8 @@ export function render({ navigate, chrome }) {
|
|||||||
? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), sha256Hex: String(currentAvatar?.sha256Hex || '').trim().toLowerCase() }
|
? { ar: String(currentAvatar.txId || currentAvatar.ar || '').trim(), sha256Hex: String(currentAvatar?.sha256Hex || '').trim().toLowerCase() }
|
||||||
: null,
|
: null,
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'profile-avatar',
|
// Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана.
|
||||||
|
className: 'profile-avatar avatar-plain',
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,7 +297,7 @@ export function render({ navigate, chrome }) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false }) {
|
function openFieldEditModal({ label, value, placeholder = '', maxLength = 300, multiline = false, suggestions = null }) {
|
||||||
const root = document.getElementById('modal-root');
|
const root = document.getElementById('modal-root');
|
||||||
if (!root) return Promise.resolve(null);
|
if (!root) return Promise.resolve(null);
|
||||||
root.innerHTML = `
|
root.innerHTML = `
|
||||||
@@ -313,7 +317,8 @@ export function render({ navigate, chrome }) {
|
|||||||
maxlength="${Number(maxLength || 300)}"
|
maxlength="${Number(maxLength || 300)}"
|
||||||
placeholder="${escapeHtml(placeholder || `Введите ${label.toLowerCase()}`)}"
|
placeholder="${escapeHtml(placeholder || `Введите ${label.toLowerCase()}`)}"
|
||||||
value="${escapeHtml(String(value || ''))}"
|
value="${escapeHtml(String(value || ''))}"
|
||||||
/>`}
|
${suggestions?.length ? 'list="profile-field-edit-suggestions" autocomplete="off"' : ''}
|
||||||
|
/>${suggestions?.length ? `<datalist id="profile-field-edit-suggestions">${suggestions.map((item) => `<option value="${escapeHtml(item)}"></option>`).join('')}</datalist>` : ''}`}
|
||||||
<div class="meta-muted">До ${Number(maxLength || 300)} символов.</div>
|
<div class="meta-muted">До ${Number(maxLength || 300)} символов.</div>
|
||||||
<div class="form-actions-grid">
|
<div class="form-actions-grid">
|
||||||
<button class="secondary-btn" id="profile-field-edit-cancel" type="button">Отмена</button>
|
<button class="secondary-btn" id="profile-field-edit-cancel" type="button">Отмена</button>
|
||||||
@@ -626,8 +631,8 @@ export function render({ navigate, chrome }) {
|
|||||||
status.textContent = '';
|
status.textContent = '';
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось загрузить параметры: ${error.message || 'ошибка сети'}`;
|
status.textContent = actionErrorText('Не удалось загрузить параметры', error);
|
||||||
showLocalErrorAlert('Ошибка загрузки параметров профиля', error);
|
showLocalErrorAlert('Не удалось загрузить профиль', error);
|
||||||
} finally {
|
} finally {
|
||||||
reloadBtn.disabled = false;
|
reloadBtn.disabled = false;
|
||||||
accountRoleBtn.disabled = false;
|
accountRoleBtn.disabled = false;
|
||||||
@@ -663,7 +668,7 @@ export function render({ navigate, chrome }) {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = error?.message || 'Не удалось открыть мастер аватара.';
|
status.textContent = actionErrorText('Не удалось открыть мастер аватара', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -691,8 +696,9 @@ export function render({ navigate, chrome }) {
|
|||||||
await refreshProfileSnapshot();
|
await refreshProfileSnapshot();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось изменить ${statusKey}: ${error.message || 'ошибка сети'}`;
|
const what = isAccountRole ? 'тип аккаунта' : 'сияние';
|
||||||
showLocalErrorAlert(`Ошибка изменения ${statusKey}`, error);
|
status.textContent = `Не удалось изменить ${what}. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||||
|
showLocalErrorAlert(`Не удалось изменить ${what}`, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -706,10 +712,11 @@ export function render({ navigate, chrome }) {
|
|||||||
placeholder: field.placeholder || '',
|
placeholder: field.placeholder || '',
|
||||||
maxLength: field.maxLength || 300,
|
maxLength: field.maxLength || 300,
|
||||||
multiline: Boolean(field.multiline),
|
multiline: Boolean(field.multiline),
|
||||||
|
suggestions: field.suggestions,
|
||||||
});
|
});
|
||||||
if (entered === null) return;
|
if (entered === null) return;
|
||||||
if (String(entered).length > Number(field.maxLength || 300)) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -721,8 +728,8 @@ export function render({ navigate, chrome }) {
|
|||||||
await refreshProfileSnapshot();
|
await refreshProfileSnapshot();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось изменить ${field.key}: ${error.message || 'ошибка сети'}`;
|
status.textContent = `Не удалось изменить поле «${field.label}». ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||||
showLocalErrorAlert(`Ошибка изменения ${field.key}`, error);
|
showLocalErrorAlert(`Не удалось изменить поле «${field.label}»`, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -738,15 +745,15 @@ export function render({ navigate, chrome }) {
|
|||||||
await refreshProfileSnapshot();
|
await refreshProfileSnapshot();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось изменить пол: ${error.message || 'ошибка сети'}`;
|
status.textContent = `Не удалось изменить пол. ${toUserMessage(error, 'Попробуйте ещё раз.')}`;
|
||||||
showLocalErrorAlert('Ошибка изменения пола', error);
|
showLocalErrorAlert('Не удалось изменить пол', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onAddRelativeClick() {
|
async function onAddRelativeClick() {
|
||||||
const sessionLogin = String(login || '').trim();
|
const sessionLogin = String(login || '').trim();
|
||||||
if (!sessionLogin) {
|
if (!sessionLogin) {
|
||||||
window.alert('Для добавления связи нужен активный логин.');
|
showToast('Для добавления связи нужен вход в аккаунт.', { kind: 'error' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -785,17 +792,19 @@ export function render({ navigate, chrome }) {
|
|||||||
targetCard = await loadUserProfileCard(inputLogin);
|
targetCard = await loadUserProfileCard(inputLogin);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Пользователь не найден: ${error.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось найти пользователя', error);
|
||||||
showLocalErrorAlert('Ошибка выбора пользователя', error);
|
showLocalErrorAlert('Не удалось выбрать пользователя', error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetLogin = String(targetCard?.login || inputLogin).trim();
|
const targetLogin = String(targetCard?.login || inputLogin).trim();
|
||||||
const targetGender = normalizeGender(targetCard?.gender || PROFILE_GENDER_UNKNOWN);
|
const targetGender = normalizeGender(targetCard?.gender || PROFILE_GENDER_UNKNOWN);
|
||||||
const relationLabel = relationAccusativeLabel(relationType, targetGender);
|
const relationLabel = relationAccusativeLabel(relationType, targetGender);
|
||||||
const confirmed = window.confirm(
|
const confirmed = await confirmDialog({
|
||||||
`Добавить пользователя ${targetLogin} как ${relationLabel}?`,
|
title: 'Добавить связь?',
|
||||||
);
|
text: `Добавить ${targetLogin} как ${relationLabel}?`,
|
||||||
|
confirmLabel: 'Добавить',
|
||||||
|
});
|
||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
|
|
||||||
status.className = 'status-line';
|
status.className = 'status-line';
|
||||||
@@ -816,8 +825,8 @@ export function render({ navigate, chrome }) {
|
|||||||
status.textContent = `Связь добавлена: ${targetLogin} как ${relationLabel}.`;
|
status.textContent = `Связь добавлена: ${targetLogin} как ${relationLabel}.`;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось добавить связь: ${error.message || 'ошибка сети'}`;
|
status.textContent = actionErrorText('Не удалось добавить связь', error);
|
||||||
showLocalErrorAlert('Ошибка добавления связи', error);
|
showLocalErrorAlert('Не удалось добавить связь', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,30 +4,47 @@ import { renderUserAvatar } from '../components/avatar-image.js';
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.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: 'Профиль' };
|
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
||||||
|
|
||||||
|
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
||||||
|
const cardCache = new Map();
|
||||||
|
|
||||||
export function render({ navigate, chrome }) {
|
export function render({ navigate, chrome }) {
|
||||||
const login = String(state.session.login || profile.login || '').trim();
|
const login = String(state.session.login || profile.login || '').trim();
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack user-profile-screen';
|
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({
|
const topbar = createTopBar({
|
||||||
title: 'Профиль',
|
title: 'Профиль',
|
||||||
className: 'topbar--root user-profile-header',
|
className: 'topbar--root user-profile-header',
|
||||||
|
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
|
||||||
});
|
});
|
||||||
chrome?.setTopbar(topbar);
|
chrome?.setTopbar(topbar);
|
||||||
|
|
||||||
const status = document.createElement('div');
|
const status = document.createElement('div');
|
||||||
status.className = 'status-line user-profile-status';
|
status.className = 'user-profile-status';
|
||||||
status.textContent = 'Загрузка профиля...';
|
let card = cardCache.get(login.toLowerCase()) || null;
|
||||||
|
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
||||||
|
if (!card) status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||||
|
|
||||||
const body = document.createElement('div');
|
const body = document.createElement('div');
|
||||||
body.className = 'user-profile-body';
|
body.className = 'user-profile-body';
|
||||||
screen.append(status, body);
|
screen.append(status, body);
|
||||||
|
|
||||||
let card = null;
|
|
||||||
|
|
||||||
function renderProfile() {
|
function renderProfile() {
|
||||||
if (!card) return;
|
if (!card) return;
|
||||||
body.innerHTML = profileCardHtml({
|
body.innerHTML = profileCardHtml({
|
||||||
@@ -51,9 +68,10 @@ export function render({ navigate, chrome }) {
|
|||||||
avatar: card.avatar,
|
avatar: card.avatar,
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'user-profile-hero-avatar',
|
className: 'user-profile-hero-avatar',
|
||||||
|
official: card.accountRole === 'primary',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
status.textContent = '';
|
status.replaceChildren();
|
||||||
}
|
}
|
||||||
|
|
||||||
body.addEventListener('click', (event) => {
|
body.addEventListener('click', (event) => {
|
||||||
@@ -83,14 +101,29 @@ export function render({ navigate, chrome }) {
|
|||||||
status.textContent = 'Локальный тестовый режим.';
|
status.textContent = 'Локальный тестовый режим.';
|
||||||
return;
|
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();
|
renderProfile();
|
||||||
}
|
}
|
||||||
|
|
||||||
refresh().catch((error) => {
|
renderProfile();
|
||||||
status.className = 'status-line user-profile-status is-unavailable';
|
|
||||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
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;
|
return screen;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
prepareAddProfileLogin,
|
prepareAddProfileLogin,
|
||||||
switchToSavedProfile,
|
switchToSavedProfile,
|
||||||
} from '../state.js';
|
} from '../state.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'profiles-view', title: 'Профили' };
|
export const pageMeta = { id: 'profiles-view', title: 'Профили' };
|
||||||
|
|
||||||
@@ -51,7 +52,7 @@ export function render({navigate, chrome}) {
|
|||||||
navigate('login-view');
|
navigate('login-view');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось начать добавление профиля: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось начать добавление профиля', error);
|
||||||
addButton.disabled = false;
|
addButton.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -73,7 +74,7 @@ export function render({navigate, chrome}) {
|
|||||||
reloadTo('/start');
|
reloadTo('/start');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось закрыть профили: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось закрыть профили', error);
|
||||||
closeAllButton.disabled = false;
|
closeAllButton.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -109,7 +110,7 @@ export function render({navigate, chrome}) {
|
|||||||
reloadTo('/profile');
|
reloadTo('/profile');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось переключить профиль: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось переключить профиль', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -141,7 +142,7 @@ export function render({navigate, chrome}) {
|
|||||||
renderList();
|
renderList();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line is-unavailable';
|
status.className = 'status-line is-unavailable';
|
||||||
status.textContent = `Не удалось закрыть профиль: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось закрыть профиль', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ export const REGISTRATION_FAQ_TOPICS = [
|
|||||||
'Ключ восстановления (Recovery key) нужен для восстановления и самых критичных операций с учётной записью. Его приватная часть никогда не сохраняется на устройстве и при необходимости временно вычисляется из пароля.',
|
'Ключ восстановления (Recovery key) нужен для восстановления и самых критичных операций с учётной записью. Его приватная часть никогда не сохраняется на устройстве и при необходимости временно вычисляется из пароля.',
|
||||||
'Ключ блокчейна постоянно хранится на авторизованном устройстве. Он подписывает записи и действия в блокчейне Сияния и является исходным ключом для штатных пользовательских кошельков.',
|
'Ключ блокчейна постоянно хранится на авторизованном устройстве. Он подписывает записи и действия в блокчейне Сияния и является исходным ключом для штатных пользовательских кошельков.',
|
||||||
'Ключ доступа (client key) также постоянно хранится на устройстве. Он используется для входа на сервер, работы устройства и защищённых личных сообщений.',
|
'Ключ доступа (client key) также постоянно хранится на устройстве. Он используется для входа на сервер, работы устройства и защищённых личных сообщений.',
|
||||||
'Сейчас после обычного входа оба рабочих ключа — ключ блокчейна и ключ доступа — сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
'Сейчас после обычного входа оба рабочих ключа – ключ блокчейна и ключ доступа – сохраняются автоматически. Отдельного ограниченного режима в текущей версии нет.',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -29,8 +29,8 @@ import { defaultServerLogin } from '../deploy-config.js';
|
|||||||
|
|
||||||
export const pageMeta = { id: 'registration-payment-view', title: 'Оплата регистрации', showAppChrome: false };
|
export const pageMeta = { id: 'registration-payment-view', title: 'Оплата регистрации', showAppChrome: false };
|
||||||
const MIN_REQUIRED_SOL = 0.01;
|
const MIN_REQUIRED_SOL = 0.01;
|
||||||
const RECOMMENDED_TOPUP_SOL = 0.2;
|
const RECOMMENDED_TOPUP_SOL = 0.02;
|
||||||
const TEST_TOPUP_AMOUNT_SOL = 0.2;
|
const TEST_TOPUP_AMOUNT_SOL = 0.02;
|
||||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import {
|
import {
|
||||||
isSessionInvalidError,
|
isSessionInvalidError,
|
||||||
refreshSessions,
|
refreshSessions,
|
||||||
@@ -35,7 +37,7 @@ export function render({navigate, chrome}) {
|
|||||||
|
|
||||||
chrome?.setTopbar(createTopBar({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: 'AddBlock через homeserver',
|
title: 'AddBlock через homeserver',
|
||||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
back: { label: '←', onClick: () => navigate('my-blockchain-view') },
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const actions = document.createElement('div');
|
const actions = document.createElement('div');
|
||||||
@@ -95,7 +97,7 @@ export function render({navigate, chrome}) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
setAuthError(error.message);
|
||||||
window.alert(error.message);
|
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
listCard.append(item);
|
listCard.append(item);
|
||||||
@@ -115,7 +117,7 @@ export function render({navigate, chrome}) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
setAuthError(error.message);
|
||||||
window.alert(error.message);
|
showToast(toUserMessage(error, 'Действие не выполнено. Попробуйте ещё раз.'), { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -135,7 +137,7 @@ export function render({navigate, chrome}) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setAuthError(error.message);
|
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 { 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 { saveEntrySettings, state } from '../state.js';
|
||||||
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '../services/server-health-service.js';
|
||||||
|
|
||||||
@@ -163,7 +165,7 @@ export function render({navigate, chrome}) {
|
|||||||
cancelButton.className = 'ghost-btn';
|
cancelButton.className = 'ghost-btn';
|
||||||
cancelButton.type = 'button';
|
cancelButton.type = 'button';
|
||||||
cancelButton.textContent = 'Отмена';
|
cancelButton.textContent = 'Отмена';
|
||||||
cancelButton.addEventListener('click', () => navigate('settings-view'));
|
cancelButton.addEventListener('click', () => navigate('settings-servers-view'));
|
||||||
|
|
||||||
const saveButton = document.createElement('button');
|
const saveButton = document.createElement('button');
|
||||||
saveButton.className = 'primary-btn';
|
saveButton.className = 'primary-btn';
|
||||||
@@ -172,9 +174,9 @@ export function render({navigate, chrome}) {
|
|||||||
saveButton.addEventListener('click', async () => {
|
saveButton.addEventListener('click', async () => {
|
||||||
try {
|
try {
|
||||||
await saveEntrySettings(draft);
|
await saveEntrySettings(draft);
|
||||||
navigate('settings-view');
|
navigate('settings-servers-view');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
window.alert(error?.message || 'Не удалось сохранить настройки серверов блокчейнов.');
|
showToast(toUserMessage(error, 'Не удалось сохранить настройки серверов блокчейнов.'), { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -192,7 +194,7 @@ export function render({navigate, chrome}) {
|
|||||||
|
|
||||||
chrome?.setTopbar(createTopBar({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: 'Серверы блокчейнов',
|
title: 'Серверы блокчейнов',
|
||||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
back: { label: '←', onClick: () => navigate('settings-servers-view') },
|
||||||
}));
|
}));
|
||||||
screen.append(
|
screen.append(
|
||||||
introCard,
|
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;
|
||||||
|
}
|
||||||
+132
-106
@@ -1,38 +1,102 @@
|
|||||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
import { addAppLogEntry, authService, closeSavedProfile, state } from '../state.js';
|
||||||
import { isDeveloperToolsEnabled } from '../services/feature-settings.js';
|
import { openSheet } from '../components/sheet.js';
|
||||||
import { getThemeMode, resolveThemeMode, setThemeMode } from '../services/theme-service.js';
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import { openPaletteEditor } from '../components/palette-editor.js';
|
import { PALETTE_PRESETS, getPaletteSettings, getThemeMode } from '../services/theme-service.js';
|
||||||
|
import {
|
||||||
|
canInstallPwa,
|
||||||
|
isStandalonePwaMode,
|
||||||
|
onPwaInstallAvailabilityChange,
|
||||||
|
promptPwaInstall,
|
||||||
|
} from '../services/pwa-install-service.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
export const pageMeta = { id: 'settings-view', title: 'Настройки' };
|
||||||
|
|
||||||
|
// Номер сборки вида 20261013040000 – это дата и время: показываем «13.10.2026, 04:00».
|
||||||
function formatBuildStamp(rawValue) {
|
function formatBuildStamp(rawValue) {
|
||||||
const value = String(rawValue || '').trim();
|
const value = String(rawValue || '').trim();
|
||||||
if (!/^\d{14}$/.test(value)) return value;
|
if (!/^\d{14}$/.test(value)) return value;
|
||||||
const yyyy = value.slice(0, 4);
|
return `${value.slice(6, 8)}.${value.slice(4, 6)}.${value.slice(0, 4)}, ${value.slice(8, 10)}:${value.slice(10, 12)}`;
|
||||||
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}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatVersionForUi(rawValue) {
|
function formatVersionForUi(rawValue) {
|
||||||
const value = String(rawValue || '').trim();
|
const value = String(rawValue || '').trim();
|
||||||
if (!value) return 'n/a';
|
if (!value) return 'n/a';
|
||||||
const formatted = formatBuildStamp(value);
|
const formatted = formatBuildStamp(value);
|
||||||
if (formatted && formatted !== value) {
|
if (formatted && formatted !== value) return formatted;
|
||||||
return `${formatted} (${value})`;
|
|
||||||
}
|
|
||||||
return value;
|
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}) {
|
export function render({navigate, chrome}) {
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack';
|
screen.className = 'stack';
|
||||||
let isDisposed = false;
|
let isDisposed = false;
|
||||||
|
let aboutSheet = null;
|
||||||
|
|
||||||
const topbar = createTopBar({
|
const topbar = createTopBar({
|
||||||
title: 'Настройки',
|
title: 'Настройки',
|
||||||
@@ -55,61 +119,74 @@ export function render({navigate, chrome}) {
|
|||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'stack settings-sections';
|
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 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 = `
|
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>
|
|
||||||
<div class="nav-list">
|
<div class="nav-list">
|
||||||
${row('settings-device', 'Устройства', 'Сеансы, подключение устройств, ключи')}
|
${row('settings-appearance', 'Оформление', appearanceHint)}
|
||||||
${row('settings-my-blockchain', 'Мой блокчейн', 'Все ваши подписанные события и смена ключей')}
|
${row('settings-notifications', 'Уведомления', 'Звук, разрешение, чаты без звука')}
|
||||||
${row('settings-access-servers', 'Сервер доступа', 'Личная переписка, звонки и зашифрованные данные')}
|
|
||||||
${row('settings-blockchain-servers', 'Серверы блокчейнов', 'Solana, Сияние и Arweave для публичных данных')}
|
|
||||||
${row('settings-arweave-uploads', 'Файлы в блокчейне', 'Заранее загрузить файл и выбрать его потом')}
|
|
||||||
${row('settings-remote-addblock', 'Публикация через домашний сервер', 'Когда ключа публикаций нет на этом устройстве')}
|
|
||||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||||
</div>
|
</div>
|
||||||
<div class="nav-list">
|
<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-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">
|
||||||
|
${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>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const themeSwitch = card.querySelector('#settings-theme');
|
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||||
const syncThemeSwitch = () => {
|
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||||
const mode = getThemeMode();
|
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||||
themeSwitch.querySelectorAll('[data-mode]').forEach((btn) => {
|
aboutSheet?.close();
|
||||||
btn.setAttribute('aria-checked', String(btn.dataset.mode === mode));
|
aboutSheet = openAboutSheet();
|
||||||
});
|
|
||||||
};
|
|
||||||
syncThemeSwitch();
|
|
||||||
|
|
||||||
themeSwitch.addEventListener('click', (event) => {
|
|
||||||
const mode = event.target.closest('[data-mode]')?.dataset.mode;
|
|
||||||
if (!mode) return;
|
|
||||||
setThemeMode(mode);
|
|
||||||
syncThemeSwitch();
|
|
||||||
});
|
});
|
||||||
card.querySelector('#settings-theme-editor').addEventListener('click', () => {
|
|
||||||
openPaletteEditor({ theme: resolveThemeMode() });
|
|
||||||
});
|
|
||||||
|
|
||||||
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
card.querySelector('#settings-device').addEventListener('click', () => navigate('device-view'));
|
||||||
card.querySelector('#settings-my-blockchain').addEventListener('click', () => navigate('my-blockchain-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-servers').addEventListener('click', () => navigate('settings-servers-view'));
|
||||||
card.querySelector('#settings-access-servers').addEventListener('click', () => navigate('access-servers-view'));
|
card.querySelector('#settings-access-keys').addEventListener('click', () => navigate('access-keys-view'));
|
||||||
card.querySelector('#settings-blockchain-servers').addEventListener('click', () => navigate('server-settings-view'));
|
card.querySelector('#settings-developer').addEventListener('click', () => navigate('developer-settings-view'));
|
||||||
card.querySelector('#settings-arweave-uploads').addEventListener('click', () => navigate('arweave-uploads-view'));
|
|
||||||
card.querySelector('#settings-language').addEventListener('click', () => {
|
card.querySelector('#settings-language').addEventListener('click', () => {
|
||||||
sessionStorage.setItem('shine-language-return-page', 'settings-view');
|
sessionStorage.setItem('shine-language-return-page', 'settings-view');
|
||||||
navigate('language-view');
|
navigate('language-view');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const installList = card.querySelector('#settings-install-list');
|
||||||
|
const syncInstallAction = () => {
|
||||||
|
const available = !isStandalonePwaMode() && canInstallPwa();
|
||||||
|
installList.hidden = !available;
|
||||||
|
if (!available) {
|
||||||
|
installList.replaceChildren();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (installList.querySelector('#settings-install-pwa')) return;
|
||||||
|
|
||||||
|
installList.innerHTML = row(
|
||||||
|
'settings-install-pwa',
|
||||||
|
'Установить приложение',
|
||||||
|
'Открывать Сияние как отдельное приложение',
|
||||||
|
);
|
||||||
|
installList.querySelector('#settings-install-pwa')?.addEventListener('click', async (event) => {
|
||||||
|
const button = event.currentTarget;
|
||||||
|
button.disabled = true;
|
||||||
|
try {
|
||||||
|
await promptPwaInstall();
|
||||||
|
} finally {
|
||||||
|
syncInstallAction();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const unsubscribeInstallAvailability = onPwaInstallAvailabilityChange(syncInstallAction);
|
||||||
|
syncInstallAction();
|
||||||
|
|
||||||
const signOutBtn = card.querySelector('#settings-signout');
|
const signOutBtn = card.querySelector('#settings-signout');
|
||||||
signOutBtn.addEventListener('click', async () => {
|
signOutBtn.addEventListener('click', async () => {
|
||||||
const confirmed = await confirmDialog({
|
const confirmed = await confirmDialog({
|
||||||
@@ -136,62 +213,11 @@ export function render({navigate, chrome}) {
|
|||||||
|
|
||||||
screen.append(card);
|
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 = () => {
|
screen.cleanup = () => {
|
||||||
|
if (isDisposed) return;
|
||||||
isDisposed = true;
|
isDisposed = true;
|
||||||
|
aboutSheet?.close();
|
||||||
|
unsubscribeInstallAvailability();
|
||||||
};
|
};
|
||||||
return screen;
|
return screen;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { createLoadingState } from '../components/feedback.js';
|
||||||
import { iconHtml } from '../components/ui-icon.js';
|
import { iconHtml } from '../components/ui-icon.js';
|
||||||
import { state } from '../state.js';
|
import { state } from '../state.js';
|
||||||
import { bytesToBase58 } from '../services/crypto-utils.js';
|
import { bytesToBase58 } from '../services/crypto-utils.js';
|
||||||
@@ -16,12 +17,12 @@ export function render({navigate, chrome}) {
|
|||||||
|
|
||||||
chrome?.setTopbar(createTopBar({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: 'Ключи этого устройства',
|
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.className = 'meta-muted';
|
||||||
status.textContent = 'Загружаем сохранённые ключи...';
|
status.append(createLoadingState({ label: 'Загружаю ключи' }));
|
||||||
|
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'nav-list key-list';
|
card.className = 'nav-list key-list';
|
||||||
|
|||||||
@@ -23,19 +23,14 @@ export function render({ navigate }) {
|
|||||||
logoWrap.append(logo);
|
logoWrap.append(logo);
|
||||||
|
|
||||||
const brandBlock = document.createElement('div');
|
const brandBlock = document.createElement('div');
|
||||||
brandBlock.className = 'stack';
|
brandBlock.className = 'stack auth-brand-block';
|
||||||
brandBlock.style.alignItems = 'center';
|
|
||||||
brandBlock.style.gap = '8px';
|
|
||||||
|
|
||||||
const title = document.createElement('h1');
|
const title = document.createElement('h1');
|
||||||
title.className = 'auth-brand';
|
title.className = 'auth-brand';
|
||||||
title.append(createShineWordmark());
|
title.append(createShineWordmark());
|
||||||
|
|
||||||
const siteName = document.createElement('p');
|
const siteName = document.createElement('p');
|
||||||
siteName.className = 'meta-muted';
|
siteName.className = 'meta-muted auth-site-name';
|
||||||
siteName.style.margin = '0';
|
|
||||||
siteName.style.fontSize = '13px';
|
|
||||||
siteName.style.letterSpacing = '0.04em';
|
|
||||||
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
|
||||||
|
|
||||||
brandBlock.append(title, siteName);
|
brandBlock.append(title, siteName);
|
||||||
@@ -72,5 +67,23 @@ export function render({ navigate }) {
|
|||||||
|
|
||||||
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
actions.append(loginButton, registerButton, languageButton, settingsButton);
|
||||||
screen.append(logoWrap, brandBlock, actions);
|
screen.append(logoWrap, brandBlock, actions);
|
||||||
|
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
|
||||||
|
queueMicrotask(() => continueSplashAnimations(logoWrap));
|
||||||
return screen;
|
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 { createTopBar } from '../components/topbar.js';
|
||||||
|
import { showToast } from '../services/channels-ux.js';
|
||||||
import { state } from '../state.js';
|
import { state } from '../state.js';
|
||||||
import {
|
import {
|
||||||
createSolanaWalletFromPrivateBase58,
|
createSolanaWalletFromPrivateBase58,
|
||||||
@@ -8,11 +9,12 @@ import {
|
|||||||
transferSol,
|
transferSol,
|
||||||
} from '../services/solana-wallet-service.js';
|
} from '../services/solana-wallet-service.js';
|
||||||
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
||||||
|
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'topup-view', title: 'Пополнение solana счета', showAppChrome: false };
|
export const pageMeta = { id: 'topup-view', title: 'Пополнение solana счета', showAppChrome: false };
|
||||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||||
const SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
const SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||||
const REGISTRATION_TOPUP_AMOUNT_SOL = 0.2;
|
const REGISTRATION_TOPUP_AMOUNT_SOL = 0.02;
|
||||||
|
|
||||||
// Канонический Solana-кошелёк пользователя = текущий blockchain key.
|
// Канонический Solana-кошелёк пользователя = текущий blockchain key.
|
||||||
// Тот же адрес используется как fee payer для регистрации и обычных PDA update.
|
// Тот же адрес используется как fee payer для регистрации и обычных PDA update.
|
||||||
@@ -59,7 +61,7 @@ export function render({ navigate }) {
|
|||||||
copyButton.textContent = 'Скопировать';
|
copyButton.textContent = 'Скопировать';
|
||||||
}, 1500);
|
}, 1500);
|
||||||
} catch {
|
} catch {
|
||||||
window.alert('Не удалось скопировать номер кошелька.');
|
showToast('Не удалось скопировать номер кошелька – выделите его и скопируйте вручную.', { kind: 'error' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -88,7 +90,7 @@ export function render({ navigate }) {
|
|||||||
testButton.addEventListener('click', async () => {
|
testButton.addEventListener('click', async () => {
|
||||||
const address = String(walletValue.value || '').trim();
|
const address = String(walletValue.value || '').trim();
|
||||||
if (!address) {
|
if (!address) {
|
||||||
window.alert('Адрес кошелька не найден.');
|
showToast('Адрес кошелька не найден.', { kind: 'error' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!senderKeypair) {
|
if (!senderKeypair) {
|
||||||
@@ -118,7 +120,7 @@ export function render({ navigate }) {
|
|||||||
].join('\n');
|
].join('\n');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.style.fontSize = '13px';
|
status.style.fontSize = '13px';
|
||||||
status.textContent = `Ошибка тестового пополнения: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Ошибка тестового пополнения', error);
|
||||||
} finally {
|
} finally {
|
||||||
testButton.disabled = false;
|
testButton.disabled = false;
|
||||||
}
|
}
|
||||||
@@ -155,7 +157,7 @@ export function render({ navigate }) {
|
|||||||
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
const sender = await createSolanaWalletFromPrivateBase58(SENDER_PRIVATE_32_BASE58);
|
||||||
senderKeypair = sender.keypair;
|
senderKeypair = sender.keypair;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.textContent = `Не удалось получить баланс: ${error?.message || 'unknown'}`;
|
status.textContent = actionErrorText('Не удалось получить баланс', error);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// UNUSED FOR NOW: настройка дополнительного пароля для подключения другого устройства
|
// UNUSED FOR NOW: настройка дополнительного пароля для подключения другого устройства
|
||||||
// сохранена в коде, но не показывается в активном UI. Текущий UX всегда без пароля.
|
// сохранена в коде, но не показывается в активном UI. Текущий UX всегда без пароля.
|
||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { createLoadingState } from '../components/feedback.js';
|
||||||
import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
import { authService, setAuthError, setAuthInfo, state } from '../state.js';
|
||||||
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
import { deriveEspPairingPasswordHash } from '../services/device-pairing-service.js';
|
||||||
import { toUserMessage } from '../services/ui-error-texts.js';
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
@@ -27,9 +28,9 @@ export function render({navigate, chrome}) {
|
|||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'card stack';
|
card.className = 'card stack';
|
||||||
|
|
||||||
const summary = document.createElement('p');
|
const summary = document.createElement('div');
|
||||||
summary.className = 'auth-copy';
|
summary.className = 'auth-copy';
|
||||||
summary.textContent = 'Загружаем текущие настройки...';
|
summary.append(createLoadingState({ label: 'Загружаю настройки' }));
|
||||||
|
|
||||||
const hint = document.createElement('p');
|
const hint = document.createElement('p');
|
||||||
hint.className = 'meta-muted';
|
hint.className = 'meta-muted';
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
import { renderUserAvatar } from '../components/avatar-image.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 { authService } from '../state.js';
|
||||||
import { navigateBack } from '../router.js';
|
import { navigateBack } from '../router.js';
|
||||||
import { userDisplayName } from '../services/user-display.js';
|
import { userDisplayName } from '../services/user-display.js';
|
||||||
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
||||||
|
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||||
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
import { avatarReferenceToRenderModel, parseAvatarReference } from '../services/avatar-reference.js';
|
||||||
|
|
||||||
export const pageMeta = { id: 'user-profile-list-view', title: 'Список' };
|
export const pageMeta = { id: 'user-profile-list-view', title: 'Список' };
|
||||||
@@ -17,12 +22,22 @@ const TITLES = {
|
|||||||
channels_owned: 'Каналы', channels_following: 'Подписки на каналы',
|
channels_owned: 'Каналы', channels_following: 'Подписки на каналы',
|
||||||
};
|
};
|
||||||
|
|
||||||
function friendTabsHtml(activeKind) {
|
const EMPTY_TEXT = {
|
||||||
return `
|
friends: 'Друзей пока нет.',
|
||||||
<div class="profile-list-tabs" role="tablist" aria-label="Тип друзей">
|
close_friends: 'Близких друзей пока нет.',
|
||||||
<button type="button" class="profile-list-tab${activeKind === 'friends' ? ' is-active' : ''}" data-friend-kind="friends" role="tab" aria-selected="${activeKind === 'friends'}">Друзья</button>
|
primary_received: 'Пока никто не подтвердил.',
|
||||||
<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>
|
primary_given: 'Пока никого не подтвердили.',
|
||||||
</div>`;
|
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 }) {
|
export function render({ navigate, route, chrome }) {
|
||||||
@@ -32,124 +47,158 @@ export function render({ navigate, route, chrome }) {
|
|||||||
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
||||||
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
||||||
let includeDeleted = false;
|
let includeDeleted = false;
|
||||||
|
let disposed = false;
|
||||||
|
let rows = [];
|
||||||
|
let query = '';
|
||||||
|
|
||||||
const screen = document.createElement('section');
|
const screen = document.createElement('section');
|
||||||
screen.className = 'stack';
|
screen.className = 'stack profile-list-screen';
|
||||||
const body = document.createElement('div');
|
const body = document.createElement('div');
|
||||||
body.className = 'stack';
|
body.className = 'profile-list-body';
|
||||||
const status = document.createElement('div');
|
|
||||||
status.className = 'status-line';
|
|
||||||
status.textContent = 'Загрузка...';
|
|
||||||
|
|
||||||
chrome?.setTopbar(createTopBar({
|
chrome?.setTopbar(createTopBar({
|
||||||
title: TITLES[initialKind] || 'Список',
|
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) {
|
if (isFriendsScreen) {
|
||||||
const tabs = document.createElement('div');
|
const tabs = document.createElement('div');
|
||||||
tabs.innerHTML = friendTabsHtml(activeKind);
|
tabs.className = 'tabs profile-list-kind';
|
||||||
screen.append(tabs.firstElementChild);
|
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;
|
let loadGeneration = 0;
|
||||||
|
|
||||||
function renderRelationRows(rows) {
|
function relationRow(row) {
|
||||||
rows.forEach((row) => {
|
const marks = [
|
||||||
const el = document.createElement('button');
|
RELATION_TEXT[row.relationType] || '',
|
||||||
el.type = 'button';
|
row.shineStatus === 'shining' ? 'сияющий' : '',
|
||||||
el.className = 'ui-button card row profile-list-row';
|
row.accountRole === 'primary' ? 'официальный' : '',
|
||||||
el.append(renderUserAvatar({
|
row.primaryConfirmed ? 'официальный подтверждён' : '',
|
||||||
login: row.login,
|
row.shineConfirmed ? 'сияние подтверждено' : '',
|
||||||
firstName: row.firstName,
|
].filter(Boolean);
|
||||||
lastName: row.lastName,
|
const name = userDisplayName(row);
|
||||||
avatar: parseAvatar(row.avatarAr),
|
const sub = [name !== row.login ? `@${row.login}` : '', ...marks].filter(Boolean).join(' · ');
|
||||||
size: 'md',
|
return createPersonRow({
|
||||||
}));
|
login: row.login,
|
||||||
const fullName = userDisplayName(row);
|
name,
|
||||||
const t = document.createElement('div');
|
firstName: row.firstName,
|
||||||
t.className = 'profile-list-row-text';
|
lastName: row.lastName,
|
||||||
const marks = [
|
avatar: parseAvatar(row.avatarAr),
|
||||||
row.relationType && row.relationType !== 'none' ? ({ contact: 'контакт', friend: 'друг', close_friend: 'близкий друг' }[row.relationType] || row.relationType) : '',
|
official: row.accountRole === 'primary',
|
||||||
row.accountRole === 'primary' ? 'основной' : row.accountRole === 'non_voting' ? 'голос не учитывается' : '',
|
ring: row.shineStatus === 'shining' ? 'shining' : (row.relationType === 'close_friend' ? 'close' : ''),
|
||||||
row.shineStatus === 'shining' ? 'сияющий' : row.shineStatus === 'not_interested' ? 'сияние неинтересно' : '',
|
sub,
|
||||||
row.primaryConfirmed ? 'основной подтверждён ✓' : '',
|
onClick: () => navigate(`SHiNE/${encodeURIComponent(row.login)}`),
|
||||||
row.shineConfirmed ? 'сияющий подтверждён ✓' : '',
|
actions: [{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(row.login)}`) }],
|
||||||
].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 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) => (isChannelsScreen
|
||||||
|
? !query || searchText(`${row.displayName} ${row.slug} ${row.ownerLogin}`).includes(query)
|
||||||
|
: matchesPeopleQuery(`${userDisplayName(row)} ${row.login}`, 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) {
|
async function load(kind) {
|
||||||
const generation = ++loadGeneration;
|
const generation = ++loadGeneration;
|
||||||
status.className = 'status-line';
|
body.replaceChildren(createLoadingState({ label: 'Загружаю список' }));
|
||||||
status.textContent = 'Загрузка...';
|
|
||||||
body.replaceChildren();
|
|
||||||
try {
|
try {
|
||||||
if (kind === 'channels_owned' || kind === 'channels_following') {
|
const payload = isChannelsScreen
|
||||||
const payload = await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted);
|
? await authService.listUserProfileChannels(login, kind === 'channels_owned' ? 'owned' : 'following', 200, 0, includeDeleted)
|
||||||
if (generation !== loadGeneration) return;
|
: await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||||
const rows = Array.isArray(payload?.channels) ? payload.channels : [];
|
if (disposed || generation !== loadGeneration) return;
|
||||||
rows.forEach((row) => {
|
rows = Array.isArray(isChannelsScreen ? payload?.channels : payload?.users) ? (isChannelsScreen ? payload.channels : payload.users) : [];
|
||||||
const el = document.createElement('button');
|
searchWrap.hidden = rows.length < SEARCH_FROM;
|
||||||
el.type = 'button';
|
renderRows();
|
||||||
el.className = 'ui-button card row profile-list-row';
|
} catch (error) {
|
||||||
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' }));
|
if (disposed || generation !== loadGeneration) return;
|
||||||
const t = document.createElement('div');
|
body.replaceChildren(createErrorState({
|
||||||
t.className = 'profile-list-row-text';
|
title: 'Не удалось загрузить список',
|
||||||
t.innerHTML = `<b>${String(row.displayName || row.slug || '')}${row.deleted ? ' · Удалён' : ''}</b><small>${String(row.ownerLogin || '')} / ${String(row.slug || '')}</small>`;
|
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||||
el.append(t);
|
onRetry: () => { void load(activeKind); },
|
||||||
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'}`;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isChannelsScreen) {
|
screen.cleanup = () => {
|
||||||
screen.querySelector('#profile-list-show-deleted')?.addEventListener('change', (event) => {
|
disposed = true;
|
||||||
includeDeleted = !!event.currentTarget.checked;
|
loadGeneration += 1;
|
||||||
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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void load(activeKind);
|
void load(activeKind);
|
||||||
return screen;
|
return screen;
|
||||||
|
|||||||
@@ -2,10 +2,15 @@ import { createTopBar } from '../components/topbar.js';
|
|||||||
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
||||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||||
import { state } from '../state.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 { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||||
import { navigateBack } from '../router.js';
|
import { navigateBack } from '../router.js';
|
||||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.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: 'Профиль' };
|
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||||||
|
|
||||||
@@ -32,17 +37,28 @@ export function render({ navigate, route, chrome }) {
|
|||||||
chrome?.setTopbar(header);
|
chrome?.setTopbar(header);
|
||||||
|
|
||||||
const status = document.createElement('div');
|
const status = document.createElement('div');
|
||||||
status.className = 'status-line user-profile-status';
|
status.className = 'user-profile-status';
|
||||||
status.textContent = 'Загрузка профиля...';
|
status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||||||
|
|
||||||
const body = document.createElement('div');
|
const body = document.createElement('div');
|
||||||
body.className = 'user-profile-body';
|
body.className = 'user-profile-body';
|
||||||
screen.append(status, body);
|
screen.append(status, body);
|
||||||
|
|
||||||
let card = null;
|
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() {
|
function renderProfile() {
|
||||||
if (!card) return;
|
if (!card || disposed) return;
|
||||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||||
|
const note = isSelf ? null : getPersonNote(card.login);
|
||||||
|
|
||||||
body.innerHTML = profileCardHtml({
|
body.innerHTML = profileCardHtml({
|
||||||
card,
|
card,
|
||||||
@@ -55,6 +71,20 @@ export function render({ navigate, route, chrome }) {
|
|||||||
].join(''),
|
].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');
|
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||||
avatarSlot?.append(renderUserAvatar({
|
avatarSlot?.append(renderUserAvatar({
|
||||||
login: card.login,
|
login: card.login,
|
||||||
@@ -63,9 +93,41 @@ export function render({ navigate, route, chrome }) {
|
|||||||
avatar: card.avatar,
|
avatar: card.avatar,
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
className: 'user-profile-hero-avatar',
|
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 = `${card.gender === 'female' ? 'добавила' : card.gender === 'male' ? 'добавил' : 'добавил(а)'} вас в контакты`;
|
||||||
|
}
|
||||||
|
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) => {
|
body.addEventListener('click', (event) => {
|
||||||
@@ -92,15 +154,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() {
|
async function refresh() {
|
||||||
card = await loadUserProfileCard(requestedLogin);
|
const loaded = await loadUserProfileCard(requestedLogin);
|
||||||
|
if (disposed) return;
|
||||||
|
card = loaded;
|
||||||
renderProfile();
|
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) => {
|
const showLoadError = (error) => {
|
||||||
status.className = 'status-line user-profile-status is-unavailable';
|
if (disposed) return;
|
||||||
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
|
status.replaceChildren(createErrorState({
|
||||||
});
|
title: 'Не удалось загрузить профиль',
|
||||||
|
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||||
|
onRetry: () => {
|
||||||
|
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||||||
|
refresh().catch(showLoadError);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
refresh().catch(showLoadError);
|
||||||
|
|
||||||
return screen;
|
return screen;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { createTopBar } from '../components/topbar.js';
|
import { createTopBar } from '../components/topbar.js';
|
||||||
|
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||||
import { authService, state } from '../state.js';
|
import { authService, state } from '../state.js';
|
||||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||||
import { navigateBack } from '../router.js';
|
import { navigateBack } from '../router.js';
|
||||||
import { escapeProfileHtml } from '../components/profile-card.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: 'Добавить связь' };
|
export const pageMeta = { id: 'user-relation-manage-view', title: 'Добавить связь' };
|
||||||
|
|
||||||
@@ -62,12 +65,12 @@ function socialButtonsHtml(flags = {}) {
|
|||||||
</button>`).join('');
|
</button>`).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
function officialBlockHtml(flags = {}) {
|
function officialBlockHtml(flags = {}, targetIsOfficial = false) {
|
||||||
return `
|
return `
|
||||||
<section class="card stack relation-manage-card relation-manage-card--official">
|
<section class="card stack relation-manage-card relation-manage-card--official">
|
||||||
<div class="relation-manage-card-head">
|
<div class="relation-manage-card-head">
|
||||||
<strong>Основной аккаунт</strong>
|
<strong>Основной аккаунт</strong>
|
||||||
<span>Этот аккаунт — основной</span>
|
<span>${targetIsOfficial ? 'Этот аккаунт отмечен как основной' : 'Подтвердите, если это основной аккаунт этого человека'}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="relation-manage-confirmations">
|
<div class="relation-manage-confirmations">
|
||||||
${flags.outOfficialAccount ? '<div class="relation-manage-confirmation">✓ Вы подтвердили его основной аккаунт</div>' : ''}
|
${flags.outOfficialAccount ? '<div class="relation-manage-confirmation">✓ Вы подтвердили его основной аккаунт</div>' : ''}
|
||||||
@@ -79,12 +82,12 @@ function officialBlockHtml(flags = {}) {
|
|||||||
</section>`;
|
</section>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function shineBlockHtml(flags = {}) {
|
function shineBlockHtml(flags = {}, targetIsShining = false) {
|
||||||
return `
|
return `
|
||||||
<section class="card stack relation-manage-card relation-manage-card--shine">
|
<section class="card stack relation-manage-card relation-manage-card--shine">
|
||||||
<div class="relation-manage-card-head">
|
<div class="relation-manage-card-head">
|
||||||
<strong>Сияющий</strong>
|
<strong>Сияющий</strong>
|
||||||
<span>Этот аккаунт — сияющий</span>
|
<span>${targetIsShining ? 'Этот человек отмечен как сияющий' : 'Подтвердите, если считаете этого человека сияющим'}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="relation-manage-confirmations">
|
<div class="relation-manage-confirmations">
|
||||||
${flags.outShineConfirmed ? '<div class="relation-manage-confirmation">✓ Вы подтверждаете его сияющим</div>' : ''}
|
${flags.outShineConfirmed ? '<div class="relation-manage-confirmation">✓ Вы подтверждаете его сияющим</div>' : ''}
|
||||||
@@ -152,8 +155,11 @@ export function render({ route, chrome }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderBody() {
|
function renderBody() {
|
||||||
const canPrimary = selfCard?.accountRole === 'primary' && targetCard?.accountRole === 'primary';
|
// Те же правила, что проверяет сервер (validateConnectionVotingRights): голосует основной аккаунт,
|
||||||
const canShine = selfCard?.shineStatus === 'shining' && targetCard?.shineStatus === 'shining';
|
// за сияние – основной и сам сияющий; цель не должна отказываться от подтверждений.
|
||||||
|
const selfPrimary = selfCard?.accountRole === 'primary';
|
||||||
|
const canPrimary = selfPrimary && targetCard?.accountRole !== 'non_voting';
|
||||||
|
const canShine = selfPrimary && selfCard?.shineStatus === 'shining' && targetCard?.shineStatus !== 'not_interested';
|
||||||
|
|
||||||
body.innerHTML = `
|
body.innerHTML = `
|
||||||
<section class="card stack relation-manage-card relation-manage-card--social">
|
<section class="card stack relation-manage-card relation-manage-card--social">
|
||||||
@@ -166,26 +172,36 @@ export function render({ route, chrome }) {
|
|||||||
${socialButtonsHtml(flags)}
|
${socialButtonsHtml(flags)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
${canPrimary ? officialBlockHtml(flags) : ''}
|
${canPrimary ? officialBlockHtml(flags, targetCard?.accountRole === 'primary') : ''}
|
||||||
${canShine ? shineBlockHtml(flags) : ''}
|
${canShine ? shineBlockHtml(flags, targetCard?.shineStatus === 'shining') : ''}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refresh({ loading = true } = {}) {
|
async function refresh({ loading = true } = {}) {
|
||||||
if (loading) {
|
// Спиннер – только если ответ задержался, иначе он мелькает и сдвигает экран.
|
||||||
status.className = 'status-line relation-manage-status';
|
const loadingTimer = loading ? window.setTimeout(() => {
|
||||||
status.textContent = 'Загрузка...';
|
if (screen.isConnected && !body.childElementCount) status.replaceChildren(createLoadingState({ label: 'Загрузка', delayMs: 0 }));
|
||||||
}
|
}, 500) : 0;
|
||||||
[selfCard, targetCard, flags] = await Promise.all([
|
[selfCard, targetCard, flags] = await Promise.all([
|
||||||
loadUserProfileCard(selfLogin),
|
loadUserProfileCard(selfLogin),
|
||||||
loadUserProfileCard(targetLogin),
|
loadUserProfileCard(targetLogin),
|
||||||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin }),
|
loadRelationsForPair({ currentLogin: selfLogin, targetLogin }),
|
||||||
]);
|
]);
|
||||||
|
window.clearTimeout(loadingTimer);
|
||||||
renderBody();
|
renderBody();
|
||||||
status.className = 'status-line relation-manage-status';
|
status.className = 'status-line relation-manage-status';
|
||||||
status.textContent = '';
|
status.textContent = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SOCIAL_DONE = {
|
||||||
|
none: 'Связь убрана',
|
||||||
|
contact: 'Добавлен в контакты',
|
||||||
|
friend: 'Добавлен в друзья',
|
||||||
|
close_friend: 'Добавлен в близкие друзья',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Выбор сохраняется прямо на нажатой кнопке (без строки статуса, которая сдвигала экран),
|
||||||
|
// после сохранения – короткое сообщение и возврат на страницу пользователя.
|
||||||
body.addEventListener('click', async (event) => {
|
body.addEventListener('click', async (event) => {
|
||||||
const button = event.target.closest('button');
|
const button = event.target.closest('button');
|
||||||
if (!button || busy) return;
|
if (!button || busy) return;
|
||||||
@@ -193,24 +209,36 @@ export function render({ route, chrome }) {
|
|||||||
const social = button.dataset.socialKind;
|
const social = button.dataset.socialKind;
|
||||||
const confirm = button.dataset.confirm;
|
const confirm = button.dataset.confirm;
|
||||||
if (!social && !confirm) return;
|
if (!social && !confirm) return;
|
||||||
|
if (social && effectiveSocial(flags, 'out') === social) { navigateBack(); return; }
|
||||||
|
|
||||||
busy = true;
|
busy = true;
|
||||||
body.classList.add('is-busy');
|
body.classList.add('is-busy');
|
||||||
status.className = 'status-line relation-manage-status';
|
body.querySelectorAll('button').forEach((item) => { item.disabled = true; });
|
||||||
status.textContent = 'Сохранение...';
|
const label = button.textContent;
|
||||||
|
button.classList.add('is-pending');
|
||||||
|
button.textContent = 'Сохраняем…';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
let done = '';
|
||||||
if (social) {
|
if (social) {
|
||||||
await changeSocial(social);
|
await changeSocial(social);
|
||||||
|
done = SOCIAL_DONE[social] || 'Связь сохранена';
|
||||||
} else if (confirm === 'official_account') {
|
} else if (confirm === 'official_account') {
|
||||||
await setKind('official_account', !flags.outOfficialAccount);
|
await setKind('official_account', !flags.outOfficialAccount);
|
||||||
|
done = flags.outOfficialAccount ? 'Подтверждение убрано' : 'Вы подтвердили официальный аккаунт';
|
||||||
} else if (confirm === 'shine_confirmed') {
|
} else if (confirm === 'shine_confirmed') {
|
||||||
await setKind('shine_confirmed', !flags.outShineConfirmed);
|
await setKind('shine_confirmed', !flags.outShineConfirmed);
|
||||||
|
done = flags.outShineConfirmed ? 'Подтверждение убрано' : 'Вы подтвердили сияние';
|
||||||
}
|
}
|
||||||
await refresh({ loading: false });
|
if (!screen.isConnected) return;
|
||||||
|
showToast(done);
|
||||||
|
navigateBack();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
status.className = 'status-line relation-manage-status is-unavailable';
|
if (!screen.isConnected) return;
|
||||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось изменить связь'}`;
|
showToast(toUserMessage(error, 'Не удалось изменить связь'), { kind: 'error', timeoutMs: 4000 });
|
||||||
|
button.textContent = label;
|
||||||
|
button.classList.remove('is-pending');
|
||||||
|
body.querySelectorAll('button').forEach((item) => { item.disabled = false; });
|
||||||
} finally {
|
} finally {
|
||||||
busy = false;
|
busy = false;
|
||||||
body.classList.remove('is-busy');
|
body.classList.remove('is-busy');
|
||||||
@@ -223,10 +251,18 @@ export function render({ route, chrome }) {
|
|||||||
return screen;
|
return screen;
|
||||||
}
|
}
|
||||||
|
|
||||||
refresh().catch((error) => {
|
const showLoadError = (error) => {
|
||||||
status.className = 'status-line relation-manage-status is-unavailable';
|
status.className = 'relation-manage-status';
|
||||||
status.textContent = `Ошибка: ${error?.message || 'Не удалось загрузить связи'}`;
|
status.replaceChildren(createErrorState({
|
||||||
});
|
title: 'Не удалось загрузить связь',
|
||||||
|
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||||||
|
onRetry: () => {
|
||||||
|
status.replaceChildren();
|
||||||
|
refresh().catch(showLoadError);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
refresh().catch(showLoadError);
|
||||||
|
|
||||||
return screen;
|
return screen;
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user