diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..01a500e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,13 @@ +## Agent skills + +### Issue tracker + +Issues and specs live as local markdown files under `.scratch//`. See `docs/agents/issue-tracker.md`. + +### Triage labels + +Standard canonical labels (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`). See `docs/agents/triage-labels.md`. + +### Domain docs + +Single-context layout (`GLOSSARY.md` and `docs/adr/` at the repo root). See `docs/agents/domain.md`. diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..80134fa --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,53 @@ +# LectureLog Web + +Веб-платформа для загрузки записей лекций, чтения структурированных конспектов и обмена ими с людьми и ИИ-агентами. + +## Язык + +### Библиотека и уровни видимости + +**Лекция** (`Lecture`): +Запись пользователя на платформе со статусом обработки, уровнем видимости и привязкой к актуальной задаче ядра. +_Avoid_: Файл, проект, сессия + +**Конспект**: +Структурированный результат обработки лекции: дерево разделов и подтем с текстом, таймкодами, слайдами и медиафрагментами. +_Avoid_: Транскрипт, саммари, статья + +**Личная лекция** (`private`): +Лекция, доступная исключительно её владельцу; для всех остальных запросов неотличима от несуществующей. +_Avoid_: Закрытая, черновик + +**Лекция по ссылке** (`unlisted`): +Готовая лекция, открытая по прямой ссылке любому человеку и ИИ-агенту, но скрытая с Витрины, из каталогов для агентов и из поисковой индексации. +_Avoid_: Скрытая публичная, полуприватная + +**Публичная лекция** (`public`): +Готовая лекция, опубликованная владельцем на Витрине и в агентских каталогах и открытая по прямой ссылке всем. +_Avoid_: Общая, открытая + +**Витрина** (`Hub`): +Общий каталог всех публичных лекций платформы, отсортированный по времени публикации. +_Avoid_: Лента, маркетплейс, галерея лекций + +### Структура конспекта и представления + +**Читальный зал** (`Reader`): +Режим чтения готового конспекта человеком в браузере с оглавлением, поиском, медиафрагментами и просмотром слайдов. +_Avoid_: Плеер, просмотрщик + +**Раздел** (`Section`): +Верхний уровень смыслового деления конспекта, объединяющий несколько подтем. +_Avoid_: Глава, тема верхнего уровня + +**Подтема** (`Subtopic`): +Единица изложения внутри раздела с заголовком, временным интервалом исходной записи, текстом и привязанными слайдами. +_Avoid_: Параграф, топик + +**Слайд**: +Изображение страницы презентации или кадра видеозаписи, привязанное к конкретному месту текста подтемы или к её галерее. +_Avoid_: Скриншот, аттач + +**Агентское представление**: +Машиночитаемая Markdown-версия конспекта (или каталога Витрины) с оглавлением, таймкодами и прямыми ссылками на изображения слайдов без аудио- и видеофрагментов, предназначенная для насыщения контекста ИИ-агентов. +_Avoid_: Сырой дамп, экспорт ZIP diff --git a/cmd/preview/main.go b/cmd/preview/main.go index bec6e93..273e1ee 100644 --- a/cmd/preview/main.go +++ b/cmd/preview/main.go @@ -134,6 +134,7 @@ func hubCards() []web.HubCardVM { func lectureCards() []web.LectureCardVM { return []web.LectureCardVM{ {ID: "video", Title: "Кодинг с ИИ: практика внедрения", Status: "ready", StatusLabel: "Готово", Visibility: "public", SourceKind: "video", CanPublish: true, UpdatedAt: "30 Jun 2026"}, + {ID: "unlisted", Title: "Алгоритмы: динамическое программирование", Status: "ready", StatusLabel: "Готово", Visibility: "unlisted", SourceKind: "video", CanPublish: true, UpdatedAt: "4 Jul 2026"}, {ID: "a2", Title: "ОС: планировщик", Status: "processing", StatusLabel: "Обработка", Visibility: "private", SourceKind: "video", ProgressPct: 62, StageLabel: "Распознавание речи", UpdatedAt: "2 Jul 2026"}, {ID: "a3", Title: "Матан: ряды Фурье (YouTube)", Status: "failed", StatusLabel: "Ошибка", Visibility: "private", SourceKind: "video_url", CanRetry: true, ErrorText: "Не удалось скачать видео: требуется авторизация.", UpdatedAt: "1 Jul 2026"}, {ID: "slides", Title: "Фундаментальные основы разработки в эпоху ИИ", Status: "ready", StatusLabel: "Готово", Visibility: "private", SourceKind: "audio", CanPublish: true, UpdatedAt: "21 Jun 2026"}, @@ -175,6 +176,10 @@ func readerVM(dir, title, kind string, isOwner bool) (web.ReaderVM, error) { if sourceTitle == "" { sourceTitle = title } + visibility := "public" + if isOwner { + visibility = "private" + } vm := web.ReaderVM{ LectureID: dir, Title: title, @@ -182,6 +187,7 @@ func readerVM(dir, title, kind string, isOwner bool) (web.ReaderVM, error) { SourceKind: kind, Duration: int(structure.Source.Duration), IsOwner: isOwner, + Visibility: visibility, } mediaIndex, slideIndex := 0, 0 diff --git a/cmd/server/main.go b/cmd/server/main.go index 316e1b4..00f5b56 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -191,7 +191,11 @@ func main() { &lectureRepo{lectures: lectureDB}, &coreTasksAdapter{core: core}, ) - hubSvc := hub.NewService(&hubRepo{lectures: lectureDB}, 0) + hubSvc := hub.NewService( + &hubRepo{lectures: lectureDB}, + 0, + hub.WithBaseOrigin(web.OriginFromCallbackURL(cfg.OAuth.CallbackURL)), + ) s3Client, err := s3.New(s3.Config{ Endpoint: cfg.CoreMinIO.Endpoint, AccessKey: cfg.CoreMinIO.AccessKey, @@ -209,7 +213,7 @@ func main() { reader.NewMarkdownRenderer(), cfg.PresignedTTL, ) - readerHandlers := reader.NewHandlers(readerSvc, core) + readerHandlers := reader.NewHandlers(readerSvc, core, reader.WithBaseOrigin(web.OriginFromCallbackURL(cfg.OAuth.CallbackURL))) // CSRF-ключ генерируется на старте (32 случайных байта). // ДОЛГ: для прод-стабильности вынести в env (PLATFORM_CSRF_KEY) — рестарт инвалидирует токены. diff --git a/docs/adr/0001-agent-markdown-and-slide-proxy.md b/docs/adr/0001-agent-markdown-and-slide-proxy.md new file mode 100644 index 0000000..b0f178a --- /dev/null +++ b/docs/adr/0001-agent-markdown-and-slide-proxy.md @@ -0,0 +1,3 @@ +# Агентское представление конспектов и проксирование слайдов через платформу + +ИИ-агенты (как локальные CLI-инструменты, так и облачные веб-фетчеры) теряют структуру на обвязке SSR-HTML «Читального зала», раздувают контекст длинными временными S3 presigned-ссылками и ломаются при их протухании через 24 часа или блокировке стороннего S3-домена. Мы отдаём каноническое агентское представление в `text/markdown` из `structure.json` как по явному маршруту `/read/{id}.md` (и каталогам `/hub.md`, `/llms.txt`), так и на основном `/read/{id}` через согласование `Accept: text/markdown` и распознавание агентских `User-Agent` (с `Vary: Accept, User-Agent`), а изображения слайдов стримим напрямую через платформу по стабильным URL `/read/{id}/slides/{n}` с проверкой прав на каждый запрос (в отступление от общего правила «весь контент — только presigned S3», которое сохраняется для тяжёлых медиафрагментов в браузере). diff --git a/docs/adr/0002-unlisted-lecture-visibility.md b/docs/adr/0002-unlisted-lecture-visibility.md new file mode 100644 index 0000000..948b52b --- /dev/null +++ b/docs/adr/0002-unlisted-lecture-visibility.md @@ -0,0 +1,3 @@ +# Трёхуровневая видимость лекции (`private` / `unlisted` / `public`) без отдельных share-токенов + +Владельцам нужно кормить конспектами внешних ИИ-агентов (не имеющих пользовательской куки-сессии), не выставляя личные или рабочие лекции на общую Витрину. Вместо таблицы отзываемых `share_token` и удлинённых секретных ссылок мы расширяем `lecture_visibility` третьим состоянием `unlisted` («По ссылке»), опираясь на криптостойкость уже существующего `lecture_id` (UUID v4): лекция открыта по тому же каноническому URL `/read/{id}` и `/read/{id}.md` до переключения обратно в `private`, но исключена из `/hub`, `/hub.md` и `/llms.txt`, не меняет `published_at` и отдаётся с `X-Robots-Tag: noindex, nofollow` и `Cache-Control: private, no-store`. diff --git a/docs/agents/domain.md b/docs/agents/domain.md new file mode 100644 index 0000000..4032de0 --- /dev/null +++ b/docs/agents/domain.md @@ -0,0 +1,51 @@ +# Domain Docs + +How the engineering skills should consume this repo's domain documentation when exploring the codebase. + +## Before exploring, read these + +- **`GLOSSARY.md`** at the repo root, or +- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic. +- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src//docs/adr/` for context-scoped decisions. + +If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved. + +## File structure + +Single-context repo (most repos): + +``` +/ +├── GLOSSARY.md +├── docs/adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +Multi-context repo (presence of `GLOSSARY-MAP.md` at the root): + +``` +/ +├── GLOSSARY-MAP.md +├── docs/adr/ ← system-wide decisions +└── src/ + ├── ordering/ + │ ├── GLOSSARY.md + │ └── docs/adr/ ← context-specific decisions + └── billing/ + ├── GLOSSARY.md + └── docs/adr/ +``` + +## Use the glossary's vocabulary + +When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids. + +If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`). + +## Flag ADR conflicts + +If your output contradicts an existing ADR, surface it explicitly rather than silently overriding: + +> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_ diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md new file mode 100644 index 0000000..0209a19 --- /dev/null +++ b/docs/agents/issue-tracker.md @@ -0,0 +1,30 @@ +# Issue tracker: Local Markdown + +Issues and specs for this repo live as markdown files in `.scratch/`. + +## Conventions + +- One feature per directory: `.scratch//` +- The spec is `.scratch//spec.md` +- Implementation issues are one file per ticket at `.scratch//issues/-.md`, numbered from `01`, never a single combined tickets file +- Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings) +- Comments and conversation history append to the bottom of the file under a `## Comments` heading + +## When a skill says "publish to the issue tracker" + +Create a new file under `.scratch//` (creating the directory if needed). + +## When a skill says "fetch the relevant ticket" + +Read the file at the referenced path. The user will normally pass the path or the issue number directly. + +## Wayfinding operations + +Used by `/wayfinder`. The **map** is a file with one **child** file per ticket. + +- **Map**: `.scratch//map.md` (the Notes / Decisions-so-far / Fog body). +- **Child ticket**: `.scratch//issues/NN-.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`. +- **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`. +- **Frontier**: scan `.scratch//issues/` for files that are open, unblocked, and unclaimed; first by number wins. +- **Claim**: set `Status: claimed` and save before any work. +- **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`. diff --git a/docs/agents/triage-labels.md b/docs/agents/triage-labels.md new file mode 100644 index 0000000..5276464 --- /dev/null +++ b/docs/agents/triage-labels.md @@ -0,0 +1,15 @@ +# Triage Labels + +The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker. + +| Label in mattpocock/skills | Label in our tracker | Meaning | +| -------------------------- | -------------------- | ---------------------------------------- | +| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue | +| `needs-info` | `needs-info` | Waiting on reporter for more information | +| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent | +| `ready-for-human` | `ready-for-human` | Requires human implementation | +| `wontfix` | `wontfix` | Will not be actioned | + +When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table. + +Edit the "Label in our tracker" column to match whatever vocabulary you actually use. diff --git a/internal/db/lectures.go b/internal/db/lectures.go index d05e0ec..49fcf0f 100644 --- a/internal/db/lectures.go +++ b/internal/db/lectures.go @@ -25,7 +25,7 @@ type LectureRow struct { Status string // ErrorCode — код ошибки ядра при failed; "" если NULL (COALESCE). ErrorCode string - // Visibility — видимость: private|public. + // Visibility — видимость: private|unlisted|public. Visibility string // SourceKind — тип источника: audio|video|video_url. SourceKind string @@ -243,32 +243,39 @@ func (db *LectureDB) Rename(ctx context.Context, lectureID, ownerID, title strin // SetVisibility меняет видимость лекции. // - public: WHERE owner_id=? AND status='ready'; SET published_at = now() (обновляем при каждой публикации). +// - unlisted: WHERE owner_id=? AND status='ready'; published_at НЕ трогаем (историческое значение сохраняется). // - private: WHERE owner_id=?; published_at НЕ обнуляем (§8: снятие в любой момент). // -// Возвращает affected (0 при public+не-ready → домен трактует как «нельзя опубликовать»). +// Возвращает affected (0 при public/unlisted + не-ready → домен трактует как «нельзя открыть»). func (db *LectureDB) SetVisibility(ctx context.Context, lectureID, ownerID, visibility string) (int64, error) { var q string - var args []any - - if visibility == "public" { + switch visibility { + case "public": // Публикация только готовых лекций; обновляем published_at при каждой публикации q = ` UPDATE lectures SET visibility = 'public', published_at = now(), updated_at = now() WHERE lecture_id = $1 AND owner_id = $2 AND status = 'ready' ` - args = []any{lectureID, ownerID} - } else { + case "unlisted": + // Открытие по ссылке только готовых лекций; published_at сохраняем как есть + q = ` + UPDATE lectures + SET visibility = 'unlisted', updated_at = now() + WHERE lecture_id = $1 AND owner_id = $2 AND status = 'ready' + ` + case "private": // Снятие с публикации: published_at сохраняем (§8: повторная публикация перепишет) q = ` UPDATE lectures SET visibility = 'private', updated_at = now() WHERE lecture_id = $1 AND owner_id = $2 ` - args = []any{lectureID, ownerID} + default: + return 0, fmt.Errorf("db: SetVisibility: неизвестная видимость %q", visibility) } - tag, err := db.Pool.Exec(ctx, q, args...) + tag, err := db.Pool.Exec(ctx, q, lectureID, ownerID) if err != nil { return 0, fmt.Errorf("db: SetVisibility: %w", err) } diff --git a/internal/db/lectures_test.go b/internal/db/lectures_test.go index 25c7514..4bcdcfd 100644 --- a/internal/db/lectures_test.go +++ b/internal/db/lectures_test.go @@ -371,6 +371,152 @@ func TestLectureDB_SetVisibility_PrivateNoPublishedAtReset(t *testing.T) { } } +// TestLectureDB_SetVisibility_UnlistedOnReady проверяет открытие готовой лекции +// по ссылке: visibility=unlisted и published_at остаётся NULL. +func TestLectureDB_SetVisibility_UnlistedOnReady(t *testing.T) { + ctx, userDB, lectureDB := setupLectureTestDB(t) + + user := createTestUser(t, ctx, userDB, "unlisted@example.com") + lec := createTestLecture(t, ctx, lectureDB, user.UserID, "Лекция по ссылке", "audio") + setReadyStatus(t, ctx, lectureDB.Pool, lec.LectureID) + + affected, err := lectureDB.SetVisibility(ctx, lec.LectureID, user.UserID, "unlisted") + if err != nil { + t.Fatalf("SetVisibility unlisted: %v", err) + } + if affected != 1 { + t.Errorf("SetVisibility unlisted affected = %d, ожидается 1", affected) + } + + updated, err := lectureDB.FindByID(ctx, lec.LectureID) + if err != nil { + t.Fatalf("FindByID после unlisted: %v", err) + } + if updated.Visibility != "unlisted" { + t.Errorf("Visibility = %q, ожидается unlisted", updated.Visibility) + } + if updated.PublishedAt != nil { + t.Errorf("PublishedAt = %v, ожидается nil: переход в unlisted не публикует лекцию", *updated.PublishedAt) + } +} + +// TestLectureDB_SetVisibility_UnlistedKeepsPublishedAt проверяет, что исторический +// published_at сохраняется при цепочке public → unlisted → private. +func TestLectureDB_SetVisibility_UnlistedKeepsPublishedAt(t *testing.T) { + ctx, userDB, lectureDB := setupLectureTestDB(t) + + user := createTestUser(t, ctx, userDB, "unlisted-history@example.com") + lec := createTestLecture(t, ctx, lectureDB, user.UserID, "История публикации", "audio") + setReadyStatus(t, ctx, lectureDB.Pool, lec.LectureID) + + if _, err := lectureDB.SetVisibility(ctx, lec.LectureID, user.UserID, "public"); err != nil { + t.Fatalf("SetVisibility public: %v", err) + } + published, err := lectureDB.FindByID(ctx, lec.LectureID) + if err != nil || published.PublishedAt == nil { + t.Fatalf("после публикации PublishedAt = %v, err = %v", published, err) + } + savedPublishedAt := *published.PublishedAt + + for _, visibility := range []string{"unlisted", "private"} { + affected, err := lectureDB.SetVisibility(ctx, lec.LectureID, user.UserID, visibility) + if err != nil { + t.Fatalf("SetVisibility %s: %v", visibility, err) + } + if affected != 1 { + t.Fatalf("SetVisibility %s affected = %d, ожидается 1", visibility, affected) + } + + updated, err := lectureDB.FindByID(ctx, lec.LectureID) + if err != nil { + t.Fatalf("FindByID после %s: %v", visibility, err) + } + if updated.Visibility != visibility { + t.Errorf("Visibility = %q, ожидается %q", updated.Visibility, visibility) + } + if updated.PublishedAt == nil { + t.Fatalf("PublishedAt обнулился при переходе в %s", visibility) + } + if !updated.PublishedAt.Equal(savedPublishedAt) { + t.Errorf("PublishedAt изменился при переходе в %s: было %v, стало %v", visibility, savedPublishedAt, *updated.PublishedAt) + } + } +} + +// TestLectureDB_SetVisibility_UnlistedOnNotReady проверяет отказ открыть по ссылке +// неготовую лекцию: affected=0 для processing и failed. +func TestLectureDB_SetVisibility_UnlistedOnNotReady(t *testing.T) { + ctx, userDB, lectureDB := setupLectureTestDB(t) + + user := createTestUser(t, ctx, userDB, "unlisted-not-ready@example.com") + + processing := createTestLecture(t, ctx, lectureDB, user.UserID, "В обработке", "audio") // статус по умолчанию processing + failed := createTestLecture(t, ctx, lectureDB, user.UserID, "С ошибкой", "audio") + setFailedStatus(t, ctx, lectureDB.Pool, failed.LectureID, "processing_error") + + for _, lec := range []*LectureRow{processing, failed} { + affected, err := lectureDB.SetVisibility(ctx, lec.LectureID, user.UserID, "unlisted") + if err != nil { + t.Fatalf("SetVisibility unlisted для статуса %q: %v", lec.Status, err) + } + if affected != 0 { + t.Errorf("SetVisibility unlisted для статуса %q: affected = %d, ожидается 0", lec.Status, affected) + } + } +} + +// TestLectureDB_SetVisibility_UnknownVisibility проверяет, что неизвестное значение +// видимости отвергается без изменения строки. +func TestLectureDB_SetVisibility_UnknownVisibility(t *testing.T) { + ctx, userDB, lectureDB := setupLectureTestDB(t) + + user := createTestUser(t, ctx, userDB, "unknown-visibility@example.com") + lec := createTestLecture(t, ctx, lectureDB, user.UserID, "Неизвестная видимость", "audio") + + if _, err := lectureDB.SetVisibility(ctx, lec.LectureID, user.UserID, "shared"); err == nil { + t.Fatal("SetVisibility с неизвестной видимостью: ожидается ошибка") + } + + row, err := lectureDB.FindByID(ctx, lec.LectureID) + if err != nil { + t.Fatalf("FindByID: %v", err) + } + if row.Visibility != "private" { + t.Errorf("Visibility = %q, ожидается private (значение не изменилось)", row.Visibility) + } +} + +// TestLectureDB_ListPublic_ExcludesUnlisted проверяет, что лекции по ссылке +// не попадают на Витрину как без предварительной публикации (published_at IS NULL), +// так и после снятия с публикации в public → unlisted (published_at IS NOT NULL). +func TestLectureDB_ListPublic_ExcludesUnlisted(t *testing.T) { + ctx, userDB, lectureDB := setupLectureTestDB(t) + + user := createTestUser(t, ctx, userDB, "hub-unlisted@example.com") + directUnlisted := createTestLecture(t, ctx, lectureDB, user.UserID, "По ссылке сразу", "audio") + formerlyPublic := createTestLecture(t, ctx, lectureDB, user.UserID, "По ссылке после Витрины", "video") + setReadyStatus(t, ctx, lectureDB.Pool, directUnlisted.LectureID) + setReadyStatus(t, ctx, lectureDB.Pool, formerlyPublic.LectureID) + + if _, err := lectureDB.SetVisibility(ctx, directUnlisted.LectureID, user.UserID, "unlisted"); err != nil { + t.Fatalf("SetVisibility direct unlisted: %v", err) + } + if _, err := lectureDB.SetVisibility(ctx, formerlyPublic.LectureID, user.UserID, "public"); err != nil { + t.Fatalf("SetVisibility public: %v", err) + } + if _, err := lectureDB.SetVisibility(ctx, formerlyPublic.LectureID, user.UserID, "unlisted"); err != nil { + t.Fatalf("SetVisibility public->unlisted: %v", err) + } + + rows, err := lectureDB.ListPublic(ctx, 10) + if err != nil { + t.Fatalf("ListPublic: %v", err) + } + if len(rows) != 0 { + t.Errorf("ListPublic: len = %d, ожидается 0 — unlisted не попадает на Витрину", len(rows)) + } +} + // TestLectureDB_Delete_Owner проверяет hard-delete своей лекции. func TestLectureDB_Delete_Owner(t *testing.T) { ctx, userDB, lectureDB := setupLectureTestDB(t) diff --git a/internal/db/migrate_integration_test.go b/internal/db/migrate_integration_test.go index 7fd5bfb..da40018 100644 --- a/internal/db/migrate_integration_test.go +++ b/internal/db/migrate_integration_test.go @@ -194,6 +194,23 @@ func TestMigrateIntegration(t *testing.T) { t.Fatal("enum lecture_visibility не найден в pg_type") } + // Проверяем, что миграция 005 добавила третье значение видимости 'unlisted'. + var hasUnlisted bool + err = pool.QueryRow(ctx, + `SELECT EXISTS ( + SELECT 1 FROM pg_enum e + JOIN pg_type t ON t.oid = e.enumtypid + WHERE t.typname = 'lecture_visibility' + AND e.enumlabel = 'unlisted' + )`, + ).Scan(&hasUnlisted) + if err != nil { + t.Fatalf("запрос pg_enum для lecture_visibility: %v", err) + } + if !hasUnlisted { + t.Fatal("значение 'unlisted' не найдено в pg_enum для lecture_visibility") + } + // Проверяем наличие enum lecture_source_kind err = pool.QueryRow(ctx, `SELECT EXISTS ( diff --git a/internal/db/migrations/005_lecture_visibility_unlisted.sql b/internal/db/migrations/005_lecture_visibility_unlisted.sql new file mode 100644 index 0000000..f72daa2 --- /dev/null +++ b/internal/db/migrations/005_lecture_visibility_unlisted.sql @@ -0,0 +1,8 @@ +-- 005: расширение перечисления lecture_visibility значением 'unlisted' («По ссылке»). + +ALTER TYPE lecture_visibility ADD VALUE IF NOT EXISTS 'unlisted'; + +---- create above / drop below ---- + +-- Удаление значения из ENUM в PostgreSQL не поддерживается напрямую. +SELECT 1; diff --git a/internal/hub/handlers.go b/internal/hub/handlers.go index d3cb141..70230ca 100644 --- a/internal/hub/handlers.go +++ b/internal/hub/handlers.go @@ -2,21 +2,34 @@ package hub import ( "context" + "fmt" + "io" "log" "net/http" + "strings" "time" "github.com/LectureLog/lecturelog-web/internal/web" "github.com/go-chi/chi/v5" ) -// Mount монтирует витрину. RequireAuth не нужен: маршрут доступен анонимам. +// Mount монтирует витрину. RequireAuth не нужен: маршруты доступны анонимам. func (s *Service) Mount(r chi.Router) { r.Get("/hub", s.handleHub) + r.Get("/hub.md", s.handleHubMarkdown) + r.Get("/llms.txt", s.handleLLMsTxt) } -// handleHub рендерит публичную витрину лекций. +// handleHub рендерит публичную витрину лекций: HTML для людей и Markdown для агентов. func (s *Service) handleHub(w http.ResponseWriter, r *http.Request) { + // Ответ зависит от Accept и User-Agent — сообщаем об этом кешам, + // сохраняя уже выставленные Vary (например, Cookie от CSRF-middleware). + web.SetVaryAcceptUserAgent(w) + if web.WantsMarkdown(r) { + s.handleHubMarkdown(w, r) + return + } + lectures, err := s.List(r.Context()) if err != nil { log.Printf("hub: handleHub: %v", err) @@ -35,6 +48,64 @@ func (s *Service) handleHub(w http.ResponseWriter, r *http.Request) { } } +// handleHubMarkdown отдаёт Markdown-каталог Витрины (агентское представление). +func (s *Service) handleHubMarkdown(w http.ResponseWriter, r *http.Request) { + s.serveMarkdown(w, r, "handleHubMarkdown", func(b *strings.Builder, lectures []PublicLecture, origin string) { + b.WriteString("# Витрина LectureLog\n\n") + writeLectureCatalog(b, lectures, origin) + }) +} + +// handleLLMsTxt отдаёт индекс платформы для внешних ИИ-агентов (llms.txt). +func (s *Service) handleLLMsTxt(w http.ResponseWriter, r *http.Request) { + s.serveMarkdown(w, r, "handleLLMsTxt", func(b *strings.Builder, lectures []PublicLecture, origin string) { + b.WriteString("# LectureLog\n\n") + b.WriteString("> Веб-платформа для чтения структурированных конспектов лекций с тайм-кодами и слайдами.\n\n") + b.WriteString("## Как читать лекции агентом\n\n") + b.WriteString("Конспект публичной лекции или лекции по ссылке доступен в Markdown по адресу " + origin + "/read/{id}.md\n") + b.WriteString("или по адресу " + origin + "/read/{id} с заголовком `Accept: text/markdown`.\n") + b.WriteString("Изображения слайдов отдаются по " + origin + "/read/{id}/slides/{n}, где `{n}` — номер слайда начиная с 1.\n") + b.WriteString("Каталог Витрины в Markdown: " + origin + "/hub.md.\n\n") + b.WriteString("## Публичные лекции\n\n") + writeLectureCatalog(b, lectures, origin) + }) +} + +// serveMarkdown загружает публичные лекции и отдаёт отформатированный Markdown-ответ. +func (s *Service) serveMarkdown(w http.ResponseWriter, r *http.Request, op string, build func(b *strings.Builder, lectures []PublicLecture, origin string)) { + lectures, err := s.List(r.Context()) + if err != nil { + log.Printf("hub: %s: %v", op, err) + http.Error(w, "внутренняя ошибка", http.StatusInternalServerError) + return + } + + var b strings.Builder + build(&b, lectures, web.ResolveOrigin(s.baseOrigin, r)) + + w.Header().Set("Content-Type", "text/markdown; charset=utf-8") + _, _ = io.WriteString(w, b.String()) +} + +// writeLectureCatalog пишет Markdown-список публичных лекций с абсолютными +// ссылками на их агентское представление. +func writeLectureCatalog(b *strings.Builder, lectures []PublicLecture, origin string) { + if len(lectures) == 0 { + b.WriteString("Пока нет публичных лекций.\n") + return + } + for _, lecture := range lectures { + fmt.Fprintf(b, "- [%s](%s/read/%s.md) — %s, автор: %s, опубликовано: %s\n", + web.EscapeMarkdownLinkText(lecture.Title), + origin, + lecture.ID, + sourceLabel(lecture.SourceKind), + web.SanitizeInlineText(lecture.AuthorName), + lecture.PublishedAt.UTC().Format("2006-01-02"), + ) + } +} + // hubToVM конвертирует доменную лекцию в данные карточки витрины. func hubToVM(lecture PublicLecture) web.HubCardVM { return web.HubCardVM{ diff --git a/internal/hub/handlers_test.go b/internal/hub/handlers_test.go index 158eaf7..84369dc 100644 --- a/internal/hub/handlers_test.go +++ b/internal/hub/handlers_test.go @@ -78,3 +78,330 @@ func TestHandleHub_RepoError(t *testing.T) { t.Errorf("GET /hub = %d, ожидается 500", rec.Code) } } + +const testBaseOrigin = "https://lecturelog.example" + +// testRepository — репозиторий витрины с фиксированным набором публичных лекций. +func testRepository(lectures []PublicLecture) *mockRepository { + return &mockRepository{ + listPublicFn: func(_ context.Context, _ int) ([]PublicLecture, error) { + return lectures, nil + }, + } +} + +// testLectures — две публичные лекции с детерминированными метаданными. +func testLectures() []PublicLecture { + return []PublicLecture{ + { + ID: "lecture-1", + Title: "Алгебра", + SourceKind: "audio", + AuthorName: "Анна", + PublishedAt: time.Date(2026, 2, 3, 10, 0, 0, 0, time.UTC), + }, + { + ID: "lecture-2", + Title: "Физика", + SourceKind: "video_url", + AuthorName: "Борис", + PublishedAt: time.Date(2026, 3, 14, 18, 30, 0, 0, time.UTC), + }, + } +} + +func serveHub(svc *Service, target string, headers map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, target, nil) + for key, value := range headers { + req.Header.Set(key, value) + } + rec := httptest.NewRecorder() + mountHubTestRouter(svc).ServeHTTP(rec, req) + return rec +} + +// TestHandleHubMarkdown_Catalog проверяет Markdown-каталог Витрины с абсолютными ссылками. +func TestHandleHubMarkdown_Catalog(t *testing.T) { + rec := serveHub(NewService(testRepository(testLectures()), 0, WithBaseOrigin(testBaseOrigin)), "/hub.md", nil) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /hub.md = %d, ожидается 200", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" { + t.Errorf("Content-Type = %q, ожидается text/markdown; charset=utf-8", got) + } + + body := rec.Body.String() + for _, want := range []string{ + "# Витрина LectureLog", + "- [Алгебра](https://lecturelog.example/read/lecture-1.md) — Аудио, автор: Анна, опубликовано: 2026-02-03", + "- [Физика](https://lecturelog.example/read/lecture-2.md) — Ссылка, автор: Борис, опубликовано: 2026-03-14", + } { + if !strings.Contains(body, want) { + t.Errorf("каталог не содержит %q:\n%s", want, body) + } + } +} + +// TestHandleHubMarkdown_Empty проверяет явное сообщение при пустой Витрине. +func TestHandleHubMarkdown_Empty(t *testing.T) { + rec := serveHub(NewService(testRepository([]PublicLecture{}), 0, WithBaseOrigin(testBaseOrigin)), "/hub.md", nil) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /hub.md = %d, ожидается 200", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Пока нет публичных лекций.") { + t.Errorf("пустой каталог должен сообщать об отсутствии лекций:\n%s", rec.Body.String()) + } +} + +// TestHandleHubMarkdown_OriginFallback проверяет fallback origin из запроса. +func TestHandleHubMarkdown_OriginFallback(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "http://hub.local/hub.md", nil) + rec := httptest.NewRecorder() + mountHubTestRouter(NewService(testRepository(testLectures()), 0)).ServeHTTP(rec, req) + + if !strings.Contains(rec.Body.String(), "http://hub.local/read/lecture-1.md") { + t.Errorf("ссылка должна строиться от origin запроса:\n%s", rec.Body.String()) + } +} + +// TestHandleHubMarkdown_RepoError проверяет лаконичную ошибку без утечки деталей. +func TestHandleHubMarkdown_RepoError(t *testing.T) { + repo := &mockRepository{listPublicFn: func(_ context.Context, _ int) ([]PublicLecture, error) { + return nil, errors.New("ошибка БД") + }} + + rec := serveHub(NewService(repo, 0), "/hub.md", nil) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("GET /hub.md = %d, ожидается 500", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" { + t.Errorf("Content-Type = %q, ожидается text/plain; charset=utf-8", got) + } + if strings.Contains(rec.Body.String(), "ошибка БД") { + t.Errorf("ответ не должен раскрывать детали хранилища:\n%s", rec.Body.String()) + } +} + +// TestHandleLLMsTxt проверяет индекс платформы для агентов. +func TestHandleLLMsTxt(t *testing.T) { + rec := serveHub(NewService(testRepository(testLectures()), 0, WithBaseOrigin(testBaseOrigin)), "/llms.txt", nil) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /llms.txt = %d, ожидается 200", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" { + t.Errorf("Content-Type = %q, ожидается text/markdown; charset=utf-8", got) + } + + body := rec.Body.String() + for _, want := range []string{ + "# LectureLog", + "## Как читать лекции агентом", + "https://lecturelog.example/read/{id}.md", + "https://lecturelog.example/read/{id}/slides/{n}", + "https://lecturelog.example/hub.md", + "## Публичные лекции", + "- [Алгебра](https://lecturelog.example/read/lecture-1.md) — Аудио, автор: Анна, опубликовано: 2026-02-03", + "- [Физика](https://lecturelog.example/read/lecture-2.md) — Ссылка, автор: Борис, опубликовано: 2026-03-14", + } { + if !strings.Contains(body, want) { + t.Errorf("llms.txt не содержит %q:\n%s", want, body) + } + } +} + +// TestHandleLLMsTxt_Empty проверяет пустую Витрину в llms.txt. +func TestHandleLLMsTxt_Empty(t *testing.T) { + rec := serveHub(NewService(testRepository([]PublicLecture{}), 0, WithBaseOrigin(testBaseOrigin)), "/llms.txt", nil) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /llms.txt = %d, ожидается 200", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Пока нет публичных лекций.") { + t.Errorf("llms.txt без лекций должен сообщать об их отсутствии:\n%s", rec.Body.String()) + } +} + +// TestHandleLLMsTxt_RepoError проверяет лаконичную ошибку без утечки деталей. +func TestHandleLLMsTxt_RepoError(t *testing.T) { + repo := &mockRepository{listPublicFn: func(_ context.Context, _ int) ([]PublicLecture, error) { + return nil, errors.New("ошибка БД") + }} + + rec := serveHub(NewService(repo, 0), "/llms.txt", nil) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("GET /llms.txt = %d, ожидается 500", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" { + t.Errorf("Content-Type = %q, ожидается text/plain; charset=utf-8", got) + } +} + +// TestHandleHub_ContentNegotiation проверяет выбор Markdown/HTML и заголовок Vary. +func TestHandleHub_ContentNegotiation(t *testing.T) { + tests := []struct { + name string + headers map[string]string + wantType string + wantMarkdown bool + }{ + { + name: "обычный браузер", + headers: map[string]string{"Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) Chrome/126.0"}, + wantType: "text/html; charset=utf-8", + }, + { + name: "Accept text/markdown", + headers: map[string]string{"Accept": "text/markdown"}, + wantType: "text/markdown; charset=utf-8", + wantMarkdown: true, + }, + { + name: "curl", + headers: map[string]string{"Accept": "*/*", "User-Agent": "curl/8.5.0"}, + wantType: "text/markdown; charset=utf-8", + wantMarkdown: true, + }, + { + name: "ChatGPT-User", + headers: map[string]string{"Accept": "text/html", "User-Agent": "Mozilla/5.0 (compatible; ChatGPT-User/1.0)"}, + wantType: "text/markdown; charset=utf-8", + wantMarkdown: true, + }, + { + name: "ClaudeBot", + headers: map[string]string{"Accept": "*/*", "User-Agent": "ClaudeBot/1.0"}, + wantType: "text/markdown; charset=utf-8", + wantMarkdown: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := serveHub(NewService(testRepository(testLectures()), 0, WithBaseOrigin(testBaseOrigin)), "/hub", tt.headers) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /hub = %d, ожидается 200", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != tt.wantType { + t.Errorf("Content-Type = %q, ожидается %q", got, tt.wantType) + } + if got := rec.Header().Get("Vary"); got != "Accept, User-Agent" { + t.Errorf("Vary = %q, ожидается \"Accept, User-Agent\"", got) + } + body := rec.Body.String() + if tt.wantMarkdown { + if !strings.Contains(body, "# Витрина LectureLog") || strings.Contains(body, "= 3600 + + // Ядро может не знать названия источника (title: null) — берём заголовок + // Лекции, чтобы блок метаданных не был пустым. + sourceTitle := structure.Source.Title + if sourceTitle == "" { + sourceTitle = lecture.Title + } + sourceKind := lecture.SourceKind + if sourceKind == "" { + sourceKind = structure.Source.Kind + } + + fmt.Fprintf(&b, "# %s\n\n", web.SanitizeInlineText(lecture.Title)) + fmt.Fprintf(&b, "- Источник: %s\n", web.SanitizeInlineText(sourceTitle)) + fmt.Fprintf(&b, "- Тип источника: %s\n", agentSourceLabel(sourceKind)) + fmt.Fprintf(&b, "- Длительность: %s\n", formatClock(int(structure.Source.Duration))) + fmt.Fprintf(&b, "- Канонический URL: %s/read/%s\n\n", origin, lecture.ID) + + b.WriteString("## Содержание\n\n") + for sectionIndex, section := range structure.Sections { + fmt.Fprintf(&b, "- %02d. %s\n", sectionIndex+1, web.SanitizeInlineText(section.Title)) + for subtopicIndex, subtopic := range section.Subtopics { + fmt.Fprintf(&b, " - %d.%d %s\n", sectionIndex+1, subtopicIndex+1, web.SanitizeInlineText(subtopic.Title)) + } + } + b.WriteString("\n") + + for sectionIndex, section := range structure.Sections { + fmt.Fprintf(&b, "## %02d. %s\n\n", sectionIndex+1, web.SanitizeInlineText(section.Title)) + for subtopicIndex, subtopic := range section.Subtopics { + writeAgentSubtopic(&b, origin, lecture.ID, subtopic, slideMap, sectionIndex, subtopicIndex, longLecture) + } + } + return b.String() +} + +// writeAgentSubtopic пишет Подтему: заголовок, таймкод, текст с инлайн-Слайдами +// по маркерам и галерею оставшихся Слайдов в конце. +func writeAgentSubtopic(b *strings.Builder, origin, lectureID string, subtopic Subtopic, slideMap SlideMap, sectionIndex, subtopicIndex int, longLecture bool) { + fmt.Fprintf(b, "### %d.%d %s\n\n", sectionIndex+1, subtopicIndex+1, web.SanitizeInlineText(subtopic.Title)) + if subtopic.Media != nil { + // Для длинных записей весь Конспект держит часы в таймкодах, чтобы + // Подтемы не смешивали MM:SS и HH:MM:SS в одном представлении. + start, end := int(subtopic.Media.Start), int(subtopic.Media.End) + withHours := longLecture || start >= 3600 || end >= 3600 + fmt.Fprintf(b, "[%s – %s]\n\n", + formatClockValue(start, withHours), + formatClockValue(end, withHours), + ) + } + + subtopicSlideNums := slideMap.Numbers[sectionIndex][subtopicIndex] + placed := make(map[int]bool) + rest := subtopic.ContentMD + for { + loc := slideMarker.FindStringSubmatchIndex(rest) + if loc == nil { + break + } + writeAgentText(b, rest[:loc[0]]) + if num, err := strconv.Atoi(rest[loc[2]:loc[3]]); err == nil { + if slices.Contains(subtopicSlideNums, num) && !placed[num] { + writeAgentSlide(b, origin, lectureID, num, subtopic.Title) + placed[num] = true + } + } + rest = rest[loc[1]:] + } + writeAgentText(b, rest) + + for _, num := range subtopicSlideNums { + if placed[num] { + continue + } + writeAgentSlide(b, origin, lectureID, num, subtopic.Title) + placed[num] = true + } +} + +// writeAgentSlide пишет Markdown-картинку Слайда с абсолютной ссылкой. +func writeAgentSlide(b *strings.Builder, origin, lectureID string, num int, subtopicTitle string) { + fmt.Fprintf(b, "![Слайд %d: %s](%s/read/%s/slides/%d)\n\n", num, web.EscapeMarkdownLinkText(subtopicTitle), origin, lectureID, num) +} + +// writeAgentText пишет текстовый фрагмент Подтемы: обычный Markdown остаётся +// как есть, Obsidian-callout'ы превращаются в чистые Markdown-цитаты. +func writeAgentText(b *strings.Builder, md string) { + for _, block := range splitCallouts(md) { + if block.callout == nil { + text := strings.TrimSpace(block.text) + if text == "" { + continue + } + b.WriteString(text) + b.WriteString("\n\n") + continue + } + b.WriteString(agentCalloutMarkdown(*block.callout, block.text)) + b.WriteString("\n\n") + } +} + +// agentCalloutMarkdown собирает Markdown-цитату вместо свёрнутого HTML-callout'а: +// первая строка — полужирный локализованный тип и заголовок, далее тело. +func agentCalloutMarkdown(meta calloutMeta, body string) string { + var b strings.Builder + title := calloutTitle(meta.kind) + if meta.title != "" { + fmt.Fprintf(&b, "> **%s: %s**", title, meta.title) + } else { + fmt.Fprintf(&b, "> **%s**", title) + } + if body == "" { + return b.String() + } + for _, line := range strings.Split(body, "\n") { + if strings.TrimSpace(line) == "" { + b.WriteString("\n>") + continue + } + b.WriteString("\n> ") + b.WriteString(line) + } + return b.String() +} + +// agentSourceLabel локализует тип источника для блока метаданных. +func agentSourceLabel(kind string) string { + switch kind { + case "audio": + return "Аудио" + case "video": + return "Видео" + case "video_url": + return "Ссылка" + default: + return kind + } +} + +// formatClock форматирует секунды в MM:SS, а для записей от часа — в HH:MM:SS. +func formatClock(seconds int) string { + return formatClockValue(seconds, seconds >= 3600) +} + +// formatClockValue форматирует секунды в MM:SS либо HH:MM:SS при withHours. +func formatClockValue(seconds int, withHours bool) string { + if seconds < 0 { + seconds = 0 + } + if withHours { + return fmt.Sprintf("%02d:%02d:%02d", seconds/3600, (seconds%3600)/60, seconds%60) + } + return fmt.Sprintf("%02d:%02d", seconds/60, seconds%60) +} diff --git a/internal/reader/agent_markdown_test.go b/internal/reader/agent_markdown_test.go new file mode 100644 index 0000000..a773f93 --- /dev/null +++ b/internal/reader/agent_markdown_test.go @@ -0,0 +1,699 @@ +package reader + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/LectureLog/lecturelog-web/internal/auth" + "github.com/go-chi/chi/v5" +) + +// agentAuthRepo подставляет заданного пользователя для проверки матрицы +// доступа: владелец, посторонний читатель или аноним (без куки). +type agentAuthRepo struct{ userID string } + +func (agentAuthRepo) FindUserByEmail(context.Context, string) (*auth.User, error) { + return nil, nil +} + +func (r agentAuthRepo) FindUserByID(context.Context, string) (*auth.User, error) { + return &auth.User{ID: r.userID}, nil +} + +func (agentAuthRepo) CreateUser(context.Context, auth.Profile) (*auth.User, error) { return nil, nil } + +func (agentAuthRepo) UpsertIdentity(context.Context, string, string, string) error { return nil } + +func (agentAuthRepo) CreateSession(context.Context, string, time.Time) (*auth.Session, error) { + return nil, nil +} + +func (r agentAuthRepo) GetSession(context.Context, string) (*auth.Session, error) { + return &auth.Session{ID: "session", UserID: r.userID, ExpiresAt: time.Now().Add(time.Hour)}, nil +} + +func (agentAuthRepo) DeleteSession(context.Context, string) error { return nil } + +const structureKey = "results/task/output/structure.json" + +const agentStructure = `{ + "source":{"title":"Курс по Go","kind":"audio","duration":"00:42"}, + "sections":[ + {"title":"Введение","subtopics":[{ + "title":"Первый шаг", + "media":{"kind":"audio","start":"00:05","end":"00:35","key":"results/task/media-1.m4a"}, + "slide_keys":["results/task/slide-1.png","results/task/slide-2.png"], + "slide_nums":[1,2], + "content_md":"Абзац первый\n\n\n\nТекст **жирный**\n\n> [!tangent]- Подробнее\n> Тело отступления\n>\n> Вторая строка" + }]}, + {"title":"Практика","subtopics":[{"title":"Разбор","content_md":"\n\nФинальный абзац"}]} + ] +}` + +const legacyStructure = `{ + "source":{"title":"Старая запись","kind":"video","duration":"00:10"}, + "sections":[ + {"title":"С1","subtopics":[{"title":"П1","slide_keys":["results/task/a.png","results/task/b.png"],"content_md":"Текст 1"}]}, + {"title":"С2","subtopics":[{"title":"П2","slide_keys":["results/task/c.png"],"content_md":"Текст 2"}]} + ] +}` + +const longStructure = `{ + "source":{"title":"Длинный курс","kind":"audio","duration":"01:02:03"}, + "sections":[{"title":"Часть","subtopics":[{ + "title":"Кусок", + "media":{"kind":"video","start":"01:00:00","end":"01:02:03","key":"results/task/media-1.mp4"}, + "content_md":"Текст" + }]}] +}` + +// agentLecture — готовая Публичная лекция владельца «owner». +func agentLecture() *LectureMeta { + return &LectureMeta{ + ID: "lecture", + OwnerID: "owner", + Status: "ready", + Visibility: "public", + CoreTaskID: "task", + Title: "Лекция по Go", + SourceKind: "audio", + } +} + +func agentLectureWith(visibility string) *LectureMeta { + lecture := agentLecture() + lecture.Visibility = visibility + return lecture +} + +// newAgentHandler собирает HTTP-хендлер читального зала поверх фейковых +// портов и заданного пользователя ("" — аноним). +func newAgentHandler(t *testing.T, lecture *LectureMeta, viewerID, structure string, opts ...HandlerOption) (http.Handler, *objectStore) { + t.Helper() + store := &objectStore{objects: map[string][]byte{structureKey: []byte(structure)}} + return newAgentHandlerWithStore(t, lecture, viewerID, store, opts...), store +} + +func newAgentHandlerWithStore(t *testing.T, lecture *LectureMeta, viewerID string, store *objectStore, opts ...HandlerOption) http.Handler { + t.Helper() + svc := NewService(handlerRepo{lecture: lecture}, store, handlerPresigner{}, NewMarkdownRenderer(), time.Hour) + r := chi.NewRouter() + authSvc := auth.NewService(agentAuthRepo{userID: viewerID}, nil, time.Hour, false) + r.Use(authSvc.LoadSession) + NewHandlers(svc, nil, opts...).Mount(r) + return r +} + +// agentGet выполняет запрос от имени viewerID ("owner", "stranger" или ""). +func agentGet(handler http.Handler, path, viewerID string, headers map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + for name, value := range headers { + req.Header.Set(name, value) + } + if viewerID != "" { + req.AddCookie(&http.Cookie{Name: "ll_session", Value: "session"}) + } + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + return rec +} + +// wantAgentStatus повторяет правила accessLecture для ожидаемого статуса. +func wantAgentStatus(lecture *LectureMeta, viewerID string) int { + if lecture == nil { + return http.StatusNotFound + } + if lecture.Status != "ready" { + if viewerID == "owner" { + return http.StatusAccepted + } + return http.StatusNotFound + } + if lecture.Visibility == "private" && viewerID != "owner" { + return http.StatusNotFound + } + return http.StatusOK +} + +// TestAgentMarkdownAccessMatrix проверяет права доступа на `.md`-маршруте и на +// основном URL с Accept: text/markdown для всех уровней видимости, статусов и +// зрителей, а также отсутствие чтения хранилища при запрещённом доступе. +func TestAgentMarkdownAccessMatrix(t *testing.T) { + viewers := []string{"", "owner", "stranger"} + visibilities := []string{"private", "unlisted", "public"} + statuses := []string{"processing", "ready"} + paths := []struct { + name string + path string + headers map[string]string + }{ + {name: "md route", path: "/read/lecture.md"}, + {name: "negotiated", path: "/read/lecture", headers: map[string]string{"Accept": "text/markdown"}}, + } + + for _, path := range paths { + for _, visibility := range visibilities { + for _, status := range statuses { + for _, viewerID := range viewers { + name := path.name + "/" + visibility + "/" + status + "/" + viewerName(viewerID) + t.Run(name, func(t *testing.T) { + lecture := agentLectureWith(visibility) + lecture.Status = status + handler, store := newAgentHandler(t, lecture, viewerID, agentStructure) + + rec := agentGet(handler, path.path, viewerID, path.headers) + want := wantAgentStatus(lecture, viewerID) + if rec.Code != want { + t.Fatalf("GET %s = %d, want %d: %s", path.path, rec.Code, want, rec.Body.String()) + } + if want == http.StatusOK { + if got := rec.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" { + t.Fatalf("Content-Type = %q, want text/markdown", got) + } + if len(store.calls) != 1 { + t.Fatalf("GetObject вызван %d раз, want 1: %v", len(store.calls), store.calls) + } + return + } + if len(store.calls) != 0 { + t.Fatalf("GetObject вызван при запрещённом доступе: %v", store.calls) + } + if got := rec.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/plain") { + t.Fatalf("Content-Type ошибки = %q, want text/plain", got) + } + assertSoftError(t, rec.Body.String()) + }) + } + } + } + } +} + +func viewerName(viewerID string) string { + if viewerID == "" { + return "anonymous" + } + return viewerID +} + +// TestAgentMarkdownMissingLecture проверяет 404 на `.md` для несуществующей лекции. +func TestAgentMarkdownMissingLecture(t *testing.T) { + handler, store := newAgentHandler(t, nil, "", agentStructure) + rec := agentGet(handler, "/read/lecture.md", "", nil) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET missing .md = %d, want 404", rec.Code) + } + if len(store.calls) != 0 { + t.Fatalf("GetObject вызван для несуществующей лекции: %v", store.calls) + } + if got := rec.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/plain") { + t.Fatalf("Content-Type = %q, want text/plain", got) + } +} + +// TestAgentMarkdownRouteIsDeterministic проверяет, что явный `.md`-маршрут +// отдаёт Markdown даже браузерным клиентам с Accept: text/html. +func TestAgentMarkdownRouteIsDeterministic(t *testing.T) { + handler, _ := newAgentHandler(t, agentLecture(), "", agentStructure) + headers := map[string]string{ + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36", + } + rec := agentGet(handler, "/read/lecture.md", "", headers) + if rec.Code != http.StatusOK { + t.Fatalf("GET .md = %d, want 200: %s", rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Content-Type"); got != "text/markdown; charset=utf-8" { + t.Fatalf("Content-Type = %q, want text/markdown", got) + } + if !strings.HasPrefix(rec.Body.String(), "# Лекция по Go\n") { + t.Fatalf("тело не начинается с H1 конспекта: %q", rec.Body.String()) + } +} + +// TestHandlersReadContentNegotiation проверяет выбор Markdown/HTML на основном +// URL по Accept и User-Agent, а также обязательный Vary. +func TestHandlersReadContentNegotiation(t *testing.T) { + tests := []struct { + name string + headers map[string]string + wantMarkdown bool + }{ + { + name: "browser html", + headers: map[string]string{"Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Gecko/20100101 Firefox/121.0"}, + }, + { + name: "accept markdown", + headers: map[string]string{"Accept": "text/markdown"}, + wantMarkdown: true, + }, + { + name: "accept x-markdown", + headers: map[string]string{"Accept": "text/x-markdown"}, + wantMarkdown: true, + }, + { + name: "chatgpt user agent", + headers: map[string]string{"User-Agent": "ChatGPT-User/2.0"}, + wantMarkdown: true, + }, + { + name: "claudebot user agent", + headers: map[string]string{"User-Agent": "ClaudeBot/1.0"}, + wantMarkdown: true, + }, + { + name: "curl user agent", + headers: map[string]string{"User-Agent": "curl/8.5.0"}, + wantMarkdown: true, + }, + { + name: "python httpx user agent", + headers: map[string]string{"User-Agent": "python-httpx/0.27.0"}, + wantMarkdown: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + handler, _ := newAgentHandler(t, agentLecture(), "", agentStructure) + rec := agentGet(handler, "/read/lecture", "", tt.headers) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /read/lecture = %d, want 200: %s", rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Vary"); got != "Accept, User-Agent" { + t.Fatalf("Vary = %q, want Accept, User-Agent", got) + } + contentType := rec.Header().Get("Content-Type") + if tt.wantMarkdown { + if contentType != "text/markdown; charset=utf-8" { + t.Fatalf("Content-Type = %q, want text/markdown", contentType) + } + return + } + if contentType != "text/html; charset=utf-8" { + t.Fatalf("Content-Type = %q, want text/html", contentType) + } + if !strings.Contains(rec.Body.String(), `class="ll-reader"`) { + t.Fatal("браузеру должен отдаваться HTML Читального зала") + } + }) + } +} + +// TestAgentMarkdownCacheAndRobots проверяет заголовки кеширования и индексации +// для public, unlisted и private, включая не-200 ответы. +func TestAgentMarkdownCacheAndRobots(t *testing.T) { + tests := []struct { + name string + lecture *LectureMeta + status string + viewerID string + path string + headers map[string]string + storeErr error + wantStatus int + wantCache string + wantRobots string + }{ + { + name: "public md", + lecture: agentLecture(), + path: "/read/lecture.md", + wantStatus: http.StatusOK, + wantCache: "public, max-age=60", + }, + { + name: "public negotiated", + lecture: agentLecture(), + path: "/read/lecture", + headers: map[string]string{"Accept": "text/markdown"}, + wantStatus: http.StatusOK, + wantCache: "public, max-age=60", + }, + { + name: "unlisted md", + lecture: agentLectureWith("unlisted"), + path: "/read/lecture.md", + wantStatus: http.StatusOK, + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "private owner md", + lecture: agentLectureWith("private"), + viewerID: "owner", + path: "/read/lecture.md", + wantStatus: http.StatusOK, + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "private owner processing", + lecture: agentLectureWith("private"), + status: "processing", + viewerID: "owner", + path: "/read/lecture.md", + wantStatus: http.StatusAccepted, + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "unlisted owner processing", + lecture: agentLectureWith("unlisted"), + status: "processing", + viewerID: "owner", + path: "/read/lecture.md", + wantStatus: http.StatusAccepted, + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "public owner processing", + lecture: agentLectureWith("public"), + status: "processing", + viewerID: "owner", + path: "/read/lecture.md", + wantStatus: http.StatusAccepted, + }, + { + name: "unlisted core unavailable", + lecture: agentLectureWith("unlisted"), + path: "/read/lecture.md", + storeErr: errors.New("ошибка хранилища"), + wantStatus: http.StatusBadGateway, + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "public core unavailable", + lecture: agentLecture(), + path: "/read/lecture.md", + storeErr: errors.New("ошибка хранилища"), + wantStatus: http.StatusBadGateway, + }, + { + name: "missing lecture", + path: "/read/lecture.md", + wantStatus: http.StatusNotFound, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := &objectStore{objects: map[string][]byte{structureKey: []byte(agentStructure)}} + if tt.storeErr != nil { + store.errs = map[string]error{structureKey: tt.storeErr} + } + lecture := tt.lecture + if lecture != nil && tt.status != "" { + lecture.Status = tt.status + } + handler := newAgentHandlerWithStore(t, lecture, tt.viewerID, store) + rec := agentGet(handler, tt.path, tt.viewerID, tt.headers) + + if rec.Code != tt.wantStatus { + t.Fatalf("GET %s = %d, want %d", tt.path, rec.Code, tt.wantStatus) + } + if got := rec.Header().Get("Cache-Control"); got != tt.wantCache { + t.Fatalf("Cache-Control = %q, want %q", got, tt.wantCache) + } + if got := rec.Header().Get("X-Robots-Tag"); got != tt.wantRobots { + t.Fatalf("X-Robots-Tag = %q, want %q", got, tt.wantRobots) + } + if tt.wantStatus >= http.StatusBadRequest { + assertSoftError(t, rec.Body.String()) + } + }) + } +} + +// TestAgentMarkdownContent проверяет точность Агентского представления: +// метаданные, оглавление, заголовки, таймкод, инлайн-Слайд, галерею и +// преобразование callout'ов без медиа и HTML-обвязки. +func TestAgentMarkdownContent(t *testing.T) { + handler, _ := newAgentHandler(t, agentLecture(), "", agentStructure, WithBaseOrigin("https://lecture.example/")) + rec := agentGet(handler, "/read/lecture.md", "", nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET .md = %d, want 200: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + + inlineSlide := "![Слайд 1: Первый шаг](https://lecture.example/read/lecture/slides/1)" + gallerySlide := "![Слайд 2: Первый шаг](https://lecture.example/read/lecture/slides/2)" + for _, want := range []string{ + "# Лекция по Go", + "- Источник: Курс по Go", + "- Тип источника: Аудио", + "- Длительность: 00:42", + "- Канонический URL: https://lecture.example/read/lecture", + "## Содержание", + "- 01. Введение", + " - 1.1 Первый шаг", + "- 02. Практика", + " - 2.1 Разбор", + "## 01. Введение", + "### 1.1 Первый шаг", + "[00:05 – 00:35]", + inlineSlide, + gallerySlide, + "> **Отступление от темы: Подробнее**", + "> Тело отступления", + "> Вторая строка", + "Финальный абзац", + } { + if !strings.Contains(body, want) { + t.Errorf("в Агентском представлении отсутствует %q\n%s", want, body) + } + } + + // Аудио- и видеофрагменты, ключи хранилища и сырой HTML не попадают в ответ. + for _, forbidden := range []string{"= 0 && first < second && second < nextSection && nextSection < third) { + t.Errorf("нарушен порядок нумерации Слайдов по Разделам и Подтемам\n%s", body) + } +} + +// TestAgentMarkdownOriginFallback проверяет fallback origin из +// X-Forwarded-Proto + Host, когда базовая конфигурация отсутствует. +func TestAgentMarkdownOriginFallback(t *testing.T) { + handler, _ := newAgentHandler(t, agentLecture(), "", agentStructure) + req := httptest.NewRequest(http.MethodGet, "/read/lecture.md", nil) + req.Host = "cdn.example.test" + req.Header.Set("X-Forwarded-Proto", "https") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("GET .md = %d, want 200: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + for _, want := range []string{ + "- Канонический URL: https://cdn.example.test/read/lecture", + "![Слайд 1: Первый шаг](https://cdn.example.test/read/lecture/slides/1)", + } { + if !strings.Contains(body, want) { + t.Errorf("в Агентском представлении отсутствует %q\n%s", want, body) + } + } +} + +// TestAgentMarkdownCalloutWithoutTitle проверяет цитату callout'а без +// пользовательского заголовка: остаётся только локализованный тип. +func TestAgentMarkdownCalloutWithoutTitle(t *testing.T) { + const structure = `{ + "source":{"title":"Источник","kind":"audio","duration":"00:10"}, + "sections":[{"title":"Раздел","subtopics":[ + { + "title":"Подтема", + "slide_keys":["results/task/s1.png"], + "slide_nums":[1], + "content_md":"Текст\n\n\n\n> [!note]\n> Тело заметки\n\n> [!warning]+ Важно\n> Осторожно\n\n> [!quote] Только заголовок" + }, + { + "title":"Вторая подтема", + "slide_keys":["results/task/s2.png"], + "slide_nums":[2], + "content_md":"Второй текст" + } + ]}] + }` + handler, _ := newAgentHandler(t, agentLecture(), "", structure) + body := agentGet(handler, "/read/lecture.md", "", nil).Body.String() + + for _, want := range []string{ + "> **Заметка**", + "> Тело заметки", + "> **Внимание: Важно**", + "> Осторожно", + "> **Цитата: Только заголовок**\n\n", + "![Слайд 2: Вторая подтема]", + } { + if !strings.Contains(body, want) { + t.Errorf("в Агентском представлении отсутствует %q\n%s", want, body) + } + } + if strings.Contains(body, "![Слайд 2: Подтема]") { + t.Errorf("чужой инлайн-маркер слайда не должен вставляться в первую подтему:\n%s", body) + } + if strings.Contains(body, "> **Цитата: Только заголовок**\n>") { + t.Errorf("callout без тела не должен порождать пустую строку цитаты:\n%s", body) + } + if strings.Contains(body, " и действие MD в шапке. +func TestReaderHTMLAlternateMarkdownLink(t *testing.T) { + handler, _ := newAgentHandler(t, agentLecture(), "", agentStructure) + headers := map[string]string{ + "Accept": "text/html,application/xhtml+xml,*/*;q=0.8", + "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15", + } + rec := agentGet(handler, "/read/lecture", "", headers) + if rec.Code != http.StatusOK { + t.Fatalf("GET /read/lecture = %d, want 200: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + for _, want := range []string{ + ``, + `href="/read/lecture.md"`, + `title="Агентское представление (Markdown)"`, + } { + if !strings.Contains(body, want) { + t.Errorf("в HTML Читального зала отсутствует %q", want) + } + } +} + +// TestAgentMarkdownEscapesBracketsAndNewlines проверяет экранирование скобок в +// названиях подтем для ссылок на слайды и нормализацию переводов строк. +func TestAgentMarkdownEscapesBracketsAndNewlines(t *testing.T) { + const structure = `{ + "source":{"title":"Пост\nсо второй строкой","kind":"video","duration":"00:15"}, + "sections":[{"title":"Раздел\n1","subtopics":[{ + "title":"Полуинтервалы [l, r)", + "slide_keys":["results/task/s1.png"], + "slide_nums":[1], + "content_md":"Текст\n\n" + }]}] + }` + lecture := agentLecture() + lecture.Title = "Алгоритмы\nбаза" + handler, _ := newAgentHandler(t, lecture, "", structure, WithBaseOrigin("https://lecture.example")) + body := agentGet(handler, "/read/lecture.md", "", nil).Body.String() + + for _, want := range []string{ + "# Алгоритмы база\n", + "- Источник: Пост со второй строкой\n", + "- 01. Раздел 1\n", + " - 1.1 Полуинтервалы [l, r)\n", + `![Слайд 1: Полуинтервалы \[l, r)](https://lecture.example/read/lecture/slides/1)`, + } { + if !strings.Contains(body, want) { + t.Errorf("в Агентском представлении отсутствует %q:\n%s", want, body) + } + } +} diff --git a/internal/reader/handlers.go b/internal/reader/handlers.go index 5f7c034..c05c195 100644 --- a/internal/reader/handlers.go +++ b/internal/reader/handlers.go @@ -6,6 +6,8 @@ import ( "io" "log" "net/http" + "strconv" + "strings" "github.com/LectureLog/lecturelog-web/internal/auth" "github.com/LectureLog/lecturelog-web/internal/web" @@ -21,23 +23,59 @@ type ExportURLProvider interface { type Handlers struct { svc *Service export ExportURLProvider + // baseOrigin — внешний origin платформы (scheme://host) для абсолютных + // ссылок в Агентском представлении. Пусто — origin выводится из запроса. + baseOrigin string +} + +// HandlerOption — функциональная опция HTTP-хендлеров читального зала. +type HandlerOption func(*Handlers) + +// WithBaseOrigin задаёт внешний origin платформы (обычно извлекается из +// PLATFORM_CALLBACK_URL) для абсолютных ссылок в Агентском представлении. +func WithBaseOrigin(origin string) HandlerOption { + return func(h *Handlers) { + h.baseOrigin = origin + } } // NewHandlers создаёт HTTP-хендлеры читального зала. -func NewHandlers(svc *Service, export ExportURLProvider) *Handlers { - return &Handlers{svc: svc, export: export} +func NewHandlers(svc *Service, export ExportURLProvider, opts ...HandlerOption) *Handlers { + h := &Handlers{svc: svc, export: export} + for _, opt := range opts { + opt(h) + } + return h } // Mount регистрирует публичные маршруты читального зала. func (h *Handlers) Mount(r chi.Router) { r.Get("/read/{id}", h.handleRead) + r.Get("/read/{id}.md", h.handleReadMarkdown) + r.Get("/read/{id}/slides/{n}", h.handleSlide) r.Get("/read/{id}/export", h.handleExport) } func (h *Handlers) handleRead(w http.ResponseWriter, r *http.Request) { lectureID := chi.URLParam(r, "id") + // Ответ зависит от Accept и User-Agent — сообщаем об этом кешам, + // сохраняя уже выставленные Vary (например, Cookie от CSRF-middleware). + setVaryAcceptUserAgent(w) + + // chi разбирает `{id}.md` как параметр `{id}` и статический суффикс, но + // страховка на случай иного порядка матчинга: `.md` всегда Markdown. + if strings.HasSuffix(lectureID, ".md") { + h.serveReadMarkdown(w, r, strings.TrimSuffix(lectureID, ".md")) + return + } + if web.WantsMarkdown(r) { + h.serveReadMarkdown(w, r, lectureID) + return + } + viewerID := viewerID(r.Context()) view, err := h.svc.Load(r.Context(), lectureID, viewerID) + setNonPublicHeaders(w, view.Visibility) if err != nil { h.writeLoadError(w, err) return @@ -45,11 +83,73 @@ func (h *Handlers) handleRead(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") data := web.NewLayoutData(r.Context(), view.Title) + data.NoIndex = view.Visibility != "public" if err := web.ReaderPage(data, readerToVM(view)).Render(r.Context(), w); err != nil { log.Printf("reader: render: %v", err) } } +// handleReadMarkdown детерминированно отдаёт Агентское представление +// Конспекта независимо от Accept и User-Agent. +func (h *Handlers) handleReadMarkdown(w http.ResponseWriter, r *http.Request) { + h.serveReadMarkdown(w, r, chi.URLParam(r, "id")) +} + +// serveReadMarkdown проверяет доступ и отдаёт текст Агентского представления +// с заголовками кеширования и индексации по видимости Лекции. +func (h *Handlers) serveReadMarkdown(w http.ResponseWriter, r *http.Request, lectureID string) { + origin := web.ResolveOrigin(h.baseOrigin, r) + doc, err := h.svc.LoadMarkdown(r.Context(), lectureID, viewerID(r.Context()), origin) + + setNonPublicHeaders(w, doc.Visibility) + if err != nil { + status, message := resolveLoadError(err, "Лекция не найдена", "markdown") + writeTextMessage(w, status, message) + return + } + if doc.Visibility == "public" { + w.Header().Set("Cache-Control", "public, max-age=60") + } + + w.Header().Set("Content-Type", "text/markdown; charset=utf-8") + _, _ = io.WriteString(w, doc.Markdown) +} + +// handleSlide раздаёт байты Слайда напрямую с домена платформы. +func (h *Handlers) handleSlide(w http.ResponseWriter, r *http.Request) { + num, parseErr := strconv.Atoi(chi.URLParam(r, "n")) + if parseErr != nil || num <= 0 { + num = 0 + } + + slide, err := h.svc.LoadSlide(r.Context(), chi.URLParam(r, "id"), viewerID(r.Context()), num) + setNonPublicHeaders(w, slide.Visibility) + if err != nil { + h.writeSlideError(w, err) + return + } + + w.Header().Set("Content-Type", slide.ContentType) + if slide.Visibility == "public" { + w.Header().Set("Cache-Control", "public, max-age=3600") + } + _, _ = w.Write(slide.Bytes) +} + +// setNonPublicHeaders выставляет запрет индексации и кеширования для +// не-публичных Лекций (unlisted и private). +func setNonPublicHeaders(w http.ResponseWriter, visibility string) { + if visibility != "" && visibility != "public" { + w.Header().Set("X-Robots-Tag", "noindex, nofollow") + w.Header().Set("Cache-Control", "private, no-store") + } +} + +// setVaryAcceptUserAgent делегирует выставление Vary: Accept, User-Agent в пакет web. +func setVaryAcceptUserAgent(w http.ResponseWriter) { + web.SetVaryAcceptUserAgent(w) +} + func (h *Handlers) handleExport(w http.ResponseWriter, r *http.Request) { taskID, err := h.svc.AccessTaskID(r.Context(), chi.URLParam(r, "id"), viewerID(r.Context())) if err != nil { @@ -72,28 +172,48 @@ func (h *Handlers) handleExport(w http.ResponseWriter, r *http.Request) { } func (h *Handlers) writeLoadError(w http.ResponseWriter, err error) { + status, message := resolveLoadError(err, "Лекция не найдена", "request") + writeMessage(w, status, message) +} + +func writeMessage(w http.ResponseWriter, status int, message string) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + _, _ = io.WriteString(w, "

"+message+"

") +} + +// writeTextMessage отправляет лаконичный текстовый ответ без HTML-обвязки. +func writeTextMessage(w http.ResponseWriter, status int, message string) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.WriteHeader(status) + _, _ = io.WriteString(w, message+"\n") +} + +// writeSlideError отдаёт текстовую ошибку раздачи Слайда, не раскрывая +// внутренние пути и ошибки хранилища. +func (h *Handlers) writeSlideError(w http.ResponseWriter, err error) { + status, message := resolveLoadError(err, "Слайд не найден", "slide") + writeTextMessage(w, status, message) +} + +// resolveLoadError отображает доменную ошибку чтения в HTTP-статус и безопасное сообщение. +func resolveLoadError(err error, notFoundMessage, logScope string) (int, string) { switch { case errors.Is(err, ErrNotFound): - writeMessage(w, http.StatusNotFound, "Лекция не найдена") + return http.StatusNotFound, notFoundMessage case errors.Is(err, ErrNotReady): - writeMessage(w, http.StatusAccepted, "Лекция ещё обрабатывается") + return http.StatusAccepted, "Лекция ещё обрабатывается" case errors.Is(err, ErrCoreUnavailable): // Логируем причину: молчаливое проглатывание уже раз скрыло // расхождение ключа structure.json с реальным путём выхода core. - log.Printf("reader: core unavailable: %v", err) - writeMessage(w, http.StatusBadGateway, "Результат обработки временно недоступен, попробуйте позже") + log.Printf("reader: %s core unavailable: %v", logScope, err) + return http.StatusBadGateway, "Результат обработки временно недоступен, попробуйте позже" default: - log.Printf("reader: request: %v", err) - writeMessage(w, http.StatusInternalServerError, "Внутренняя ошибка") + log.Printf("reader: %s: %v", logScope, err) + return http.StatusInternalServerError, "Внутренняя ошибка" } } -func writeMessage(w http.ResponseWriter, status int, message string) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(status) - _, _ = io.WriteString(w, "

"+message+"

") -} - func viewerID(ctx context.Context) string { user := auth.UserFromContext(ctx) if user == nil { @@ -103,7 +223,7 @@ func viewerID(ctx context.Context) string { } func readerToVM(view ReaderView) web.ReaderVM { - vm := web.ReaderVM{LectureID: view.LectureID, Title: view.Title, SourceTitle: view.SourceTitle, SourceKind: view.SourceKind, Duration: view.Duration, IsOwner: view.IsOwner, Sections: make([]web.ReaderSectionVM, 0, len(view.Sections))} + vm := web.ReaderVM{LectureID: view.LectureID, Title: view.Title, SourceTitle: view.SourceTitle, SourceKind: view.SourceKind, Duration: view.Duration, IsOwner: view.IsOwner, Visibility: view.Visibility, Sections: make([]web.ReaderSectionVM, 0, len(view.Sections))} for _, section := range view.Sections { sectionVM := web.ReaderSectionVM{Number: section.Number, Title: section.Title, Subtopics: make([]web.ReaderSubtopicVM, 0, len(section.Subtopics))} for _, subtopic := range section.Subtopics { diff --git a/internal/reader/handlers_test.go b/internal/reader/handlers_test.go index 7649abc..ff1f1af 100644 --- a/internal/reader/handlers_test.go +++ b/internal/reader/handlers_test.go @@ -1,10 +1,12 @@ package reader import ( + "bytes" "context" "errors" "net/http" "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -18,6 +20,22 @@ const handlerStructure = `{ "sections":[{"title":"Тема","subtopics":[{"title":"Подтема","content_md":"Текст"}]}] }` +const slideStructure = `{ + "source":{"title":"Аудиолекция","kind":"audio","duration":42}, + "sections":[{"title":"Тема","subtopics":[{ + "title":"Подтема", + "slide_keys":["results/task/slide-1.png","results/task/slide-2.jpg","results/task/slide-3.webp"], + "slide_nums":[1,2,3], + "content_md":"Текст" + }]}] +}` + +var ( + pngSlideBytes = []byte("\x89PNG\r\n\x1a\nslide-1") + jpegSlideBytes = []byte("\xff\xd8\xff\xe0slide-2") + webpSlideBytes = []byte("RIFF\x00\x00\x00\x00WEBPslide-3") +) + type handlerRepo struct { lecture *LectureMeta } @@ -111,6 +129,31 @@ func assertSoftError(t *testing.T, body string) { } } +// objectStore отдаёт объекты по ключам и запоминает обращения. +type objectStore struct { + objects map[string][]byte + errs map[string]error + calls []string +} + +func (s *objectStore) GetObject(_ context.Context, key string) ([]byte, error) { + s.calls = append(s.calls, key) + if err, ok := s.errs[key]; ok { + return nil, err + } + return s.objects[key], nil +} + +func newSlideHandler(t *testing.T, lecture *LectureMeta, store *objectStore) http.Handler { + t.Helper() + svc := NewService(handlerRepo{lecture: lecture}, store, handlerPresigner{}, NewMarkdownRenderer(), time.Hour) + r := chi.NewRouter() + authSvc := auth.NewService(handlerAuthRepo{}, nil, time.Hour, false) + r.Use(authSvc.LoadSession) + NewHandlers(svc, nil).Mount(r) + return r +} + func TestHandlersReadPublicReadyAnonymous(t *testing.T) { rec := requestReader(newReaderHandler(t, readerLecture("ready", "public"), nil, nil), "/read/lecture", false) if rec.Code != http.StatusOK { @@ -119,6 +162,77 @@ func TestHandlersReadPublicReadyAnonymous(t *testing.T) { if !strings.Contains(rec.Body.String(), "Подтема") { t.Fatalf("страница не содержит раздел: %s", rec.Body.String()) } + // Публичная лекция индексируется и не запрещает кеширование. + if got := rec.Header().Get("X-Robots-Tag"); got != "" { + t.Errorf("X-Robots-Tag публичной лекции = %q, want пусто", got) + } + if got := rec.Header().Get("Cache-Control"); got != "" { + t.Errorf("Cache-Control публичной лекции = %q, want пусто", got) + } + if strings.Contains(rec.Body.String(), `name="robots"`) { + t.Error("публичная лекция не должна содержать meta robots") + } +} + +// TestHandlersReadUnlistedAnonymous проверяет чтение unlisted-лекции анонимом: +// 200, доступ по прямой ссылке и запрет индексации/кеширования. +func TestHandlersReadUnlistedAnonymous(t *testing.T) { + rec := requestReader(newReaderHandler(t, readerLecture("ready", "unlisted"), nil, nil), "/read/lecture", false) + if rec.Code != http.StatusOK { + t.Fatalf("GET unlisted /read/lecture = %d, want 200: %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "Подтема") { + t.Fatalf("страница не содержит раздел: %s", rec.Body.String()) + } + assertNoIndexHeaders(t, rec) +} + +// TestHandlersReadUnlistedProcessingHidden проверяет, что неготовая unlisted-лекция +// не открывается анониму и отдаёт 202 владельцу. +func TestHandlersReadUnlistedProcessingHidden(t *testing.T) { + handler := newReaderHandler(t, readerLecture("processing", "unlisted"), nil, nil) + + anonymous := requestReader(handler, "/read/lecture", false) + if anonymous.Code != http.StatusNotFound { + t.Fatalf("GET unlisted processing анонимом = %d, want 404", anonymous.Code) + } + assertSoftError(t, anonymous.Body.String()) + + owner := requestReader(handler, "/read/lecture", true) + if owner.Code != http.StatusAccepted { + t.Fatalf("GET unlisted processing владельцем = %d, want 202", owner.Code) + } + if got := owner.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" { + t.Errorf("X-Robots-Tag (202 unlisted) = %q, want noindex, nofollow", got) + } + if got := owner.Header().Get("Cache-Control"); got != "private, no-store" { + t.Errorf("Cache-Control (202 unlisted) = %q, want private, no-store", got) + } + assertSoftError(t, owner.Body.String()) +} + +// TestHandlersReadPrivateOwnerNoIndex проверяет, что владелец читает свою +// личную лекцию, но страница закрыта от индексации и кеша. +func TestHandlersReadPrivateOwnerNoIndex(t *testing.T) { + rec := requestReader(newReaderHandler(t, readerLecture("ready", "private"), nil, nil), "/read/lecture", true) + if rec.Code != http.StatusOK { + t.Fatalf("GET private /read/lecture владельцем = %d, want 200", rec.Code) + } + assertNoIndexHeaders(t, rec) +} + +// assertNoIndexHeaders проверяет пару заголовков запрета индексации и метатег в . +func assertNoIndexHeaders(t *testing.T, rec *httptest.ResponseRecorder) { + t.Helper() + if got := rec.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" { + t.Errorf("X-Robots-Tag = %q, want noindex, nofollow", got) + } + if got := rec.Header().Get("Cache-Control"); got != "private, no-store" { + t.Errorf("Cache-Control = %q, want private, no-store", got) + } + if !strings.Contains(rec.Body.String(), ``) { + t.Error("в ожидается meta robots noindex, nofollow") + } } func TestHandlersReadNotFound(t *testing.T) { @@ -167,6 +281,12 @@ func TestHandlersExport(t *testing.T) { } assertSoftError(t, rec.Body.String()) }) + t.Run("unlisted anonymous redirects to signed archive", func(t *testing.T) { + rec := requestReader(newReaderHandler(t, readerLecture("ready", "unlisted"), nil, handlerExport{url: "https://signed"}), "/read/lecture/export", false) + if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://signed" { + t.Fatalf("GET unlisted /read/lecture/export = %d Location=%q, want 302", rec.Code, rec.Header().Get("Location")) + } + }) t.Run("private anonymous is hidden before provider", func(t *testing.T) { export := &forbiddenExport{t: t} rec := requestReader(newReaderHandler(t, readerLecture("ready", "private"), nil, export), "/read/lecture/export", false) @@ -188,3 +308,294 @@ func TestHandlersExport(t *testing.T) { } }) } + +func TestHandlersSlideServesImage(t *testing.T) { + objects := map[string][]byte{ + "results/task/output/structure.json": []byte(slideStructure), + "results/task/slide-1.png": pngSlideBytes, + "results/task/slide-2.jpg": jpegSlideBytes, + "results/task/slide-3.webp": webpSlideBytes, + } + + tests := []struct { + name string + visibility string + owner bool + path string + wantBody []byte + wantType string + wantCache string + wantRobots string + }{ + { + name: "owner private png", + visibility: "private", + owner: true, + path: "/read/lecture/slides/1", + wantBody: pngSlideBytes, + wantType: "image/png", + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "anonymous unlisted jpeg", + visibility: "unlisted", + path: "/read/lecture/slides/2", + wantBody: jpegSlideBytes, + wantType: "image/jpeg", + wantCache: "private, no-store", + wantRobots: "noindex, nofollow", + }, + { + name: "anonymous public webp", + visibility: "public", + path: "/read/lecture/slides/3", + wantBody: webpSlideBytes, + wantType: "image/webp", + wantCache: "public, max-age=3600", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := &objectStore{objects: objects} + handler := newSlideHandler(t, readerLecture("ready", tt.visibility), store) + rec := requestReader(handler, tt.path, tt.owner) + + if rec.Code != http.StatusOK { + t.Fatalf("GET %s = %d, want 200: %s", tt.path, rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Content-Type"); got != tt.wantType { + t.Fatalf("Content-Type = %q, want %q", got, tt.wantType) + } + if got := rec.Header().Get("Cache-Control"); got != tt.wantCache { + t.Fatalf("Cache-Control = %q, want %q", got, tt.wantCache) + } + if got := rec.Header().Get("X-Robots-Tag"); got != tt.wantRobots { + t.Fatalf("X-Robots-Tag = %q, want %q", got, tt.wantRobots) + } + if !bytes.Equal(rec.Body.Bytes(), tt.wantBody) { + t.Fatalf("тело ответа = %q, want %q", rec.Body.Bytes(), tt.wantBody) + } + }) + } +} + +func TestHandlersSlideDetectsTypeByBytes(t *testing.T) { + structure := `{ + "source":{"title":"Лекция","kind":"audio","duration":60}, + "sections":[{"title":"Тема","subtopics":[{ + "title":"Подтема", + "slide_keys":["results/task/frame"], + "slide_nums":[1], + "content_md":"Текст" + }]}] + }` + store := &objectStore{objects: map[string][]byte{ + "results/task/output/structure.json": []byte(structure), + "results/task/frame": pngSlideBytes, + }} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/1", false) + + if rec.Code != http.StatusOK { + t.Fatalf("GET slide = %d, want 200: %s", rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Content-Type"); got != "image/png" { + t.Fatalf("Content-Type = %q, want image/png", got) + } +} + +func TestHandlersSlideNumbering(t *testing.T) { + explicitStructure := `{ + "source":{"title":"Л","kind":"audio","duration":60}, + "sections":[{"title":"С","subtopics":[{ + "title":"П", + "slide_keys":["results/task/a.png","results/task/b.png"], + "slide_nums":[3,4], + "content_md":"Текст" + }]}] + }` + legacyStructure := `{ + "source":{"title":"Л","kind":"audio","duration":60}, + "sections":[ + {"title":"С1","subtopics":[{"title":"П1","slide_keys":["results/task/a.png","results/task/b.png"],"content_md":"Текст"}]}, + {"title":"С2","subtopics":[{"title":"П2","slide_keys":["results/task/c.png"],"content_md":"Текст"}]} + ] + }` + mixedStructure := `{ + "source":{"title":"Л","kind":"audio","duration":60}, + "sections":[ + {"title":"С1","subtopics":[{"title":"П1","slide_keys":["results/task/a.png"],"slide_nums":[2],"content_md":"Текст"}]}, + {"title":"С2","subtopics":[{"title":"П2","slide_keys":["results/task/b.png","results/task/c.png"],"content_md":"Текст"}]} + ] + }` + + tests := []struct { + name string + structure string + keys []string + want map[int]string + missing int + }{ + { + name: "explicit slide nums", + structure: explicitStructure, + keys: []string{"results/task/a.png", "results/task/b.png"}, + want: map[int]string{3: "results/task/a.png", 4: "results/task/b.png"}, + missing: 1, + }, + { + name: "legacy without slide nums", + structure: legacyStructure, + keys: []string{"results/task/a.png", "results/task/b.png", "results/task/c.png"}, + want: map[int]string{1: "results/task/a.png", 2: "results/task/b.png", 3: "results/task/c.png"}, + missing: 4, + }, + { + name: "mixed numbers without collisions", + structure: mixedStructure, + keys: []string{"results/task/a.png", "results/task/b.png", "results/task/c.png"}, + want: map[int]string{2: "results/task/a.png", 3: "results/task/b.png", 4: "results/task/c.png"}, + missing: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + objects := map[string][]byte{"results/task/output/structure.json": []byte(tt.structure)} + for _, key := range tt.keys { + objects[key] = []byte(key) + } + for num, key := range tt.want { + store := &objectStore{objects: objects} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/"+strconv.Itoa(num), false) + if rec.Code != http.StatusOK { + t.Fatalf("GET slide %d = %d, want 200: %s", num, rec.Code, rec.Body.String()) + } + if !bytes.Equal(rec.Body.Bytes(), []byte(key)) { + t.Fatalf("slide %d = %q, want %q", num, rec.Body.Bytes(), key) + } + } + + store := &objectStore{objects: objects} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/"+strconv.Itoa(tt.missing), false) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET missing slide %d = %d, want 404", tt.missing, rec.Code) + } + }) + } +} + +func TestHandlersSlideDeniedDoesNotReadStore(t *testing.T) { + tests := []struct { + name string + lecture *LectureMeta + owner bool + wantStatus int + wantCache string + wantRobots string + }{ + {name: "private anonymous", lecture: readerLecture("ready", "private"), wantStatus: http.StatusNotFound}, + {name: "private other user", lecture: &LectureMeta{ID: "lecture", OwnerID: "another-owner", Status: "ready", Visibility: "private", CoreTaskID: "task"}, owner: true, wantStatus: http.StatusNotFound}, + {name: "processing anonymous", lecture: readerLecture("processing", "private"), wantStatus: http.StatusNotFound}, + {name: "unlisted processing anonymous", lecture: readerLecture("processing", "unlisted"), wantStatus: http.StatusNotFound}, + {name: "public processing anonymous", lecture: readerLecture("processing", "public"), wantStatus: http.StatusNotFound}, + {name: "private processing owner", lecture: readerLecture("processing", "private"), owner: true, wantStatus: http.StatusAccepted, wantCache: "private, no-store", wantRobots: "noindex, nofollow"}, + {name: "unlisted processing owner", lecture: readerLecture("processing", "unlisted"), owner: true, wantStatus: http.StatusAccepted, wantCache: "private, no-store", wantRobots: "noindex, nofollow"}, + {name: "public processing owner", lecture: readerLecture("processing", "public"), owner: true, wantStatus: http.StatusAccepted}, + {name: "missing lecture", wantStatus: http.StatusNotFound}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := &objectStore{objects: map[string][]byte{ + "results/task/output/structure.json": []byte(slideStructure), + "results/task/slide-1.png": pngSlideBytes, + }} + rec := requestReader(newSlideHandler(t, tt.lecture, store), "/read/lecture/slides/1", tt.owner) + if rec.Code != tt.wantStatus { + t.Fatalf("GET denied slide = %d, want %d", rec.Code, tt.wantStatus) + } + if len(store.calls) != 0 { + t.Fatalf("GetObject вызван при запрещённом доступе: %v", store.calls) + } + if got := rec.Header().Get("Cache-Control"); got != tt.wantCache { + t.Fatalf("Cache-Control = %q, want %q", got, tt.wantCache) + } + if got := rec.Header().Get("X-Robots-Tag"); got != tt.wantRobots { + t.Fatalf("X-Robots-Tag = %q, want %q", got, tt.wantRobots) + } + assertSoftError(t, rec.Body.String()) + }) + } +} + +func TestHandlersSlideInvalidNumber(t *testing.T) { + for _, n := range []string{"0", "-1", "abc"} { + t.Run(n, func(t *testing.T) { + store := &objectStore{objects: map[string][]byte{ + "results/task/output/structure.json": []byte(slideStructure), + "results/task/slide-1.png": pngSlideBytes, + }} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/"+n, false) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET slide %q = %d, want 404", n, rec.Code) + } + if len(store.calls) != 0 { + t.Fatalf("GetObject вызван для некорректного номера: %v", store.calls) + } + if got := rec.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/plain") { + t.Fatalf("Content-Type = %q, want text/plain", got) + } + assertSoftError(t, rec.Body.String()) + }) + } +} + +func TestHandlersSlideUnknownNumberDoesNotReadSlideObject(t *testing.T) { + store := &objectStore{objects: map[string][]byte{ + "results/task/output/structure.json": []byte(slideStructure), + "results/task/slide-1.png": pngSlideBytes, + }} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/999", false) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET unknown slide = %d, want 404", rec.Code) + } + for _, call := range store.calls { + if strings.HasPrefix(call, "results/task/slide-") { + t.Fatalf("GetObject прочитал объект слайда для отсутствующего номера: %v", store.calls) + } + } +} + +func TestHandlersSlideCoreUnavailable(t *testing.T) { + t.Run("structure", func(t *testing.T) { + store := &objectStore{errs: map[string]error{ + "results/task/output/structure.json": errors.New("ошибка хранилища"), + }} + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/1", false) + if rec.Code != http.StatusBadGateway { + t.Fatalf("GET slide without structure = %d, want 502", rec.Code) + } + assertSoftError(t, rec.Body.String()) + }) + + t.Run("slide object", func(t *testing.T) { + store := &objectStore{ + objects: map[string][]byte{"results/task/output/structure.json": []byte(slideStructure)}, + errs: map[string]error{"results/task/slide-1.png": errors.New("ошибка хранилища")}, + } + handler := newSlideHandler(t, readerLecture("ready", "public"), store) + rec := requestReader(handler, "/read/lecture/slides/1", false) + if rec.Code != http.StatusBadGateway { + t.Fatalf("GET slide with failed object = %d, want 502", rec.Code) + } + assertSoftError(t, rec.Body.String()) + }) +} diff --git a/internal/reader/reader.go b/internal/reader/reader.go index 451a8ce..1666552 100644 --- a/internal/reader/reader.go +++ b/internal/reader/reader.go @@ -55,6 +55,9 @@ type ReaderView struct { Duration int Sections []ViewSection IsOwner bool + // Visibility — уровень видимости лекции: private|unlisted|public. + // HTTP-слой по нему решает, закрывать ли страницу от индексации. + Visibility string } // ViewSection — раздел читального зала. diff --git a/internal/reader/service.go b/internal/reader/service.go index a9f5525..f6f488e 100644 --- a/internal/reader/service.go +++ b/internal/reader/service.go @@ -12,19 +12,15 @@ import ( func (s *Service) Load(ctx context.Context, lectureID, viewerID string) (ReaderView, error) { lecture, isOwner, err := s.accessLecture(ctx, lectureID, viewerID) if err != nil { + if lecture != nil { + return ReaderView{Visibility: lecture.Visibility}, err + } return ReaderView{}, err } - // Ядро кладёт выход задачи под results//output/ (см. контракт пути - // выхода core). Сегмент output/ обязателен, иначе GetObject вернёт NoSuchKey. - structureKey := "results/" + lecture.CoreTaskID + "/output/structure.json" - b, err := s.store.GetObject(ctx, structureKey) + structure, err := s.loadStructure(ctx, lecture.CoreTaskID) if err != nil { - return ReaderView{}, fmt.Errorf("%w: прочитать structure.json: %v", ErrCoreUnavailable, err) - } - structure, err := ParseStructure(b) - if err != nil { - return ReaderView{}, err + return ReaderView{Visibility: lecture.Visibility}, err } // Ядро может не знать названия источника (title: null) — показываем @@ -42,6 +38,7 @@ func (s *Service) Load(ctx context.Context, lectureID, viewerID string) (ReaderV Duration: int(structure.Source.Duration), Sections: make([]ViewSection, 0, len(structure.Sections)), IsOwner: isOwner, + Visibility: lecture.Visibility, } for sectionIndex, section := range structure.Sections { viewSection := ViewSection{ @@ -72,6 +69,10 @@ func (s *Service) AccessTaskID(ctx context.Context, lectureID, viewerID string) } // accessLecture централизует проверку доступа для чтения и экспорта. +// Готовая лекция открыта владельцу при любой видимости, а всем остальным +// (включая анонимов) — при unlisted и public. Личная лекция (private) для +// не-владельца неотличима от несуществующей: возврат в private мгновенно +// закрывает внешний доступ к /read/{id} и /read/{id}/export. func (s *Service) accessLecture(ctx context.Context, lectureID, viewerID string) (*LectureMeta, bool, error) { lecture, err := s.repo.FindByID(ctx, lectureID) if err != nil { @@ -84,16 +85,30 @@ func (s *Service) accessLecture(ctx context.Context, lectureID, viewerID string) isOwner := viewerID != "" && viewerID == lecture.OwnerID if lecture.Status != "ready" { if isOwner { - return nil, false, ErrNotReady + return lecture, true, ErrNotReady } return nil, false, ErrNotFound } - if lecture.Visibility == "private" && !isOwner { + // Личная лекция (и любое неизвестное состояние видимости) скрыта от всех, + // кроме владельца; только unlisted и public открыты по прямой ссылке. + if lecture.Visibility != "public" && lecture.Visibility != "unlisted" && !isOwner { return nil, false, ErrNotFound } return lecture, isOwner, nil } +// loadStructure читает и разбирает structure.json результата задачи ядра. +func (s *Service) loadStructure(ctx context.Context, coreTaskID string) (Structure, error) { + // Ядро кладёт выход задачи под results//output/ (см. контракт пути + // выхода core). Сегмент output/ обязателен, иначе GetObject вернёт NoSuchKey. + structureKey := "results/" + coreTaskID + "/output/structure.json" + b, err := s.store.GetObject(ctx, structureKey) + if err != nil { + return Structure{}, fmt.Errorf("%w: прочитать structure.json: %v", ErrCoreUnavailable, err) + } + return ParseStructure(b) +} + func (s *Service) buildSubtopic(ctx context.Context, sectionNumber, subtopicNumber int, subtopic Subtopic) (ViewSubtopic, error) { html, err := s.md.ToHTML(subtopic.ContentMD) if err != nil { diff --git a/internal/reader/service_test.go b/internal/reader/service_test.go index aa36be9..9b042d0 100644 --- a/internal/reader/service_test.go +++ b/internal/reader/service_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "slices" "testing" "time" ) @@ -49,8 +50,10 @@ func TestServiceLoadAccess(t *testing.T) { readyPrivate := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "ready", Visibility: "private", CoreTaskID: "task"} readyPublic := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "ready", Visibility: "public", CoreTaskID: "task"} + readyUnlisted := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "ready", Visibility: "unlisted", CoreTaskID: "task"} processingPrivate := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "processing", Visibility: "private", CoreTaskID: "task"} processingPublic := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "processing", Visibility: "public", CoreTaskID: "task"} + processingUnlisted := &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "processing", Visibility: "unlisted", CoreTaskID: "task"} tests := []struct { name string @@ -64,12 +67,18 @@ func TestServiceLoadAccess(t *testing.T) { {name: "public ready owner", lecture: readyPublic, viewer: "owner"}, {name: "public ready other user", lecture: readyPublic, viewer: "other"}, {name: "public ready anonymous", lecture: readyPublic}, + {name: "unlisted ready owner", lecture: readyUnlisted, viewer: "owner"}, + {name: "unlisted ready other user", lecture: readyUnlisted, viewer: "other"}, + {name: "unlisted ready anonymous", lecture: readyUnlisted}, {name: "private processing owner", lecture: processingPrivate, viewer: "owner", wantErr: ErrNotReady}, {name: "private processing other user", lecture: processingPrivate, viewer: "other", wantErr: ErrNotFound}, {name: "private processing anonymous", lecture: processingPrivate, wantErr: ErrNotFound}, {name: "public processing owner", lecture: processingPublic, viewer: "owner", wantErr: ErrNotReady}, {name: "public processing other user", lecture: processingPublic, viewer: "other", wantErr: ErrNotFound}, {name: "public processing anonymous", lecture: processingPublic, wantErr: ErrNotFound}, + {name: "unlisted processing owner", lecture: processingUnlisted, viewer: "owner", wantErr: ErrNotReady}, + {name: "unlisted processing other user", lecture: processingUnlisted, viewer: "other", wantErr: ErrNotFound}, + {name: "unlisted processing anonymous", lecture: processingUnlisted, wantErr: ErrNotFound}, {name: "missing lecture", wantErr: ErrNotFound}, } @@ -131,6 +140,29 @@ func TestServiceLoadBuildsView(t *testing.T) { } } +// TestServiceLoadPropagatesVisibility проверяет, что модель читалки несёт +// текущую видимость лекции — по ней HTTP-слой выставляет noindex-заголовки. +func TestServiceLoadPropagatesVisibility(t *testing.T) { + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "lecture", OwnerID: "owner", Status: "ready", Visibility: "unlisted", CoreTaskID: "task-1"}}, + &fakeObjectStore{data: validStructure(t)}, + &fakePresigner{}, + fakeRenderer{}, + time.Hour, + ) + + view, err := service.Load(context.Background(), "lecture", "") + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if view.Visibility != "unlisted" { + t.Errorf("ReaderView.Visibility = %q, want unlisted", view.Visibility) + } + if view.IsOwner { + t.Error("ReaderView.IsOwner = true для анонимного чтения unlisted-лекции") + } +} + func TestServiceLoadCoreUnavailable(t *testing.T) { service := NewService( fakeLectureRepo{lecture: &LectureMeta{OwnerID: "owner", Status: "ready", Visibility: "private", CoreTaskID: "task"}}, @@ -157,6 +189,85 @@ func TestServiceLoadInvalidStructure(t *testing.T) { } } +func structureWith(sections ...Section) Structure { + return Structure{Source: Source{Kind: "video"}, Sections: sections} +} + +func numberedSection(title string, subtopics ...Subtopic) Section { + return Section{Title: title, Subtopics: subtopics} +} + +func slideSubtopic(keys []string, nums []int) Subtopic { + return Subtopic{Title: "Подтема", SlideKeys: keys, SlideNums: nums} +} + +func TestBuildSlideMapNumbersSlides(t *testing.T) { + tests := []struct { + name string + structure Structure + wantNumbers [][][]int + wantKeys map[int]string + }{ + { + name: "explicit slide nums", + structure: structureWith(numberedSection("С", slideSubtopic([]string{"a", "b"}, []int{3, 4}))), + wantNumbers: [][][]int{{[]int{3, 4}}}, + wantKeys: map[int]string{3: "a", 4: "b"}, + }, + { + name: "legacy without slide nums", + structure: structureWith( + numberedSection("С1", slideSubtopic([]string{"a", "b"}, nil)), + numberedSection("С2", slideSubtopic([]string{"c"}, nil)), + ), + wantNumbers: [][][]int{{[]int{1, 2}}, {[]int{3}}}, + wantKeys: map[int]string{1: "a", 2: "b", 3: "c"}, + }, + { + name: "mixed numbers continue after max", + structure: structureWith( + numberedSection("С1", slideSubtopic([]string{"a"}, []int{2})), + numberedSection("С2", slideSubtopic([]string{"b", "c"}, nil)), + ), + wantNumbers: [][][]int{{[]int{2}}, {[]int{3, 4}}}, + wantKeys: map[int]string{2: "a", 3: "b", 4: "c"}, + }, + { + name: "partially filled nums keep explicit and number the rest", + structure: structureWith(numberedSection("С", slideSubtopic([]string{"a", "b", "c"}, []int{5, 0}))), + wantNumbers: [][][]int{{[]int{5, 6, 7}}}, + wantKeys: map[int]string{5: "a", 6: "b", 7: "c"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := BuildSlideMap(tt.structure) + if len(got.Numbers) != len(tt.wantNumbers) { + t.Fatalf("Numbers = %#v, want %#v", got.Numbers, tt.wantNumbers) + } + for si := range tt.wantNumbers { + if len(got.Numbers[si]) != len(tt.wantNumbers[si]) { + t.Fatalf("Numbers[%d] = %#v, want %#v", si, got.Numbers[si], tt.wantNumbers[si]) + } + for ti := range tt.wantNumbers[si] { + if !slices.Equal(got.Numbers[si][ti], tt.wantNumbers[si][ti]) { + t.Fatalf("Numbers[%d][%d] = %#v, want %#v", si, ti, got.Numbers[si][ti], tt.wantNumbers[si][ti]) + } + } + } + if len(got.Keys) != len(tt.wantKeys) { + t.Fatalf("Keys = %#v, want %#v", got.Keys, tt.wantKeys) + } + for num, key := range tt.wantKeys { + if got.Keys[num] != key { + t.Fatalf("Keys[%d] = %q, want %q", num, got.Keys[num], key) + } + } + }) + } +} + func validStructure(t *testing.T) []byte { t.Helper() b, err := os.ReadFile("testdata/structure_valid.json") @@ -243,3 +354,126 @@ func TestServiceLoadWithoutMarkersKeepsGallery(t *testing.T) { t.Errorf("SlideURLs = %#v", sub.SlideURLs) } } + +func TestServiceLoadSlide(t *testing.T) { + structure := []byte(`{ + "source": {"title": "Л", "kind": "video", "duration": 60}, + "sections": [{"title": "С", "subtopics": [{ + "title": "П", + "slide_keys": ["results/t/slide-1.png", "results/t/slide-2.jpg"], + "slide_nums": [1, 2], + "content_md": "Текст" + }]}] + }`) + store := &objectStore{objects: map[string][]byte{ + "results/t/output/structure.json": structure, + "results/t/slide-1.png": pngSlideBytes, + "results/t/slide-2.jpg": jpegSlideBytes, + }} + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "l", OwnerID: "o", Status: "ready", Visibility: "unlisted", CoreTaskID: "t"}}, + store, &fakePresigner{}, fakeRenderer{}, time.Hour, + ) + + slide, err := service.LoadSlide(context.Background(), "l", "", 2) + if err != nil { + t.Fatalf("LoadSlide() error = %v", err) + } + if string(slide.Bytes) != string(jpegSlideBytes) { + t.Errorf("Bytes = %q, want %q", slide.Bytes, jpegSlideBytes) + } + if slide.ContentType != "image/jpeg" { + t.Errorf("ContentType = %q, want image/jpeg", slide.ContentType) + } + if slide.Visibility != "unlisted" { + t.Errorf("Visibility = %q, want unlisted", slide.Visibility) + } + if len(store.calls) != 2 || store.calls[0] != "results/t/output/structure.json" || store.calls[1] != "results/t/slide-2.jpg" { + t.Errorf("GetObject calls = %v", store.calls) + } +} + +func TestServiceLoadSlideContentTypes(t *testing.T) { + tests := []struct { + key string + data []byte + want string + }{ + {key: "results/t/a.PNG", data: []byte("x"), want: "image/png"}, + {key: "results/t/a.jpeg", data: []byte("x"), want: "image/jpeg"}, + {key: "results/t/a.webp", data: []byte("x"), want: "image/webp"}, + {key: "results/t/frame", data: pngSlideBytes, want: "image/png"}, + {key: "results/t/frame", data: []byte("не картинка"), want: "text/plain; charset=utf-8"}, + } + + for _, tt := range tests { + store := &objectStore{objects: map[string][]byte{ + "results/t/output/structure.json": []byte(`{ + "source": {"title": "Л", "kind": "video", "duration": 60}, + "sections": [{"title": "С", "subtopics": [{"title": "П", "slide_keys": ["` + tt.key + `"], "slide_nums": [1], "content_md": "Текст"}]}] + }`), + tt.key: tt.data, + }} + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "l", OwnerID: "o", Status: "ready", Visibility: "public", CoreTaskID: "t"}}, + store, &fakePresigner{}, fakeRenderer{}, time.Hour, + ) + slide, err := service.LoadSlide(context.Background(), "l", "", 1) + if err != nil { + t.Fatalf("LoadSlide(%q) error = %v", tt.key, err) + } + if slide.ContentType != tt.want { + t.Errorf("LoadSlide(%q) ContentType = %q, want %q", tt.key, slide.ContentType, tt.want) + } + } +} + +func TestServiceLoadSlideUnknownNumber(t *testing.T) { + store := &objectStore{objects: map[string][]byte{ + "results/t/output/structure.json": []byte(`{ + "source": {"title": "Л", "kind": "video", "duration": 60}, + "sections": [{"title": "С", "subtopics": [{"title": "П", "slide_keys": ["results/t/a.png"], "slide_nums": [4], "content_md": "Текст"}]}] + }`), + }} + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "l", OwnerID: "o", Status: "ready", Visibility: "private", CoreTaskID: "t"}}, + store, &fakePresigner{}, fakeRenderer{}, time.Hour, + ) + + if _, err := service.LoadSlide(context.Background(), "l", "o", 1); !errors.Is(err, ErrNotFound) { + t.Fatalf("LoadSlide() error = %v, want ErrNotFound", err) + } + if len(store.calls) != 1 { + t.Fatalf("GetObject calls = %v, want только structure.json", store.calls) + } +} + +func TestServiceLoadSlideAccessDenied(t *testing.T) { + store := &objectStore{} + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "l", OwnerID: "o", Status: "ready", Visibility: "private", CoreTaskID: "t"}}, + store, &fakePresigner{}, fakeRenderer{}, time.Hour, + ) + + for _, viewer := range []string{"", "other"} { + for _, n := range []int{0, 1} { + if _, err := service.LoadSlide(context.Background(), "l", viewer, n); !errors.Is(err, ErrNotFound) { + t.Fatalf("LoadSlide(viewer=%q, %d) error = %v, want ErrNotFound", viewer, n, err) + } + } + } + if len(store.calls) != 0 { + t.Fatalf("GetObject calls = %v, want пусто", store.calls) + } +} + +func TestServiceLoadSlideCoreUnavailable(t *testing.T) { + service := NewService( + fakeLectureRepo{lecture: &LectureMeta{ID: "l", OwnerID: "o", Status: "ready", Visibility: "public", CoreTaskID: "t"}}, + &objectStore{errs: map[string]error{"results/t/output/structure.json": errors.New("хранилище недоступно")}}, + &fakePresigner{}, fakeRenderer{}, time.Hour, + ) + if _, err := service.LoadSlide(context.Background(), "l", "", 1); !errors.Is(err, ErrCoreUnavailable) { + t.Fatalf("LoadSlide() error = %v, want ErrCoreUnavailable", err) + } +} diff --git a/internal/reader/slides.go b/internal/reader/slides.go new file mode 100644 index 0000000..b6fb9a1 --- /dev/null +++ b/internal/reader/slides.go @@ -0,0 +1,116 @@ +package reader + +import ( + "context" + "fmt" + "net/http" + "path" + "strings" +) + +// SlideData — изображение Слайда, готовое к прямой раздаче. +type SlideData struct { + Bytes []byte + ContentType string + Visibility string +} + +// SlideMap — детерминированная 1-based карта Слайдов Конспекта. +// Numbers повторяет форму дерева: номер Слайда по индексам +// [раздел][подтема][слайд], Keys связывает номер с ключом хранилища. +type SlideMap struct { + Numbers [][][]int + Keys map[int]string +} + +// BuildSlideMap обходит Конспект в порядке Разделов и Подтем. Сначала +// учитываются явные slide_nums, затем оставшимся Слайдам (старые Конспекты +// без slide_nums) присваиваются последовательные номера после максимального. +func BuildSlideMap(structure Structure) SlideMap { + numbers := make([][][]int, len(structure.Sections)) + keys := make(map[int]string) + maxNum := 0 + + for sectionIndex, section := range structure.Sections { + numbers[sectionIndex] = make([][]int, len(section.Subtopics)) + for subtopicIndex, subtopic := range section.Subtopics { + numbers[sectionIndex][subtopicIndex] = make([]int, len(subtopic.SlideKeys)) + for slideIndex := range subtopic.SlideKeys { + if slideIndex >= len(subtopic.SlideNums) || subtopic.SlideNums[slideIndex] < 1 { + continue + } + num := subtopic.SlideNums[slideIndex] + numbers[sectionIndex][subtopicIndex][slideIndex] = num + keys[num] = subtopic.SlideKeys[slideIndex] + if num > maxNum { + maxNum = num + } + } + } + } + + next := maxNum + for sectionIndex, section := range structure.Sections { + for subtopicIndex, subtopic := range section.Subtopics { + for slideIndex, key := range subtopic.SlideKeys { + if numbers[sectionIndex][subtopicIndex][slideIndex] >= 1 { + continue + } + next++ + numbers[sectionIndex][subtopicIndex][slideIndex] = next + keys[next] = key + } + } + } + + return SlideMap{Numbers: numbers, Keys: keys} +} + +// LoadSlide проверяет доступ к Лекции и читает байты Слайда по его номеру. +func (s *Service) LoadSlide(ctx context.Context, lectureID, viewerID string, slideNum int) (SlideData, error) { + lecture, _, err := s.accessLecture(ctx, lectureID, viewerID) + if err != nil { + if lecture != nil { + return SlideData{Visibility: lecture.Visibility}, err + } + return SlideData{}, err + } + out := SlideData{Visibility: lecture.Visibility} + if slideNum <= 0 { + return out, ErrNotFound + } + + structure, err := s.loadStructure(ctx, lecture.CoreTaskID) + if err != nil { + return out, err + } + + key, ok := BuildSlideMap(structure).Keys[slideNum] + if !ok { + return out, ErrNotFound + } + + slideBytes, err := s.store.GetObject(ctx, key) + if err != nil { + return out, fmt.Errorf("%w: прочитать слайд: %v", ErrCoreUnavailable, err) + } + + out.Bytes = slideBytes + out.ContentType = slideContentType(key, slideBytes) + return out, nil +} + +// slideContentType определяет тип изображения по расширению ключа, +// а при неизвестном расширении — по первым байтам. +func slideContentType(key string, b []byte) string { + switch strings.ToLower(path.Ext(key)) { + case ".png": + return "image/png" + case ".jpg", ".jpeg": + return "image/jpeg" + case ".webp": + return "image/webp" + default: + return http.DetectContentType(b) + } +} diff --git a/internal/web/agent.go b/internal/web/agent.go new file mode 100644 index 0000000..f7f2670 --- /dev/null +++ b/internal/web/agent.go @@ -0,0 +1,217 @@ +package web + +// Хелперы агентского представления: базовый origin платформы и согласование +// Markdown/HTML. Живут в пакете web, чтобы ими пользовались и витрина (hub), +// и читальный зал (reader), не дублируя разбор заголовков. + +import ( + "net/http" + "net/url" + "strconv" + "strings" +) + +// agentUserAgentMarkers — подстроки известных ИИ-фетчеров и CLI-клиентов +// (без учёта регистра). Такой клиент получает Markdown даже с `Accept: text/html`. +var agentUserAgentMarkers = []string{ + "chatgpt-user", + "oai-searchbot", + "gptbot", + "claude-web", + "claude-user", + "claudebot", + "anthropic", + "perplexitybot", + "perplexity-user", + "google-extended", + "cohere-ai", + "duckassistbot", + "youbot", + "curl/", + "wget/", + "python-httpx", + "python-requests", + "go-http-client", + "undici", + "node-fetch", + "axios/", +} + +// robotsTxt — правила обхода платформы для краулеров и агентских фетчеров. +const robotsTxt = `User-agent: * +Allow: / +Disallow: /lectures +Disallow: /upload +Disallow: /settings +Disallow: /auth +` + +// OriginFromCallbackURL извлекает `scheme://host` из обязательного callback-URL +// OAuth (PLATFORM_CALLBACK_URL), отбрасывая путь, query и fragment. +// Пустая строка означает, что origin не сконфигурирован и нужен fallback из запроса. +func OriginFromCallbackURL(callbackURL string) string { + u, err := url.Parse(strings.TrimSpace(callbackURL)) + if err != nil { + return "" + } + if u.Scheme != "http" && u.Scheme != "https" { + return "" + } + if u.Host == "" { + return "" + } + return strings.ToLower(u.Scheme) + "://" + u.Host +} + +// ResolveOrigin возвращает внешний origin платформы для абсолютных ссылок. +// Сконфигурированный базовый origin имеет приоритет (защита от Host-header +// injection); без него используется безопасный fallback из самого запроса. +func ResolveOrigin(baseOrigin string, r *http.Request) string { + if trimmed := strings.TrimSpace(baseOrigin); trimmed != "" { + return strings.TrimRight(trimmed, "/") + } + + scheme := "http" + host := "localhost" + if r != nil { + if forwarded := forwardedProto(r); forwarded != "" { + scheme = forwarded + } else if r.TLS != nil { + scheme = "https" + } + if r.Host != "" { + host = r.Host + } + } + return scheme + "://" + host +} + +// forwardedProto берёт первое значение X-Forwarded-Proto, если это http или https. +func forwardedProto(r *http.Request) string { + value := r.Header.Get("X-Forwarded-Proto") + if idx := strings.IndexByte(value, ','); idx >= 0 { + value = value[:idx] + } + proto := strings.ToLower(strings.TrimSpace(value)) + if proto == "http" || proto == "https" { + return proto + } + return "" +} + +// mediaPreference описывает присутствие и максимальный вес q семейства медиатипов в Accept. +type mediaPreference struct { + weight float64 + present bool +} + +// WantsMarkdown решает, отдавать ли Агентское представление вместо HTML. +// +// Правило выбора: +// 1. `Accept` явно предпочитает `text/markdown` / `text/x-markdown` перед +// `text/html` (с учётом весов `q=`); при `qMD == 0` (явный отказ) или +// `qHTML >= qMD` при явном присутствии обоих семейств приоритет у HTML. +// 2. Известный агентский или CLI `User-Agent` получает Markdown независимо +// от дефолтного `Accept` (`text/html` или `*/*`) — облачные боты часто шлют `Accept: text/html`. +// 3. Во всех остальных случаях (обычный браузер, пустые заголовки) — HTML. +func WantsMarkdown(r *http.Request) bool { + if r == nil { + return false + } + + mdPref, htmlPref := acceptPreferences(strings.Join(r.Header.Values("Accept"), ", ")) + if mdPref.present { + if mdPref.weight == 0 { + return false + } + if mdPref.weight > htmlPref.weight { + return true + } + } + + userAgent := strings.ToLower(r.Header.Get("User-Agent")) + for _, marker := range agentUserAgentMarkers { + if strings.Contains(userAgent, marker) { + return true + } + } + return false +} + +// SetVaryAcceptUserAgent добавляет Accept и User-Agent в заголовок Vary, +// сохраняя существующие значения (например, Cookie от глобального CSRF-middleware). +func SetVaryAcceptUserAgent(w http.ResponseWriter) { + existing := strings.Join(w.Header().Values("Vary"), ", ") + if existing == "" { + w.Header().Set("Vary", "Accept, User-Agent") + return + } + if !strings.Contains(existing, "Accept, User-Agent") { + w.Header().Set("Vary", "Accept, User-Agent, "+existing) + } +} + +// EscapeMarkdownLinkText нормализует переводы строк и экранирует скобки +// в тексте Markdown-ссылки или подписи изображения ![...](...). +func EscapeMarkdownLinkText(s string) string { + s = SanitizeInlineText(s) + s = strings.ReplaceAll(s, `\`, `\\`) + s = strings.ReplaceAll(s, "[", `\[`) + s = strings.ReplaceAll(s, "]", `\]`) + return s +} + +// SanitizeInlineText убирает переводы строк из однострочных заголовков и полей списка. +func SanitizeInlineText(s string) string { + s = strings.ReplaceAll(s, "\r\n", " ") + s = strings.ReplaceAll(s, "\n", " ") + s = strings.ReplaceAll(s, "\r", " ") + return strings.TrimSpace(s) +} + +// acceptPreferences возвращает максимальные веса markdown- и html-типов из Accept. +func acceptPreferences(accept string) (mdPref mediaPreference, htmlPref mediaPreference) { + for _, part := range strings.Split(accept, ",") { + mediaType, quality := parseAcceptPart(part) + switch mediaType { + case "text/markdown", "text/x-markdown": + mdPref.present = true + if quality > mdPref.weight { + mdPref.weight = quality + } + case "text/html", "application/xhtml+xml": + htmlPref.present = true + if quality > htmlPref.weight { + htmlPref.weight = quality + } + } + } + return mdPref, htmlPref +} + +// parseAcceptPart разбирает один элемент Accept: медиатип и вес q (по умолчанию 1.0). +// Пустой медиатип означает, что элемент пропускается. +func parseAcceptPart(part string) (mediaType string, quality float64) { + segments := strings.Split(part, ";") + mediaType = strings.ToLower(strings.TrimSpace(segments[0])) + if mediaType == "" { + return "", 0 + } + + quality = 1.0 + for _, param := range segments[1:] { + key, value, ok := strings.Cut(param, "=") + if !ok || !strings.EqualFold(strings.TrimSpace(key), "q") { + continue + } + parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64) + if err != nil || parsed < 0 { + continue + } + if parsed > 1 { + parsed = 1 + } + quality = parsed + } + return mediaType, quality +} diff --git a/internal/web/agent_test.go b/internal/web/agent_test.go new file mode 100644 index 0000000..73132de --- /dev/null +++ b/internal/web/agent_test.go @@ -0,0 +1,200 @@ +package web_test + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/LectureLog/lecturelog-web/internal/web" +) + +// TestOriginFromCallbackURL проверяет извлечение scheme://host из callback-URL. +func TestOriginFromCallbackURL(t *testing.T) { + tests := []struct { + name string + callbackURL string + want string + }{ + {name: "https с путём callback", callbackURL: "https://lecturelog.example/auth/callback", want: "https://lecturelog.example"}, + {name: "http с query и fragment", callbackURL: "http://localhost:8080/auth/callback?code=1#frag", want: "http://localhost:8080"}, + {name: "без пути", callbackURL: "https://example.org", want: "https://example.org"}, + {name: "пробелы вокруг", callbackURL: " https://example.org/auth/callback ", want: "https://example.org"}, + {name: "пустая строка", callbackURL: "", want: ""}, + {name: "только пробелы", callbackURL: " ", want: ""}, + {name: "без схемы", callbackURL: "example.org/auth/callback", want: ""}, + {name: "относительный путь", callbackURL: "/auth/callback", want: ""}, + {name: "неподдерживаемая схема", callbackURL: "ftp://example.org/auth/callback", want: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := web.OriginFromCallbackURL(tt.callbackURL); got != tt.want { + t.Errorf("OriginFromCallbackURL(%q) = %q, ожидается %q", tt.callbackURL, got, tt.want) + } + }) + } +} + +// TestResolveOrigin проверяет приоритет сконфигурированного origin и fallback из запроса. +func TestResolveOrigin(t *testing.T) { + tests := []struct { + name string + baseOrigin string + request func() *http.Request + want string + }{ + { + name: "базовый origin из конфигурации", + baseOrigin: "https://lecturelog.example", + request: func() *http.Request { return httptest.NewRequest(http.MethodGet, "/hub", nil) }, + want: "https://lecturelog.example", + }, + { + name: "базовый origin с пробелами и слэшем", + baseOrigin: " https://lecturelog.example/ ", + request: func() *http.Request { return httptest.NewRequest(http.MethodGet, "/hub", nil) }, + want: "https://lecturelog.example", + }, + { + name: "fallback на X-Forwarded-Proto", + request: func() *http.Request { + req := httptest.NewRequest(http.MethodGet, "/hub", nil) + req.Host = "lecturelog.example" + req.Header.Set("X-Forwarded-Proto", "https") + return req + }, + want: "https://lecturelog.example", + }, + { + name: "fallback игнорирует неизвестную схему прокси", + request: func() *http.Request { + req := httptest.NewRequest(http.MethodGet, "/hub", nil) + req.Host = "lecturelog.example" + req.Header.Set("X-Forwarded-Proto", "ftp") + return req + }, + want: "http://lecturelog.example", + }, + { + name: "fallback на TLS запроса", + request: func() *http.Request { + req := httptest.NewRequest(http.MethodGet, "/hub", nil) + req.Host = "lecturelog.example" + req.TLS = &tls.ConnectionState{} + return req + }, + want: "https://lecturelog.example", + }, + { + name: "nil-запрос без конфигурации", + request: func() *http.Request { return nil }, + want: "http://localhost", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := web.ResolveOrigin(tt.baseOrigin, tt.request()); got != tt.want { + t.Errorf("ResolveOrigin(%q, ...) = %q, ожидается %q", tt.baseOrigin, got, tt.want) + } + }) + } +} + +// TestWantsMarkdown проверяет согласование Агентского представления по Accept и User-Agent. +func TestWantsMarkdown(t *testing.T) { + const browserUA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36" + + tests := []struct { + name string + accept string + ua string + want bool + }{ + {name: "пустые заголовки", want: false}, + {name: "браузерный Accept без агентского UA", accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", ua: browserUA, want: false}, + {name: "браузер с Accept text/html", accept: "text/html", ua: browserUA, want: false}, + {name: "Accept text/markdown", accept: "text/markdown", want: true}, + {name: "Accept text/x-markdown", accept: "text/x-markdown", want: true}, + {name: "markdown с параметром charset", accept: "text/markdown; charset=utf-8", want: true}, + {name: "markdown весит больше html", accept: "text/markdown;q=0.9, text/html;q=0.8", want: true}, + {name: "html и markdown с равным весом не предпочитают markdown в браузере", accept: "text/html, text/markdown", ua: browserUA, want: false}, + {name: "html и markdown с равным весом у известного агента отдают markdown", accept: "text/html, text/markdown", ua: "ClaudeBot/1.0", want: true}, + {name: "html весит больше markdown", accept: "text/html, text/markdown;q=0.5", want: false}, + {name: "markdown отклонён через q=0 в браузере", accept: "text/markdown;q=0, text/html", ua: browserUA, want: false}, + {name: "markdown явно отклонён через q=0 даже в curl", accept: "text/markdown;q=0, text/html", ua: "curl/8.5.0", want: false}, + {name: "curl с Accept */*", accept: "*/*", ua: "curl/8.5.0", want: true}, + {name: "curl с браузерным Accept", accept: "text/html,application/xhtml+xml,*/*;q=0.8", ua: "curl/8.5.0", want: true}, + {name: "ChatGPT-User", accept: "text/html", ua: "Mozilla/5.0 (compatible; ChatGPT-User/1.0; +https://openai.com/bot)", want: true}, + {name: "ClaudeBot", accept: "*/*", ua: "ClaudeBot/1.0", want: true}, + {name: "Claude-User", ua: "Mozilla/5.0 Claude-User", want: true}, + {name: "PerplexityBot", ua: "PerplexityBot/1.0", want: true}, + {name: "python-requests", ua: "python-requests/2.32.3", want: true}, + {name: "Go-http-client", ua: "Go-http-client/1.1", want: true}, + {name: "node-fetch", ua: "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)", want: true}, + {name: "регистр маркера не важен", ua: "gptbot/2.0", want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/hub", nil) + if tt.accept != "" { + req.Header.Set("Accept", tt.accept) + } + if tt.ua != "" { + req.Header.Set("User-Agent", tt.ua) + } + if got := web.WantsMarkdown(req); got != tt.want { + t.Errorf("WantsMarkdown(Accept=%q, UA=%q) = %v, ожидается %v", tt.accept, tt.ua, got, tt.want) + } + }) + } + + t.Run("несколько строк заголовка Accept", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/hub", nil) + req.Header.Add("Accept", "*/*") + req.Header.Add("Accept", "text/markdown") + if !web.WantsMarkdown(req) { + t.Error("WantsMarkdown должен учитывать вторую строку заголовка Accept") + } + }) +} + +// TestSetVaryAcceptUserAgent проверяет сохранение уже выставленного Vary (например, Cookie). +func TestSetVaryAcceptUserAgent(t *testing.T) { + rec := httptest.NewRecorder() + rec.Header().Set("Vary", "Cookie") + web.SetVaryAcceptUserAgent(rec) + if got := rec.Header().Get("Vary"); got != "Accept, User-Agent, Cookie" { + t.Errorf("Vary = %q, ожидается \"Accept, User-Agent, Cookie\"", got) + } +} + +// TestRobotsTxt проверяет машиночитаемые правила обхода для ИИ-краулеров. +func TestRobotsTxt(t *testing.T) { + rec := httptest.NewRecorder() + web.NewRouter().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /robots.txt = %d, ожидается 200", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" { + t.Errorf("Content-Type = %q, ожидается text/plain; charset=utf-8", got) + } + + body := rec.Body.String() + for _, want := range []string{ + "User-agent: *", + "Allow: /", + "Disallow: /lectures", + "Disallow: /upload", + "Disallow: /settings", + "Disallow: /auth", + } { + if !strings.Contains(body, want) { + t.Errorf("robots.txt не содержит %q:\n%s", want, body) + } + } +} diff --git a/internal/web/assets/tailwind.css b/internal/web/assets/tailwind.css index df43a12..74240b0 100644 --- a/internal/web/assets/tailwind.css +++ b/internal/web/assets/tailwind.css @@ -87,6 +87,27 @@ .ll-reader-source-card { display: flex; flex-direction: column; gap: 8px; padding: 16px; border: 1px solid var(--border); border-radius: var(--r-card); background: var(--surface); font-size: 13px; color: var(--text-2); } .ll-reader-source-card strong { color: var(--ink); font-size: 14px; } .ll-reader-owner { color: var(--accent); font-weight: 600; } + + /* Бейдж текущей видимости лекции в карточке источника (только владельцу) */ + .ll-reader-visibility { + display: inline-flex; + align-items: center; + padding: 1px 8px; + border: 1px solid var(--border); + border-radius: var(--r-pill); + background: var(--surface-2); + color: var(--text-2); + font-size: 11px; + font-weight: 500; + } + + .ll-reader-visibility--unlisted { border-color: var(--border-2); } + + .ll-reader-visibility--public { + background: var(--accent-soft); + border-color: var(--accent-soft); + color: var(--accent); + } .ll-reader-reading { margin: 20px 0 25px; color: var(--text-3); font-size: 12px; } .ll-reader-reading strong { float: right; color: var(--text-2); font-variant-numeric: tabular-nums; } .ll-reader-reading div { clear: both; height: 4px; margin-top: 9px; overflow: hidden; border-radius: var(--r-track); background: var(--rail); } @@ -541,12 +562,48 @@ color: var(--accent); } - .ll-toggle:disabled { + .ll-toggle:disabled:not(.ll-toggle--active) { opacity: 0.5; cursor: not-allowed; } - .ll-toggle--public { + .ll-toggle--active:disabled { + cursor: default; + } + + /* Трёхпозиционный переключатель видимости: Личная | По ссылке | Витрина. + Кнопки сегментированы в общую пилюлю; активная помечена aria-pressed. */ + .ll-toggle-group { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 2px; + border: 1px solid var(--border); + border-radius: var(--r-pill); + background: var(--surface-2); + } + + .ll-toggle-group .ll-toggle { + padding: 2px 9px; + min-height: 22px; + border-color: transparent; + background: transparent; + font-size: 11.5px; + line-height: 1.2; + white-space: nowrap; + } + + .ll-toggle--active[aria-pressed="true"] { + background: var(--surface); + border-color: var(--border); + color: var(--text-2); + } + + .ll-toggle--unlisted[aria-pressed="true"] { + border-color: var(--border-2); + } + + .ll-toggle--public[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-soft); color: var(--accent); diff --git a/internal/web/layout.templ b/internal/web/layout.templ index 71432f5..189d650 100644 --- a/internal/web/layout.templ +++ b/internal/web/layout.templ @@ -24,6 +24,12 @@ type LayoutData struct { // Active — ключ активного пункта навигации: hub|lectures|upload|"" (см. navLink). // Страницы выставляют его сами через withNav — обработчикам знать не нужно. Active string + // NoIndex — запрет индексации страницы поисковиками + // (не-публичные лекции: unlisted и private, открытая владельцу). + NoIndex bool + // AlternateMarkdownURL — адрес Агентского представления страницы для + // . Пусто — ссылка не выводится. + AlternateMarkdownURL string } // NewLayoutData собирает данные layout из контекста запроса. @@ -73,6 +79,12 @@ templ Layout(data LayoutData, actions templ.Component) { + if data.NoIndex { + + } + if data.AlternateMarkdownURL != "" { + + } ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<!doctype html><html lang=\"ru\" data-theme=\"light\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"description\" content=\"LectureLog — конспекты лекций с тайм-кодами: загрузите запись, получите структурированный конспект со слайдами.\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var2 string - templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(docTitle(data.Title)) + if data.NoIndex { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<meta name=\"robots\" content=\"noindex, nofollow\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + if data.AlternateMarkdownURL != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<link rel=\"alternate\" type=\"text/markdown\" href=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 templ.SafeURL + templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinURLErrs(data.AlternateMarkdownURL) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 86, Col: 79} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<!-- Инлайн-скрипт темы: читает localStorage до first paint, устраняет FOUC --><script>\n\t\t\t\t(function(){\n\t\t\t\t\tvar t = localStorage.getItem('ll_theme');\n\t\t\t\t\tif (t === 'dark' || t === 'light') {\n\t\t\t\t\t\tdocument.documentElement.setAttribute('data-theme', t);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t</script><link rel=\"icon\" type=\"image/svg+xml\" href=\"/static/favicon.svg\"><!-- Google Fonts: Source Serif 4 (контент) + Onest (интерфейс) --><link rel=\"preconnect\" href=\"https://fonts.googleapis.com\"><link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin><link href=\"https://fonts.googleapis.com/css2?family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,500;0,8..60,600;0,8..60,700;1,8..60,400;1,8..60,500;1,8..60,600&family=Onest:wght@400;500;600;700&display=swap\" rel=\"stylesheet\"><link rel=\"stylesheet\" href=\"/static/css/app.css\"><script src=\"/static/vendor/htmx.min.js\" defer></script><title>") if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 92, Col: 32} + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(docTitle(data.Title)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 104, Col: 32} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -129,7 +164,7 @@ func Layout(data LayoutData, actions templ.Component) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -137,7 +172,7 @@ func Layout(data LayoutData, actions templ.Component) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -145,7 +180,7 @@ func Layout(data LayoutData, actions templ.Component) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -170,12 +205,12 @@ func header(data LayoutData, actions templ.Component) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var4 := templ.GetChildren(ctx) - if templ_7745c5c3_Var4 == nil { - templ_7745c5c3_Var4 = templ.NopComponent + templ_7745c5c3_Var5 := templ.GetChildren(ctx) + if templ_7745c5c3_Var5 == nil { + templ_7745c5c3_Var5 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -183,7 +218,7 @@ func header(data LayoutData, actions templ.Component) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "LectureLog") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "LectureLog") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -191,7 +226,7 @@ func header(data LayoutData, actions templ.Component) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -202,7 +237,7 @@ func header(data LayoutData, actions templ.Component) templ.Component { } } if !data.IsAuthed { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "Войти ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "Войти ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -223,7 +258,7 @@ func header(data LayoutData, actions templ.Component) templ.Component { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -249,12 +284,12 @@ func topNav(data LayoutData) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var5 := templ.GetChildren(ctx) - if templ_7745c5c3_Var5 == nil { - templ_7745c5c3_Var5 = templ.NopComponent + templ_7745c5c3_Var6 := templ.GetChildren(ctx) + if templ_7745c5c3_Var6 == nil { + templ_7745c5c3_Var6 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -301,70 +336,70 @@ func navLink(href, label string, active bool) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var6 := templ.GetChildren(ctx) - if templ_7745c5c3_Var6 == nil { - templ_7745c5c3_Var6 = templ.NopComponent + templ_7745c5c3_Var7 := templ.GetChildren(ctx) + if templ_7745c5c3_Var7 == nil { + templ_7745c5c3_Var7 = templ.NopComponent } ctx = templ.ClearChildren(ctx) if active { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "\" aria-current=\"page\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var8 string - templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(label) + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(label) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 148, Col: 86} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 160, Col: 86} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var10 string - templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(label) + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(label) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 150, Col: 46} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 162, Col: 46} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -390,12 +425,12 @@ func themeToggle() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var11 := templ.GetChildren(ctx) - if templ_7745c5c3_Var11 == nil { - templ_7745c5c3_Var11 = templ.NopComponent + templ_7745c5c3_Var12 := templ.GetChildren(ctx) + if templ_7745c5c3_Var12 == nil { + templ_7745c5c3_Var12 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -436,12 +471,12 @@ func adminGearLink() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var12 := templ.GetChildren(ctx) - if templ_7745c5c3_Var12 == nil { - templ_7745c5c3_Var12 = templ.NopComponent + templ_7745c5c3_Var13 := templ.GetChildren(ctx) + if templ_7745c5c3_Var13 == nil { + templ_7745c5c3_Var13 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -449,7 +484,7 @@ func adminGearLink() templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -476,25 +511,25 @@ func logoutButton(csrfToken string) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var13 := templ.GetChildren(ctx) - if templ_7745c5c3_Var13 == nil { - templ_7745c5c3_Var13 = templ.NopComponent + templ_7745c5c3_Var14 := templ.GetChildren(ctx) + if templ_7745c5c3_Var14 == nil { + templ_7745c5c3_Var14 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -527,12 +562,12 @@ func footer() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var15 := templ.GetChildren(ctx) - if templ_7745c5c3_Var15 == nil { - templ_7745c5c3_Var15 = templ.NopComponent + templ_7745c5c3_Var16 := templ.GetChildren(ctx) + if templ_7745c5c3_Var16 == nil { + templ_7745c5c3_Var16 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -643,83 +678,83 @@ func footerExtLink(href string, label string, iconOnly bool) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var19 := templ.GetChildren(ctx) - if templ_7745c5c3_Var19 == nil { - templ_7745c5c3_Var19 = templ.NopComponent + templ_7745c5c3_Var20 := templ.GetChildren(ctx) + if templ_7745c5c3_Var20 == nil { + templ_7745c5c3_Var20 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - var templ_7745c5c3_Var20 = []any{"ll-footer-link", "ll-footer-link--ext", templ.KV("ll-footer-link--icon", iconOnly)} - templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var20...) + var templ_7745c5c3_Var21 = []any{"ll-footer-link", "ll-footer-link--ext", templ.KV("ll-footer-link--icon", iconOnly)} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var21...) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templ_7745c5c3_Var19.Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = templ_7745c5c3_Var20.Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if !iconOnly { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var24 string - templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(label) + var templ_7745c5c3_Var25 string + templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(label) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 231, Col: 16} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `layout.templ`, Line: 243, Col: 16} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -744,12 +779,12 @@ func brandMark() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var25 := templ.GetChildren(ctx) - if templ_7745c5c3_Var25 == nil { - templ_7745c5c3_Var25 = templ.NopComponent + templ_7745c5c3_Var26 := templ.GetChildren(ctx) + if templ_7745c5c3_Var26 == nil { + templ_7745c5c3_Var26 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -757,7 +792,7 @@ func brandMark() templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -782,12 +817,12 @@ func iconLogout() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var26 := templ.GetChildren(ctx) - if templ_7745c5c3_Var26 == nil { - templ_7745c5c3_Var26 = templ.NopComponent + templ_7745c5c3_Var27 := templ.GetChildren(ctx) + if templ_7745c5c3_Var27 == nil { + templ_7745c5c3_Var27 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/page_lectures.templ b/internal/web/page_lectures.templ index 7b5bb86..c9e9329 100644 --- a/internal/web/page_lectures.templ +++ b/internal/web/page_lectures.templ @@ -13,7 +13,7 @@ type LectureCardVM struct { Status string // StatusLabel — локализованная метка статуса: «Обработка»/«Готово»/«Ошибка». StatusLabel string - // Visibility — видимость: private|public. + // Visibility — видимость: private|unlisted|public. Visibility string // SourceKind — тип источника: audio|video|video_url. SourceKind string @@ -95,7 +95,7 @@ templ LectureCard(vm LectureCardVM) {
{ sourceLabel(vm.SourceKind) }
- if vm.Visibility == "public" { + if vm.Visibility == "public" || vm.Visibility == "unlisted" { @LectureShareButton(vm) } if vm.CanRetry { @@ -127,7 +127,7 @@ templ LectureCard(vm LectureCardVM) {
@@ -187,27 +187,39 @@ templ LectureTitleInline(vm LectureCardVM) { } -// LectureVisibilityToggle — тумблер переключения видимости лекции. -// Для public-лекции disabled если статус не ready. -// hx-vals обязателен: handleSetVisibility читает form-поле "visibility" -// с целевым значением (без него публикация из UI не работает). +// LectureVisibilityToggle — трёхпозиционный переключатель видимости лекции: +// «Личная» (private) / «По ссылке» (unlisted) / «Витрина» (public). +// Каждая неактивная кнопка шлёт hx-post с целевым значением и перерисовывает карточку; +// уже выбранный сегмент заблокирован, чтобы повторный клик не вызывал лишний запрос. +// Для неготовой лекции (processing/failed) доступен только возврат в «Личная». templ LectureVisibilityToggle(vm LectureCardVM) { +
+ @visibilitySegment(vm, "private", "Личная", "Личная лекция", "Личная лекция — доступна только вам", nil) + @visibilitySegment(vm, "unlisted", "По ссылке", "Лекция по ссылке", "Лекция по ссылке — открыта всем, кто знает URL, но скрыта с Витрины", nil) + @visibilitySegment(vm, "public", "Витрина", "Опубликовать на Витрине", "Публичная лекция — на Витрине, видна всем", publicConfirmAttrs(vm)) +
+} + +// visibilitySegment — одна кнопка трёхпозиционного переключателя видимости. +templ visibilitySegment(vm LectureCardVM, target, label, titleText, ariaLabel string, extraAttrs templ.Attributes) { } -// LectureShareButton — копирование публичной ссылки на читалку. +// LectureShareButton — копирование ссылки на читалку (для unlisted и public). // Абсолютный URL собирается в браузере (location.origin + путь), // подтверждение — сменой иконки на галочку (класс ll-share--done). templ LectureShareButton(vm LectureCardVM) { @@ -336,45 +348,29 @@ func sourceLabel(sourceKind string) string { } } -// visibilityToggleClass возвращает CSS-класс тумблера в зависимости от видимости. -func visibilityToggleClass(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "ll-toggle--public" - } - return "ll-toggle--private" -} - -// visibilityLabel возвращает aria-label для тумблера видимости. -func visibilityLabel(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "Снять с публикации" - } - return "Опубликовать" +// visibilityVals — JSON для hx-vals с выбором видимости +// (handleSetVisibility читает form-поле "visibility") — без него кнопки не работают. +func visibilityVals(visibility string) string { + return fmt.Sprintf(`{"visibility":%q}`, visibility) } -// visibilityText возвращает текстовую метку тумблера. -func visibilityText(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "Публичная" +// pressedAttr возвращает значение aria-pressed для кнопки-переключателя. +func pressedAttr(active bool) string { + if active { + return "true" } - return "Личная" + return "false" } -// visibilityVals — JSON для hx-vals с целевым значением видимости -// (противоположным текущему): его ждёт handleSetVisibility. -func visibilityVals(vm LectureCardVM) string { +// publicConfirmAttrs — подтверждение только перед публикацией на общую Витрину. +// Уже публичная лекция подтверждения не требует: кнопка лишь показывает состояние. +func publicConfirmAttrs(vm LectureCardVM) templ.Attributes { if vm.Visibility == "public" { - return `{"visibility":"private"}` + return nil } - return `{"visibility":"public"}` -} - -// visibilityConfirm — текст подтверждения переключения видимости. -func visibilityConfirm(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "Сделать лекцию личной? Она исчезнет из витрины, ссылка на чтение перестанет работать." + return templ.Attributes{ + "hx-confirm": "Опубликовать лекцию на Витрине? Она станет видна всем посетителям и появится в общем каталоге.", } - return "Опубликовать лекцию? Она появится в витрине, читать сможет любой по ссылке." } // iconShare — иконка «поделиться» (цепочка-ссылка). diff --git a/internal/web/page_lectures_templ.go b/internal/web/page_lectures_templ.go index e82a922..d521882 100644 --- a/internal/web/page_lectures_templ.go +++ b/internal/web/page_lectures_templ.go @@ -21,7 +21,7 @@ type LectureCardVM struct { Status string // StatusLabel — локализованная метка статуса: «Обработка»/«Готово»/«Ошибка». StatusLabel string - // Visibility — видимость: private|public. + // Visibility — видимость: private|unlisted|public. Visibility string // SourceKind — тип источника: audio|video|video_url. SourceKind string @@ -283,7 +283,7 @@ func LectureCard(vm LectureCardVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - if vm.Visibility == "public" { + if vm.Visibility == "public" || vm.Visibility == "unlisted" { templ_7745c5c3_Err = LectureShareButton(vm).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err @@ -392,7 +392,7 @@ func LectureCard(vm LectureCardVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - if vm.CanPublish || vm.Visibility == "public" { + if vm.CanPublish || (vm.Visibility != "" && vm.Visibility != "private") { templ_7745c5c3_Err = LectureVisibilityToggle(vm).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err @@ -669,10 +669,11 @@ func LectureTitleInline(vm LectureCardVM) templ.Component { }) } -// LectureVisibilityToggle — тумблер переключения видимости лекции. -// Для public-лекции disabled если статус не ready. -// hx-vals обязателен: handleSetVisibility читает form-поле "visibility" -// с целевым значением (без него публикация из UI не работает). +// LectureVisibilityToggle — трёхпозиционный переключатель видимости лекции: +// «Личная» (private) / «По ссылке» (unlisted) / «Витрина» (public). +// Каждая неактивная кнопка шлёт hx-post с целевым значением и перерисовывает карточку; +// уже выбранный сегмент заблокирован, чтобы повторный клик не вызывал лишний запрос. +// Для неготовой лекции (processing/failed) доступен только возврат в «Личная». func LectureVisibilityToggle(vm LectureCardVM) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context @@ -694,126 +695,176 @@ func LectureVisibilityToggle(vm LectureCardVM) templ.Component { templ_7745c5c3_Var29 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - var templ_7745c5c3_Var30 = []any{"ll-toggle", visibilityToggleClass(vm)} - templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var30...) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var39 string + templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(label) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_lectures.templ`, Line: 218, Col: 9} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -821,7 +872,7 @@ func LectureVisibilityToggle(vm LectureCardVM) templ.Component { }) } -// LectureShareButton — копирование публичной ссылки на читалку. +// LectureShareButton — копирование ссылки на читалку (для unlisted и public). // Абсолютный URL собирается в браузере (location.origin + путь), // подтверждение — сменой иконки на галочку (класс ll-share--done). func LectureShareButton(vm LectureCardVM) templ.Component { @@ -840,25 +891,25 @@ func LectureShareButton(vm LectureCardVM) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var39 := templ.GetChildren(ctx) - if templ_7745c5c3_Var39 == nil { - templ_7745c5c3_Var39 = templ.NopComponent + templ_7745c5c3_Var40 := templ.GetChildren(ctx) + if templ_7745c5c3_Var40 == nil { + templ_7745c5c3_Var40 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -900,12 +951,12 @@ func LecturesEmpty() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var41 := templ.GetChildren(ctx) - if templ_7745c5c3_Var41 == nil { - templ_7745c5c3_Var41 = templ.NopComponent + templ_7745c5c3_Var42 := templ.GetChildren(ctx) + if templ_7745c5c3_Var42 == nil { + templ_7745c5c3_Var42 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -913,7 +964,7 @@ func LecturesEmpty() templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "

Пока нет ни одной лекции

Загрузите аудио или видео, чтобы получить конспект с тайм-кодами

Загрузить лекцию
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "

Пока нет ни одной лекции

Загрузите аудио или видео, чтобы получить конспект с тайм-кодами

Загрузить лекцию
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -1016,45 +1067,29 @@ func sourceLabel(sourceKind string) string { } } -// visibilityToggleClass возвращает CSS-класс тумблера в зависимости от видимости. -func visibilityToggleClass(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "ll-toggle--public" - } - return "ll-toggle--private" +// visibilityVals — JSON для hx-vals с выбором видимости +// (handleSetVisibility читает form-поле "visibility") — без него кнопки не работают. +func visibilityVals(visibility string) string { + return fmt.Sprintf(`{"visibility":%q}`, visibility) } -// visibilityLabel возвращает aria-label для тумблера видимости. -func visibilityLabel(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "Снять с публикации" +// pressedAttr возвращает значение aria-pressed для кнопки-переключателя. +func pressedAttr(active bool) string { + if active { + return "true" } - return "Опубликовать" + return "false" } -// visibilityText возвращает текстовую метку тумблера. -func visibilityText(vm LectureCardVM) string { +// publicConfirmAttrs — подтверждение только перед публикацией на общую Витрину. +// Уже публичная лекция подтверждения не требует: кнопка лишь показывает состояние. +func publicConfirmAttrs(vm LectureCardVM) templ.Attributes { if vm.Visibility == "public" { - return "Публичная" - } - return "Личная" -} - -// visibilityVals — JSON для hx-vals с целевым значением видимости -// (противоположным текущему): его ждёт handleSetVisibility. -func visibilityVals(vm LectureCardVM) string { - if vm.Visibility == "public" { - return `{"visibility":"private"}` + return nil } - return `{"visibility":"public"}` -} - -// visibilityConfirm — текст подтверждения переключения видимости. -func visibilityConfirm(vm LectureCardVM) string { - if vm.Visibility == "public" { - return "Сделать лекцию личной? Она исчезнет из витрины, ссылка на чтение перестанет работать." + return templ.Attributes{ + "hx-confirm": "Опубликовать лекцию на Витрине? Она станет видна всем посетителям и появится в общем каталоге.", } - return "Опубликовать лекцию? Она появится в витрине, читать сможет любой по ссылке." } // iconShare — иконка «поделиться» (цепочка-ссылка). @@ -1074,12 +1109,12 @@ func iconShare() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var42 := templ.GetChildren(ctx) - if templ_7745c5c3_Var42 == nil { - templ_7745c5c3_Var42 = templ.NopComponent + templ_7745c5c3_Var43 := templ.GetChildren(ctx) + if templ_7745c5c3_Var43 == nil { + templ_7745c5c3_Var43 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -1104,12 +1139,12 @@ func iconRetry() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var43 := templ.GetChildren(ctx) - if templ_7745c5c3_Var43 == nil { - templ_7745c5c3_Var43 = templ.NopComponent + templ_7745c5c3_Var44 := templ.GetChildren(ctx) + if templ_7745c5c3_Var44 == nil { + templ_7745c5c3_Var44 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -1134,12 +1169,12 @@ func iconTrash() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var44 := templ.GetChildren(ctx) - if templ_7745c5c3_Var44 == nil { - templ_7745c5c3_Var44 = templ.NopComponent + templ_7745c5c3_Var45 := templ.GetChildren(ctx) + if templ_7745c5c3_Var45 == nil { + templ_7745c5c3_Var45 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -1164,12 +1199,12 @@ func iconCheck() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var45 := templ.GetChildren(ctx) - if templ_7745c5c3_Var45 == nil { - templ_7745c5c3_Var45 = templ.NopComponent + templ_7745c5c3_Var46 := templ.GetChildren(ctx) + if templ_7745c5c3_Var46 == nil { + templ_7745c5c3_Var46 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 73, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/page_reader.templ b/internal/web/page_reader.templ index 284e9fc..b74fbb1 100644 --- a/internal/web/page_reader.templ +++ b/internal/web/page_reader.templ @@ -13,6 +13,8 @@ type ReaderVM struct { SourceKind string Duration int IsOwner bool + // Visibility — видимость лекции: private|unlisted|public. + Visibility string Sections []ReaderSectionVM } @@ -55,7 +57,7 @@ type ReaderMediaVM struct { // ReaderPage — страница «Читальный зал» с навигацией по конспекту. templ ReaderPage(data LayoutData, vm ReaderVM) { - @Layout(data, ReaderActions(vm)) { + @Layout(withReaderHead(data, vm.LectureID), ReaderActions(vm)) {
Прочитано0%
@@ -180,6 +185,16 @@ templ ReaderActions(vm ReaderVM) { Экспорт + MD +} + +// withReaderHead дополняет LayoutData ссылкой на Агентское представление +// Конспекта, чтобы всегда предлагал машиночитаемую альтернативу. +func withReaderHead(data LayoutData, lectureID string) LayoutData { + if data.AlternateMarkdownURL == "" && lectureID != "" { + data.AlternateMarkdownURL = "/read/" + lectureID + ".md" + } + return data } // ReaderMedia — нативный медиа-плеер с временным диапазоном фрагмента. @@ -251,3 +266,18 @@ func readerSourceLabel(kind string) string { } return "Видео" } + +// readerVisibilityLabel возвращает локализованную метку видимости лекции +// для бейджа в карточке источника (виден только владельцу). +func readerVisibilityLabel(visibility string) string { + switch visibility { + case "private": + return "Личная" + case "unlisted": + return "По ссылке" + case "public": + return "Публичная" + default: + return "" + } +} diff --git a/internal/web/page_reader_templ.go b/internal/web/page_reader_templ.go index 0ffb213..ef4c079 100644 --- a/internal/web/page_reader_templ.go +++ b/internal/web/page_reader_templ.go @@ -21,7 +21,9 @@ type ReaderVM struct { SourceKind string Duration int IsOwner bool - Sections []ReaderSectionVM + // Visibility — видимость лекции: private|unlisted|public. + Visibility string + Sections []ReaderSectionVM } // ReaderSectionVM — раздел конспекта в читалке. @@ -102,7 +104,7 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { var templ_7745c5c3_Var3 string templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(readerSourceLabel(vm.SourceKind)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 74, Col: 79} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 76, Col: 79} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) if templ_7745c5c3_Err != nil { @@ -115,7 +117,7 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { var templ_7745c5c3_Var4 string templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(vm.SourceTitle) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 75, Col: 30} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 77, Col: 30} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) if templ_7745c5c3_Err != nil { @@ -128,7 +130,7 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { var templ_7745c5c3_Var5 string templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(readerDurationLabel(vm.Duration)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 76, Col: 46} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 78, Col: 46} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) if templ_7745c5c3_Err != nil { @@ -139,12 +141,49 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { return templ_7745c5c3_Err } if vm.IsOwner { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "Владелец") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "Владелец ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } + if readerVisibilityLabel(vm.Visibility) != "" { + var templ_7745c5c3_Var6 = []any{"ll-reader-visibility", "ll-reader-visibility--" + vm.Visibility} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var6...) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(readerVisibilityLabel(vm.Visibility)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 82, Col: 127} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "
Прочитано0%
Содержание") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
Прочитано0%
Содержание") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -152,105 +191,105 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -258,121 +297,121 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "

Конспект лекции

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "

Конспект лекции

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var12 string - templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(vm.Title) + var templ_7745c5c3_Var15 string + templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(vm.Title) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 106, Col: 20} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 111, Col: 20} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var13 string - templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(vm.SourceTitle) + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(vm.SourceTitle) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 107, Col: 27} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 112, Col: 27} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, " · ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, " · ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var14 string - templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(readerDurationLabel(vm.Duration)) + var templ_7745c5c3_Var17 string + templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(readerDurationLabel(vm.Duration)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 107, Col: 67} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 112, Col: 67} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for _, section := range vm.Sections { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var15 string - templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(section.Number) + var templ_7745c5c3_Var18 string + templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(section.Number) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 112, Col: 69} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 117, Col: 69} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var16 string - templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(section.Title) + var templ_7745c5c3_Var19 string + templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(section.Title) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 112, Col: 97} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 117, Col: 97} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for _, sub := range section.Subtopics { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\">
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var18 string - templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(sub.Number) + var templ_7745c5c3_Var21 string + templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(sub.Number) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 115, Col: 36} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 120, Col: 36} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var19 string - templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(sub.Title) + var templ_7745c5c3_Var22 string + templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(sub.Title) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 115, Col: 60} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 120, Col: 60} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -385,51 +424,51 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { if len(sub.Blocks) > 0 { for _, part := range sub.Blocks { if part.Slide != nil { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
\"")
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" loading=\"lazy\">
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var22 string - templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Слайд %d", part.Slide.Num)) + var templ_7745c5c3_Var25 string + templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Слайд %d", part.Slide.Num)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 124, Col: 72} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 129, Col: 72} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else if part.HTML != "" { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -437,14 +476,14 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -452,101 +491,101 @@ func ReaderPage(data LayoutData, vm ReaderVM) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } if len(sub.SlideURLs) > 0 { - var templ_7745c5c3_Var23 = []any{"ll-reader-slides", templ.KV("ll-reader-slides--multi", len(sub.SlideURLs) > 1)} - templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var23...) + var templ_7745c5c3_Var26 = []any{"ll-reader-slides", templ.KV("ll-reader-slides--multi", len(sub.SlideURLs) > 1)} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_Var26...) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for slideIndex, slideURL := range sub.SlideURLs { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
\"")
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" loading=\"lazy\">
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var27 string - templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Слайд %d из %d", slideIndex+1, len(sub.SlideURLs))) + var templ_7745c5c3_Var30 string + templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Слайд %d из %d", slideIndex+1, len(sub.SlideURLs))) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 144, Col: 98} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 149, Col: 98} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "
LectureLog · Конспект лекции
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "
LectureLog · Конспект лекции
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = Layout(data, ReaderActions(vm)).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = Layout(withReaderHead(data, vm.LectureID), ReaderActions(vm)).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -571,12 +610,12 @@ func ReaderActions(vm ReaderVM) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var28 := templ.GetChildren(ctx) - if templ_7745c5c3_Var28 == nil { - templ_7745c5c3_Var28 = templ.NopComponent + templ_7745c5c3_Var31 := templ.GetChildren(ctx) + if templ_7745c5c3_Var31 == nil { + templ_7745c5c3_Var31 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, " Экспорт") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\">Экспорт MD") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -613,6 +665,15 @@ func ReaderActions(vm ReaderVM) templ.Component { }) } +// withReaderHead дополняет LayoutData ссылкой на Агентское представление +// Конспекта, чтобы всегда предлагал машиночитаемую альтернативу. +func withReaderHead(data LayoutData, lectureID string) LayoutData { + if data.AlternateMarkdownURL == "" && lectureID != "" { + data.AlternateMarkdownURL = "/read/" + lectureID + ".md" + } + return data +} + // ReaderMedia — нативный медиа-плеер с временным диапазоном фрагмента. func ReaderMedia(media ReaderMediaVM) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { @@ -630,105 +691,105 @@ func ReaderMedia(media ReaderMediaVM) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var30 := templ.GetChildren(ctx) - if templ_7745c5c3_Var30 == nil { - templ_7745c5c3_Var30 = templ.NopComponent + templ_7745c5c3_Var34 := templ.GetChildren(ctx) + if templ_7745c5c3_Var34 == nil { + templ_7745c5c3_Var34 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "\">
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var33 string - templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(readerSourceLabel(media.Kind)) + var templ_7745c5c3_Var37 string + templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(readerSourceLabel(media.Kind)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 188, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 203, Col: 73} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var34 string - templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(readerTimeRange(media.Start, media.End)) + var templ_7745c5c3_Var38 string + templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(readerTimeRange(media.Start, media.End)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 188, Col: 184} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `page_reader.templ`, Line: 203, Col: 184} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if media.Kind == "video" { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\" controls>") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "\" controls>") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -759,18 +820,18 @@ func readerBack(isOwner bool) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var37 := templ.GetChildren(ctx) - if templ_7745c5c3_Var37 == nil { - templ_7745c5c3_Var37 = templ.NopComponent + templ_7745c5c3_Var41 := templ.GetChildren(ctx) + if templ_7745c5c3_Var41 == nil { + templ_7745c5c3_Var41 = templ.NopComponent } ctx = templ.ClearChildren(ctx) if isOwner { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "← Мои лекции") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "← Мои лекции") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "← Витрина") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "← Витрина") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -796,12 +857,12 @@ func iconChevronDown() templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var38 := templ.GetChildren(ctx) - if templ_7745c5c3_Var38 == nil { - templ_7745c5c3_Var38 = templ.NopComponent + templ_7745c5c3_Var42 := templ.GetChildren(ctx) + if templ_7745c5c3_Var42 == nil { + templ_7745c5c3_Var42 = templ.NopComponent } ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -845,4 +906,19 @@ func readerSourceLabel(kind string) string { return "Видео" } +// readerVisibilityLabel возвращает локализованную метку видимости лекции +// для бейджа в карточке источника (виден только владельцу). +func readerVisibilityLabel(visibility string) string { + switch visibility { + case "private": + return "Личная" + case "unlisted": + return "По ссылке" + case "public": + return "Публичная" + default: + return "" + } +} + var _ = templruntime.GeneratedTemplate diff --git a/internal/web/page_reader_test.go b/internal/web/page_reader_test.go index e689039..c0b676c 100644 --- a/internal/web/page_reader_test.go +++ b/internal/web/page_reader_test.go @@ -53,6 +53,57 @@ func TestReaderPage_Render(t *testing.T) { } } +// TestReaderPage_OwnerVisibilityBadge проверяет, что владелец видит в карточке +// источника бейдж текущей видимости лекции, а посторонний читатель — нет. +func TestReaderPage_OwnerVisibilityBadge(t *testing.T) { + tests := []struct { + name string + visibility string + isOwner bool + wantLabel string + }{ + {name: "личная", visibility: "private", isOwner: true, wantLabel: "Личная"}, + {name: "по ссылке", visibility: "unlisted", isOwner: true, wantLabel: "По ссылке"}, + {name: "публичная", visibility: "public", isOwner: true, wantLabel: "Публичная"}, + {name: "не владелец", visibility: "unlisted", isOwner: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + vm := web.ReaderVM{ + LectureID: "lecture-42", + Title: "Лекция", + SourceTitle: "Источник", + SourceKind: "audio", + IsOwner: tt.isOwner, + Visibility: tt.visibility, + } + + var b bytes.Buffer + if err := web.ReaderPage(web.LayoutData{Title: vm.Title}, vm).Render(context.Background(), &b); err != nil { + t.Fatalf("ReaderPage.Render: %v", err) + } + html := b.String() + + if !tt.isOwner { + if strings.Contains(html, "ll-reader-visibility") || strings.Contains(html, "Владелец") { + t.Error("посторонний читатель не должен видеть бейдж владельца/видимости") + } + return + } + if !strings.Contains(html, "ll-reader-visibility--"+tt.visibility) { + t.Errorf("ожидается класс ll-reader-visibility--%s", tt.visibility) + } + if !strings.Contains(html, tt.wantLabel) { + t.Errorf("ожидается метка видимости %q", tt.wantLabel) + } + if !strings.Contains(html, "Владелец") { + t.Error("бейдж «Владелец» должен сохраняться") + } + }) + } +} + // TestReaderPage_RenderBlocks проверяет инлайн-кадры между HTML-блоками, // которые reader-сервис построил из маркеров . func TestReaderPage_RenderBlocks(t *testing.T) { @@ -96,6 +147,49 @@ func TestReaderPage_RenderBlocks(t *testing.T) { } } +// TestReaderPage_AgentMarkdownLink проверяет ссылку rel=alternate в +// и действие MD в шапке Читального зала. +func TestReaderPage_AgentMarkdownLink(t *testing.T) { + vm := web.ReaderVM{LectureID: "lecture-42", Title: "Лекция"} + + var b bytes.Buffer + if err := web.ReaderPage(web.LayoutData{Title: vm.Title}, vm).Render(context.Background(), &b); err != nil { + t.Fatalf("ReaderPage.Render: %v", err) + } + html := b.String() + + for _, want := range []string{ + ``, + `href="/read/lecture-42.md"`, + `aria-label="Открыть конспект в Markdown для ИИ-агента"`, + `>MD`, + } { + if !strings.Contains(html, want) { + t.Errorf("в рендере отсутствует %q", want) + } + } +} + +// TestReaderPage_AlternateMarkdownURLOverride проверяет, что явно заданная +// альтернативная ссылка не перезаписывается ID лекции. +func TestReaderPage_AlternateMarkdownURLOverride(t *testing.T) { + vm := web.ReaderVM{LectureID: "lecture-42", Title: "Лекция"} + data := web.LayoutData{Title: vm.Title, AlternateMarkdownURL: "/custom.md"} + + var b bytes.Buffer + if err := web.ReaderPage(data, vm).Render(context.Background(), &b); err != nil { + t.Fatalf("ReaderPage.Render: %v", err) + } + html := b.String() + + if !strings.Contains(html, ``) { + t.Error("в должна оставаться явно заданная ссылка") + } + if strings.Contains(html, ``) { + t.Error("явно заданная ссылка не должна перезаписываться") + } +} + // TestReaderPage_RenderEmptyData проверяет рендер без необязательных данных читалки. func TestReaderPage_RenderEmptyData(t *testing.T) { tests := []struct { diff --git a/internal/web/static/css/app.css b/internal/web/static/css/app.css index 0daaf78..e6d3b06 100644 --- a/internal/web/static/css/app.css +++ b/internal/web/static/css/app.css @@ -1,2 +1,2 @@ /*! tailwindcss v4.1.10 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial}}}@layer theme{:root,:host{--font-sans:var(--font-sans);--font-serif:var(--font-serif);--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}:root{color-scheme:light}[data-theme=dark]{color-scheme:dark}body{background:var(--bg);color:var(--ink);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;flex-direction:column;min-height:100vh;display:flex}::selection{background:var(--mark);color:var(--ink)}*{scrollbar-width:thin;scrollbar-color:var(--border-2)transparent}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-thumb{background:var(--border-2);background-clip:content-box;border:2px solid #0000;border-radius:5px}::-webkit-scrollbar-track{background:0 0}html{scroll-behavior:smooth}@media (prefers-reduced-motion:reduce){*,:before,:after{scroll-behavior:auto!important;transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}}@layer components{.ll-reader{font-family:var(--font-sans);color:var(--ink)}.ll-reader-progress{z-index:55;background:var(--rail);width:100%;height:3px;position:fixed;top:58px;left:0}.ll-reader-progress>div{background:var(--accent);width:0;height:100%;transition:width .12s linear}.ll-reader-export,.ll-reader-text-button{border:1px solid var(--border);border-radius:var(--r-btn);background:var(--surface);color:var(--text-2);font:600 13px var(--font-sans);cursor:pointer;padding:8px 12px;text-decoration:none}.ll-reader-export:hover,.ll-reader-text-button:hover{color:var(--ink);border-color:var(--border-2)}.ll-reader-search{z-index:70;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);width:min(480px,100vw - 26px);box-shadow:var(--shadow);align-items:center;gap:8px;padding:9px 10px;display:flex;position:fixed;top:66px;right:22px}.ll-reader-search-field{flex:1}.ll-reader-search input{border:1px solid var(--border-2);border-radius:var(--r-btn);background:var(--surface);width:100%;color:var(--ink);font:14px var(--font-sans);outline:none;padding:10px 13px}.ll-reader-search input:focus{border-color:var(--accent)}.ll-reader-search-count{min-width:58px;color:var(--text-3);text-align:right;font-variant-numeric:tabular-nums;font-size:12px}.ll-reader-layout{align-items:flex-start;gap:54px;display:flex}.ll-reader-sidebar{flex:0 0 280px;max-height:calc(100vh - 100px);padding:4px 12px 24px 0;position:sticky;top:82px;overflow:auto}.ll-reader-source-card{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);color:var(--text-2);flex-direction:column;gap:8px;padding:16px;font-size:13px;display:flex}.ll-reader-source-card strong{color:var(--ink);font-size:14px}.ll-reader-owner{color:var(--accent);font-weight:600}.ll-reader-reading{color:var(--text-3);margin:20px 0 25px;font-size:12px}.ll-reader-reading strong{float:right;color:var(--text-2);font-variant-numeric:tabular-nums}.ll-reader-reading div{clear:both;border-radius:var(--r-track);background:var(--rail);height:4px;margin-top:9px;overflow:hidden}.ll-reader-reading i{background:var(--accent);width:0;height:100%;display:block}.ll-reader-toc>p{color:var(--text-3);letter-spacing:.14em;text-transform:uppercase;margin:0 0 12px;font-size:10px;font-weight:700}.ll-reader-toc-section+.ll-reader-toc-section{margin-top:10px}.ll-reader-toc-section>div{color:var(--text-2);gap:9px;font-size:13px;display:flex}.ll-reader-toc-section>div span,.ll-reader-toc-link span{color:var(--text-3);font-variant-numeric:tabular-nums;flex:none}.ll-reader-toc-section ul{border-left:1px solid var(--border);margin:6px 0 0 9px;padding:0 0 0 12px;list-style:none}.ll-reader-toc-link{color:var(--text-2);border-left:2px solid #0000;gap:8px;padding:6px 0 6px 10px;font-size:13px;line-height:1.4;text-decoration:none;display:flex}.ll-reader-toc-link:hover,.ll-reader-toc-link.active{border-left-color:var(--accent);color:var(--accent)}.ll-reader-article{width:min(100%,720px);padding-bottom:60px}.ll-reader-doc-head{border-bottom:1px solid var(--border);padding:12px 0 46px}.ll-reader-doc-head p{color:var(--accent);letter-spacing:.14em;text-transform:uppercase;margin:0 0 10px;font-size:11px;font-weight:700}.ll-reader-doc-head h1{color:var(--ink);font:600 clamp(34px,5vw,52px)/1.08 var(--font-serif);letter-spacing:-.025em;margin:0}.ll-reader-doc-head div{color:var(--text-3);margin-top:17px;font-size:14px}.ll-reader-timeline{border-left:1px solid var(--rail);margin-top:45px;padding-left:32px;position:relative}.ll-reader-section+.ll-reader-section{margin-top:58px}.ll-reader-section-head{align-items:baseline;gap:15px;margin-left:-33px;display:flex}.ll-reader-section-head span{color:var(--accent);font-variant-numeric:tabular-nums;font-size:13px;font-weight:700}.ll-reader-section-head h2{font:600 27px/1.22 var(--font-serif);letter-spacing:-.015em;margin:0}.ll-reader-sub{margin-top:35px;scroll-margin-top:82px;position:relative}.ll-reader-sub:before{border:2px solid var(--bg);background:var(--accent);content:"";border-radius:50%;width:9px;height:9px;position:absolute;top:9px;left:-37px}.ll-reader-sub>header{align-items:baseline;gap:12px;display:flex}.ll-reader-sub>header span{color:var(--text-3);font-variant-numeric:tabular-nums;font-size:13px}.ll-reader-sub h3{color:var(--ink);font:600 22px/1.3 var(--font-serif);margin:0}.ll-reader-prose{color:var(--ink);font:18px/1.72 var(--font-serif)}.ll-reader-prose>:first-child{margin-top:15px}.ll-reader-prose a{color:var(--accent)}.ll-reader-prose blockquote,.ll-reader-prose details{border-left:3px solid var(--accent);border-radius:0 var(--r-card)var(--r-card)0;background:var(--accent-soft);margin:18px 0;padding:14px 17px}.ll-reader-player{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);margin-top:18px;padding:13px}.ll-reader-player>div{color:var(--text-3);font-variant-numeric:tabular-nums;justify-content:space-between;margin-bottom:9px;font-size:12px;display:flex}.ll-reader-media-kind{color:var(--accent);font-weight:700}.ll-reader-player audio,.ll-reader-player video{width:100%;max-height:330px;display:block}.ll-reader-slide{border:1px solid var(--border);border-radius:var(--r-slide);background:var(--surface);margin:22px 0;overflow:hidden}.ll-reader-slide img{cursor:zoom-in;width:100%;display:block}.ll-reader-slide figcaption{color:var(--text-3);padding:9px 13px;font-size:12px}.ll-reader-foot{border-top:1px solid var(--border);color:var(--text-3);margin-top:58px;padding-top:18px;font-size:12px}.ll-reader-lightbox[hidden]{display:none}.ll-reader-lightbox{z-index:90;background:var(--ink);place-items:center;padding:4vw;display:grid;position:fixed;inset:0}@supports (color:color-mix(in lab, red, red)){.ll-reader-lightbox{background:color-mix(in srgb,var(--ink)76%,transparent)}}.ll-reader-lightbox{cursor:zoom-out}.ll-reader-lightbox img{border-radius:var(--r-slide);max-width:100%;max-height:90vh;box-shadow:var(--shadow)}.ll-reader-lightbox-close{border:1px solid var(--bg);border-radius:var(--r-btn);min-width:40px;min-height:40px;color:var(--bg);cursor:pointer;font-size:28px;line-height:1;position:absolute;top:22px;right:22px}.ll-reader-lightbox-close:focus-visible{outline:2px solid var(--bg);outline-offset:3px}.ll-reader-prose mark{background:var(--mark);color:var(--ink);-webkit-box-decoration-break:clone;box-decoration-break:clone;border-radius:3px;margin:-.05em;padding:.05em .15em}.ll-reader-prose mark.ll-reader-mark-current{background:var(--mark-cur);box-shadow:0 0 0 2px var(--mark-cur)}@media (max-width:880px){.ll-reader-layout{display:block}.ll-reader-sidebar{width:100%;max-height:none;margin-bottom:34px;padding:0;position:static}.ll-reader-article{width:100%}}@media (max-width:620px){.ll-reader-search{right:13px}.ll-reader-search-count{display:none}.ll-reader-layout{gap:0}.ll-reader-timeline{padding-left:26px}.ll-reader-sub:before{left:-31px}.ll-reader-doc-head h1{font-size:35px}}.ll-topbar{z-index:50;background:var(--bg-2);height:58px;position:sticky;top:0}@supports (color:color-mix(in lab, red, red)){.ll-topbar{background:color-mix(in srgb,var(--bg-2)86%,transparent)}}.ll-topbar{-webkit-backdrop-filter:saturate(1.05)blur(12px);backdrop-filter:saturate(1.05)blur(12px);border-bottom:1px solid var(--border)}.ll-topbar-inner{max-width:1240px;height:58px;font-family:var(--font-sans);align-items:center;gap:14px;margin:0 auto;padding:0 22px;display:flex}.ll-brand{flex:1;align-items:center;gap:11px;min-width:0;display:flex}.ll-brand-mark{background:var(--accent);width:24px;height:24px;color:var(--bg);border-radius:6px;flex:none;justify-content:center;align-items:center;display:flex}.ll-brand-mark svg{width:15px;height:15px}.ll-brand-t{color:var(--ink);white-space:nowrap;letter-spacing:-.02em;font-size:15px;font-weight:600}.ll-top-actions{flex:none;align-items:center;gap:8px;display:flex}.ll-icon-btn{width:37px;height:37px;color:var(--text-2);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:10px;justify-content:center;align-items:center;transition:all .16s;display:inline-flex}.ll-icon-btn:hover{background:var(--surface-2);color:var(--ink)}.ll-icon-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-icon-btn svg{width:18px;height:18px;display:block}.ll-icon-moon,.ll-icon-sun{display:block}[data-theme=light] .ll-icon-sun,:root:not([data-theme=dark]) .ll-icon-sun,[data-theme=dark] .ll-icon-moon{display:none}[data-theme=dark] .ll-icon-sun{display:block}.ll-main{max-width:1240px;margin:0 auto;padding:34px 22px 120px}.ll-demo-content{max-width:768px;font-family:var(--font-serif);color:var(--ink);margin:0 auto}.ll-demo-content h1{letter-spacing:-.02em;margin-bottom:16px;font-size:43px;font-weight:600;line-height:1.12}.ll-demo-content p{color:var(--text-2);font-size:19px;line-height:1.78}.ll-lectures-section{width:100%}.ll-lec-grid{grid-template-columns:repeat(auto-fill,minmax(252px,1fr));gap:16px;display:grid}.ll-lec-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);flex-direction:column;gap:10px;padding:16px;transition:border-color .16s,box-shadow .16s,transform .16s;display:flex}.ll-lec-card:hover{border-color:var(--accent);box-shadow:var(--shadow);transform:translateY(-1px)}.ll-hub-card{color:inherit;text-decoration:none}.ll-hub-card:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-lec-card-top{justify-content:space-between;align-items:center;gap:8px;display:flex}.ll-lec-card-actions{align-items:center;gap:4px;display:flex}.ll-lec-card-body{flex-direction:column;flex:1;gap:6px;display:flex}.ll-lec-card-footer{justify-content:space-between;align-items:center;gap:8px;margin-top:auto;display:flex}.ll-badge{border-radius:var(--r-pill);font-family:var(--font-sans);background:var(--accent-soft);color:var(--accent);align-items:center;padding:2px 8px;font-size:12px;font-weight:500;display:inline-flex}.ll-badge--muted{background:var(--surface-2);color:var(--text-2)}.ll-status{font-family:var(--font-sans);font-size:12.5px;font-weight:500}.ll-status--processing{color:var(--text-2);animation:1.8s ease-in-out infinite ll-pulse}@keyframes ll-pulse{0%,to{opacity:1}50%{opacity:.5}}.ll-status--ready{color:var(--accent);background:var(--accent-soft);border-radius:var(--r-pill);padding:2px 6px;display:inline-block}.ll-status--failed{color:var(--text-3)}.ll-lec-bar{border-radius:var(--r-track);background:var(--surface-2);border:1px solid var(--border);height:4px;margin-top:6px;overflow:hidden}.ll-lec-bar>i{background:var(--accent);height:100%;transition:width .3s;display:block}.ll-lec-error{font-family:var(--font-sans);color:var(--text-3);font-size:12px;line-height:1.4}.ll-lec-title{font-family:var(--font-serif);color:var(--ink);-webkit-line-clamp:2;resize:none;background:0 0;border:none;outline:none;-webkit-box-orient:vertical;width:100%;padding:0;font-size:16.5px;font-weight:600;line-height:1.35;display:-webkit-box;overflow:hidden}.ll-lec-title:focus{outline:1px solid var(--border-2);-webkit-line-clamp:unset;border-radius:3px}.ll-lec-title-form{align-items:flex-start;gap:4px;display:flex}.ll-lec-rename-btn{border:1px solid var(--border);background:var(--surface-2);width:28px;height:28px;color:var(--text-2);cursor:pointer;opacity:0;border-radius:6px;flex:none;justify-content:center;align-items:center;transition:opacity .12s;display:inline-flex}.ll-lec-title-form:focus-within .ll-lec-rename-btn{opacity:1}.ll-lec-rename-btn svg{width:14px;height:14px}.ll-lec-meta{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;font-size:12.5px}.ll-hub-author{min-width:0;font-family:var(--font-sans);color:var(--text-2);align-items:center;gap:7px;font-size:12.5px;display:inline-flex}.ll-hub-avatar{border:1px solid var(--border);object-fit:cover;border-radius:50%;flex:none;width:22px;height:22px}.ll-toggle{border-radius:var(--r-pill);border:1px solid var(--border);background:var(--surface-2);color:var(--text-2);font-family:var(--font-sans);cursor:pointer;align-items:center;min-height:26px;padding:3px 10px;font-size:12px;font-weight:500;transition:all .16s;display:inline-flex}.ll-toggle:hover:not(:disabled){background:var(--surface);border-color:var(--accent);color:var(--accent)}.ll-toggle:disabled{opacity:.5;cursor:not-allowed}.ll-toggle--public{background:var(--accent-soft);border-color:var(--accent-soft);color:var(--accent)}.ll-empty{text-align:center;flex-direction:column;justify-content:center;align-items:center;gap:16px;padding:80px 24px;display:flex}.ll-empty-icon{width:48px;height:48px;color:var(--text-3)}.ll-empty-title{font-family:var(--font-serif);color:var(--ink);margin:0;font-size:22px;font-weight:600}.ll-empty-text{font-family:var(--font-sans);color:var(--text-2);max-width:360px;margin:0;font-size:15px;line-height:1.6}.ll-btn{border-radius:var(--r-btn);font-family:var(--font-sans);cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;min-height:40px;padding:9px 20px;font-size:14px;font-weight:500;text-decoration:none;transition:all .16s;display:inline-flex}.ll-btn--accent{background:var(--accent);color:var(--bg)}.ll-btn--accent:hover{background:var(--accent-2)}.ll-upload{width:100%;max-width:660px;font-family:var(--font-sans);color:var(--ink);margin:0 auto}.ll-upload-hidden{display:none!important}.ll-upload-head{margin-bottom:22px}.ll-upload-kicker{letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin-bottom:16px;font-size:11.5px;font-weight:600}.ll-upload-title{font-family:var(--font-serif);letter-spacing:0;color:var(--ink);margin:0 0 16px;font-size:43px;font-weight:600;line-height:1.12}.ll-upload-dek{font-family:var(--font-serif);color:var(--text-2);max-width:54ch;margin:0;font-size:20px;font-style:italic;line-height:1.55}.ll-upload-seg{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--r-card);gap:3px;margin-bottom:22px;padding:3px;display:inline-flex}.ll-upload-seg-btn{font-family:var(--font-sans);color:var(--text-2);border-radius:var(--r-pill);cursor:pointer;background:0 0;border:none;align-items:center;gap:7px;padding:8px 18px;font-size:13px;font-weight:500;transition:all .14s;display:inline-flex}.ll-upload-seg-btn:hover,.ll-upload-seg-btn:focus-visible{color:var(--ink)}.ll-upload-seg-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-seg-btn svg{width:15px;height:15px}.ll-upload-seg-btn--active{background:var(--surface);color:var(--ink);box-shadow:var(--shadow)}.ll-upload-drop{border:1.5px dashed var(--border-2);border-radius:var(--r-card);background:var(--surface);text-align:center;padding:52px 40px;transition:border-color .18s,background .18s}.ll-upload-drop--over{border-color:var(--accent);background:var(--accent-soft)}.ll-upload-drop--error{border-color:var(--border-2)}.ll-upload-drop-icon{background:var(--accent-soft);width:58px;height:58px;color:var(--accent);border-radius:50%;justify-content:center;align-items:center;margin-bottom:18px;transition:transform .18s;display:inline-flex}.ll-upload-drop--over .ll-upload-drop-icon{transform:translateY(-3px)}.ll-upload-drop-icon svg{width:26px;height:26px}.ll-upload-drop-title{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;margin:0 0 4px;font-size:21px;font-weight:600}.ll-upload-drop-sub{color:var(--text-2);margin:0 0 18px;font-size:13.5px}.ll-upload-pick{border:1px solid var(--border-2);background:var(--bg);border-radius:var(--r-btn);min-height:38px;color:var(--ink);cursor:pointer;font-family:var(--font-sans);align-items:center;gap:8px;padding:0 18px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex}.ll-upload-pick:hover,.ll-upload-pick:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-upload-pick:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-pick svg{width:15px;height:15px}.ll-upload-formats{color:var(--text-3);font-variant-numeric:tabular-nums;margin:18px 0 0;font-size:12px}.ll-upload-file{text-align:left;align-items:center;gap:14px;display:flex}.ll-upload-file-icon{border-radius:var(--r-btn);background:var(--accent-soft);width:46px;height:46px;color:var(--accent);flex:none;justify-content:center;align-items:center;display:inline-flex}.ll-upload-file-icon svg{width:22px;height:22px}.ll-upload-file-meta{flex:1;min-width:0}.ll-upload-file-name{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;white-space:nowrap;text-overflow:ellipsis;font-size:18px;font-weight:600;overflow:hidden}.ll-upload-file-sub{color:var(--text-3);font-variant-numeric:tabular-nums;margin-top:3px;font-size:12.5px}.ll-upload-file-bar{border-radius:var(--r-track);background:var(--surface-2);border:1px solid var(--border);height:4px;margin-top:13px;overflow:hidden}.ll-upload-file-bar>i{background:var(--accent);width:100%;height:100%;display:block}.ll-upload-file-remove{border-radius:var(--r-btn);border:1px solid var(--border-2);width:40px;height:40px;color:var(--text-2);cursor:pointer;background:0 0;flex:none;justify-content:center;align-items:center;transition:all .14s;display:inline-flex}.ll-upload-file-remove:hover,.ll-upload-file-remove:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-upload-file-remove:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-file-remove svg{width:15px;height:15px}.ll-upload-errnote{color:var(--text-2);background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-btn);text-align:left;margin-top:16px;padding:10px 13px;font-size:13px;line-height:1.45;display:none}.ll-upload-errnote--show{display:block}.ll-upload-url-field{background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-card);align-items:center;gap:11px;min-height:54px;padding:0 15px;display:flex}.ll-upload-url-field svg{width:18px;height:18px;color:var(--text-3);flex:none}.ll-upload-url-field input{min-width:0;color:var(--ink);font-family:var(--font-sans);background:0 0;border:none;outline:none;flex:1;font-size:15px}.ll-upload-url-field input::placeholder{color:var(--text-3)}.ll-upload-url-hint{color:var(--text-3);margin:12px 2px 0;font-size:12.5px}.ll-upload-options{border-top:1px solid var(--border);gap:18px;margin-top:26px;padding-top:22px;display:grid}.ll-upload-check,.ll-upload-switch-row{cursor:pointer;align-items:flex-start;gap:14px;display:flex}.ll-upload-check input{opacity:0;pointer-events:none;position:absolute}.ll-upload-check-box{border:1px solid var(--border-2);border-radius:var(--r-pill);background:var(--surface-2);flex:none;width:23px;height:23px;margin-top:2px}.ll-upload-check input:checked+.ll-upload-check-box{background:var(--accent);border-color:var(--accent);box-shadow:inset 0 0 0 5px var(--surface)}.ll-upload-check input:focus-visible+.ll-upload-check-box{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-slides-option{gap:12px;display:grid}.ll-upload-slides{border:1px dashed var(--border-2);border-radius:var(--r-card);background:var(--surface-2);margin-left:37px;padding:14px 16px}.ll-upload-slides-pick,.ll-upload-slides-file button{border:1px solid var(--border-2);border-radius:var(--r-btn);background:var(--surface);color:var(--ink);font:600 13px var(--font-sans);cursor:pointer}.ll-upload-slides-pick{min-height:38px;padding:0 16px}.ll-upload-slides-file{color:var(--ink);justify-content:space-between;align-items:center;gap:12px;font-size:13px}.ll-upload-slides-file:not(.ll-upload-hidden){display:flex}.ll-upload-slides-file span{overflow-wrap:anywhere;min-width:0}.ll-upload-slides-file button{color:var(--text-2);flex:none;padding:7px 11px}.ll-upload-slides>p{color:var(--text-3);margin:8px 0 0;font-size:12px}.ll-upload-opt-title,.ll-upload-opt-text{display:block}.ll-upload-opt-title{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;font-size:17px;font-weight:600}.ll-upload-opt-text{color:var(--text-2);max-width:46ch;margin-top:3px;font-size:13px;line-height:1.5}.ll-upload-switch-row{justify-content:space-between}.ll-upload-switch-input{opacity:0;pointer-events:none;position:absolute}.ll-upload-switch{border-radius:var(--r-pill);background:var(--surface-2);border:1px solid var(--border-2);flex:none;width:44px;height:25px;margin-top:2px;transition:all .18s;position:relative}.ll-upload-switch:after{content:"";background:var(--bg);width:19px;height:19px;box-shadow:var(--shadow);border-radius:50%;transition:all .18s;position:absolute;top:2px;left:2px}.ll-upload-switch-input:checked+.ll-upload-switch{background:var(--accent);border-color:var(--accent)}.ll-upload-switch-input:checked+.ll-upload-switch:after{background:var(--surface);left:21px}.ll-upload-switch-input:disabled+.ll-upload-switch{opacity:.5;cursor:not-allowed}.ll-upload-switch-input:focus-visible+.ll-upload-switch{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-cta-row{align-items:center;gap:18px;margin-top:34px;display:flex}.ll-upload-cta{border-radius:var(--r-btn);background:var(--accent);min-height:50px;color:var(--bg);cursor:pointer;font-family:var(--font-sans);border:none;justify-content:center;align-items:center;gap:10px;padding:0 30px;font-size:14.5px;font-weight:600;transition:all .16s;display:inline-flex}.ll-upload-cta:hover:not(:disabled),.ll-upload-cta:focus-visible:not(:disabled){background:var(--accent-2)}.ll-upload-cta:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-cta:disabled{opacity:.42;cursor:not-allowed;background:var(--accent)}.ll-upload-cta svg{width:17px;height:17px}.ll-upload-cta-note{color:var(--text-3);font-size:12.5px;line-height:1.45}@media (max-width:620px){.ll-upload-title{font-size:30px}.ll-upload-dek{font-size:18px}.ll-upload-drop{padding:40px 22px}.ll-upload-cta-row{flex-direction:column;align-items:stretch}.ll-upload-cta{width:100%}}.ll-settings{width:100%;max-width:660px;font-family:var(--font-sans);color:var(--ink);margin:0 auto}.ll-settings-head{margin-bottom:22px}.ll-settings-kicker{letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin-bottom:16px;font-size:11.5px;font-weight:600}.ll-settings-title{font-family:var(--font-serif);letter-spacing:0;color:var(--ink);margin:0;font-size:43px;font-weight:600;line-height:1.12}.ll-settings-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);padding:24px 26px}.ll-settings-card-title{font-family:var(--font-serif);letter-spacing:-.015em;color:var(--ink);margin:0 0 6px;font-size:28px;font-weight:600;line-height:1.18}.ll-settings-card-sub{color:var(--text-2);margin:0 0 20px;font-size:14px;line-height:1.5}.ll-settings-warning{background:var(--surface-2);border-left:3px solid var(--border-2);border-radius:0 var(--r-btn)var(--r-btn)0;align-items:flex-start;gap:12px;margin-bottom:18px;padding:14px 16px;display:flex}.ll-settings-warning-icon{width:18px;height:18px;color:var(--text-2);flex:none;margin-top:1px}.ll-settings-warning-icon svg{width:18px;height:18px;display:block}.ll-settings-warning-kicker{letter-spacing:.14em;text-transform:uppercase;color:var(--text-2);margin-bottom:4px;font-size:11px;font-weight:700}.ll-settings-warning-text{color:var(--text-2);margin:0;font-size:13.5px;line-height:1.55}.ll-settings-status{border-bottom:1px solid var(--border);align-items:flex-start;gap:12px;margin-bottom:20px;padding:14px 0;display:flex}.ll-settings-status-dot{border:1.5px solid var(--border-2);background:0 0;border-radius:50%;flex:none;width:12px;height:12px;margin-top:4px}.ll-settings-status-dot--filled{border-color:var(--accent);background:var(--accent)}.ll-settings-status-body{flex:1;min-width:0}.ll-settings-status-title{font-family:var(--font-serif);color:var(--ink);font-size:17px;font-weight:600}.ll-settings-status-meta{color:var(--text-3);font-variant-numeric:tabular-nums;margin-top:3px;font-size:12.5px}.ll-settings-delete{border:1px solid var(--border-2);border-radius:var(--r-btn);min-height:37px;color:var(--text-2);font-family:var(--font-sans);cursor:pointer;background:0 0;flex:none;align-items:center;gap:7px;padding:0 14px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex}.ll-settings-delete:hover,.ll-settings-delete:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-settings-delete:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-delete svg{width:15px;height:15px}.ll-settings-status--error{border-bottom-color:var(--border)}.ll-settings-status-icon{width:18px;height:18px;color:var(--text-2);flex:none;margin-top:2px}.ll-settings-status-icon svg{width:18px;height:18px;display:block}.ll-settings-status--error .ll-settings-status-title{font-family:var(--font-sans);color:var(--ink);font-size:14px;font-weight:500}.ll-settings-form{padding-top:4px}.ll-settings-file-label{color:var(--ink);margin-bottom:10px;font-size:13px;font-weight:600;display:block}.ll-settings-file-row{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.ll-settings-file-pick{border:1px solid var(--border-2);background:var(--bg);border-radius:var(--r-btn);min-height:38px;color:var(--ink);cursor:pointer;font-family:var(--font-sans);align-items:center;gap:8px;padding:0 18px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex;position:relative}.ll-settings-file-pick:hover{border-color:var(--accent);color:var(--accent)}.ll-settings-file-pick svg{width:15px;height:15px}.ll-settings-file-input{opacity:0;cursor:pointer;width:100%;height:100%;position:absolute;inset:0}.ll-settings-file-input:focus-visible+span{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-file-name{color:var(--text-3);text-overflow:ellipsis;white-space:nowrap;min-width:0;font-size:13px;overflow:hidden}.ll-settings-file-hint{color:var(--text-2);max-width:58ch;margin:14px 0 0;font-size:12.5px;line-height:1.55}.ll-settings-file-formats{color:var(--text-3);font-variant-numeric:tabular-nums;margin:8px 0 0;font-size:12px}.ll-settings-cta-row{align-items:center;gap:14px;margin-top:20px;display:flex}.ll-settings-cta{border-radius:var(--r-btn);background:var(--accent);min-height:44px;color:var(--bg);cursor:pointer;font-family:var(--font-sans);border:none;padding:0 24px;font-size:13.5px;font-weight:600;transition:all .16s}.ll-settings-cta:hover:not(:disabled),.ll-settings-cta:focus-visible:not(:disabled){background:var(--accent-2)}.ll-settings-cta:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-cta:disabled{opacity:.55;cursor:not-allowed}.ll-settings-indicator{color:var(--text-2);opacity:0;align-items:center;gap:7px;font-size:12.5px;display:inline-flex}.ll-settings-indicator.htmx-request{opacity:1}.ll-settings-spinner{width:14px;height:14px;animation:.8s linear infinite ll-spin}@keyframes ll-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (max-width:620px){.ll-settings-title{font-size:30px}.ll-settings-card{padding:20px}.ll-settings-status{flex-wrap:wrap}.ll-settings-delete{justify-content:center;width:100%}}.ll-main{flex:1 0 auto;width:100%}.ll-brand{color:inherit;border-radius:var(--r-btn);flex:none;margin-left:-2px;padding:5px 8px 5px 2px;text-decoration:none}.ll-brand:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-brand:hover .ll-brand-t{color:var(--accent)}.ll-brand-t{transition:color .16s}.ll-nav{min-width:0;font-family:var(--font-sans);scrollbar-width:none;flex:1;align-items:center;gap:2px;margin-left:8px;display:flex;overflow-x:auto}.ll-nav::-webkit-scrollbar{display:none}.ll-nav-link{border-radius:var(--r-btn);color:var(--text-2);white-space:nowrap;padding:8px 11px;font-size:13.5px;font-weight:500;text-decoration:none;transition:color .16s,background .16s;position:relative}.ll-nav-link:hover{color:var(--ink);background:var(--surface-2)}.ll-nav-link:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-nav-link--active{color:var(--ink)}.ll-nav-link--active:after{content:"";background:var(--accent);border-radius:1px;height:2px;position:absolute;bottom:3px;left:11px;right:11px}.ll-btn--login{border:1px solid var(--border-2);background:var(--surface);min-height:34px;color:var(--ink);padding:5px 15px;font-size:13.5px}.ll-btn--login:hover{border-color:var(--accent);color:var(--accent)}.ll-logout-form{display:contents}.ll-btn{gap:8px}.ll-btn svg{width:16px;height:16px}.ll-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-btn--lg{min-height:50px;padding:0 28px;font-size:14.5px;font-weight:600}.ll-footer{border-top:1px solid var(--border);font-family:var(--font-sans)}.ll-footer-inner{flex-wrap:wrap;align-items:center;gap:18px;max-width:1240px;margin:0 auto;padding:24px 22px 32px;display:flex}.ll-footer-brand{color:var(--ink);align-items:center;gap:9px;font-size:13.5px;font-weight:600;display:inline-flex}.ll-footer-brand .ll-brand-mark{border-radius:5px;width:20px;height:20px}.ll-footer-brand .ll-brand-mark svg{width:12px;height:12px}.ll-footer-tag{min-width:240px;color:var(--text-3);flex:1;margin:0;font-size:12.5px}.ll-footer-link{color:var(--text-2);border-bottom:1px solid #0000;font-size:12.5px;text-decoration:none;transition:all .16s}.ll-footer-link:hover{color:var(--accent);border-bottom-color:var(--accent)}.ll-footer-links{flex-wrap:wrap;align-items:center;gap:16px;display:flex}.ll-footer-link--ext{align-items:center;gap:6px;display:inline-flex}.ll-footer-link--ext svg{flex-shrink:0;width:14px;height:14px}.ll-footer-link--icon{border-bottom:none;padding:3px}.ll-footer-link--icon:hover{border-bottom-color:#0000}.ll-footer-link--icon svg{width:18px;height:18px}.ll-hero{text-align:center;margin-bottom:84px;padding-top:44px}.ll-hero-kicker{font-family:var(--font-sans);letter-spacing:.18em;text-transform:uppercase;color:var(--accent);margin:0 0 18px;font-size:11.5px;font-weight:600}.ll-hero-title{font-family:var(--font-serif);letter-spacing:-.025em;color:var(--ink);max-width:21ch;margin:0 auto 20px;font-size:clamp(36px,5.2vw,56px);font-weight:600;line-height:1.08}.ll-hero-dek{font-family:var(--font-serif);color:var(--text-2);max-width:52ch;margin:0 auto 30px;font-size:20px;font-style:italic;line-height:1.6}.ll-hero-cta{flex-wrap:wrap;justify-content:center;align-items:center;gap:16px;margin-bottom:64px;display:flex}.ll-hero-note{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;font-size:12.5px}.ll-hero-steps{border-top:1px solid var(--border);text-align:left;grid-template-columns:repeat(3,1fr);gap:28px;margin:0;padding:30px 0 0;list-style:none;display:grid}.ll-hero-step-num{font-family:var(--font-sans);color:var(--accent);font-variant-numeric:tabular-nums;margin-bottom:8px;font-size:13px;font-weight:700;display:block}.ll-hero-step-title{font-family:var(--font-serif);color:var(--ink);margin-bottom:6px;font-size:18px;font-weight:600;display:block}.ll-hero-step-text{font-family:var(--font-sans);color:var(--text-2);margin:0;font-size:13.5px;line-height:1.55}.ll-section-head{align-items:baseline;gap:12px;margin-bottom:18px;display:flex}.ll-section-title{font-family:var(--font-serif);letter-spacing:-.01em;color:var(--ink);margin:0;font-size:22px;font-weight:600;line-height:1.2}.ll-section-count{font-family:var(--font-sans);color:var(--accent);background:var(--accent-soft);border-radius:var(--r-pill);font-variant-numeric:tabular-nums;padding:2px 9px;font-size:12.5px;font-weight:600}.ll-page-head{flex-wrap:wrap;justify-content:space-between;align-items:flex-end;gap:18px;margin-bottom:26px;display:flex}.ll-page-kicker{font-family:var(--font-sans);letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin:0 0 10px;font-size:11.5px;font-weight:600}.ll-page-title{font-family:var(--font-serif);letter-spacing:-.02em;color:var(--ink);margin:0;font-size:36px;font-weight:600;line-height:1.1}.ll-page-sub{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;margin:8px 0 0;font-size:13px}.ll-page-head-cta{flex:none}.ll-hub-card-arrow{width:26px;height:26px;color:var(--accent);opacity:0;border-radius:50%;justify-content:center;align-items:center;transition:opacity .18s,transform .18s;display:inline-flex;transform:translate(-4px)}.ll-hub-card-arrow svg{width:16px;height:16px}.ll-hub-card:hover .ll-hub-card-arrow,.ll-hub-card:focus-visible .ll-hub-card-arrow{opacity:1;transform:none}.ll-hub-avatar--ph{background:var(--accent-soft);color:var(--accent);justify-content:center;align-items:center;font-size:11px;font-weight:600;line-height:1;display:inline-flex}.ll-hub-author-name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.ll-empty-icon{background:var(--surface);border:1px solid var(--border);width:74px;height:74px;color:var(--text-3);border-radius:50%;justify-content:center;align-items:center;display:flex}.ll-empty-icon svg{width:30px;height:30px}.ll-empty--404{padding-top:70px}.ll-404-code{font-family:var(--font-serif);letter-spacing:-.04em;color:var(--border-2);font-variant-numeric:tabular-nums;font-size:96px;font-weight:600;line-height:1}@media (max-width:640px){.ll-topbar-inner{gap:8px;padding:0 13px}.ll-brand-t{display:none}.ll-nav{margin-left:0}.ll-nav-link{padding:8px 9px;font-size:13px}.ll-main,.ll-footer-inner{padding-left:13px;padding-right:13px}.ll-hero{text-align:left;margin-bottom:60px;padding-top:26px}.ll-hero-title,.ll-hero-dek{margin-left:0;margin-right:0}.ll-hero-cta{justify-content:flex-start;margin-bottom:44px}.ll-hero-steps{grid-template-columns:1fr;gap:22px}.ll-page-title{font-size:30px}.ll-page-head-cta{justify-content:center;width:100%}}.ll-lec-title{text-overflow:ellipsis}.ll-status-row{justify-content:space-between;align-items:center;gap:10px;display:flex}.ll-lec-read{font-family:var(--font-sans);color:var(--accent);border-radius:var(--r-pill);align-items:center;gap:5px;font-size:13px;font-weight:600;text-decoration:none;transition:gap .16s,color .16s;display:inline-flex}.ll-lec-read svg{width:14px;height:14px;transition:transform .16s}.ll-lec-read:hover{color:var(--accent-2)}.ll-lec-read:hover svg{transform:translate(2px)}.ll-lec-read:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-landing{max-width:980px;margin:0 auto}.ll-btn--ghost{border:1px solid var(--border-2);background:var(--surface);color:var(--ink)}.ll-btn--ghost:hover{border-color:var(--accent);color:var(--accent)}.ll-land-section{border-top:1px solid var(--border);padding:46px 0 54px}.ll-landing .ll-hero{margin-bottom:0;padding-bottom:64px}.ll-landing .ll-hero-cta{margin-bottom:0}.ll-land-title{font-family:var(--font-serif);letter-spacing:-.015em;color:var(--ink);margin:0 0 26px;font-size:26px;font-weight:600;line-height:1.2}.ll-land-formats{grid-template-columns:repeat(3,1fr);gap:16px;display:grid}.ll-land-format{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);font-family:var(--font-sans);flex-direction:column;gap:7px;padding:20px;display:flex}.ll-land-format-icon{border-radius:var(--r-btn);background:var(--accent-soft);width:40px;height:40px;color:var(--accent);justify-content:center;align-items:center;margin-bottom:6px;display:inline-flex}.ll-land-format-icon svg{width:20px;height:20px}.ll-land-format strong{font-family:var(--font-serif);color:var(--ink);font-size:18px;font-weight:600}.ll-land-format p{color:var(--text-2);flex:1;margin:0;font-size:13.5px;line-height:1.5}.ll-land-format-meta{color:var(--text-3);font-variant-numeric:tabular-nums;letter-spacing:.02em;font-size:12px}.ll-land-options{grid-template-columns:repeat(2,1fr);gap:16px;margin-top:16px;display:grid}.ll-land-option{border:1px dashed var(--border-2);border-radius:var(--r-card);font-family:var(--font-sans);align-items:flex-start;gap:12px;padding:16px 18px;display:flex}.ll-land-option .ll-badge{flex:none;margin-top:2px}.ll-land-option strong{font-family:var(--font-serif);color:var(--ink);margin-bottom:3px;font-size:16px;font-weight:600;display:block}.ll-land-option p{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.ll-hero-steps--landing{border-top:none;padding-top:0}.ll-land-final{border-top:1px solid var(--border);text-align:center;flex-direction:column;align-items:center;gap:20px;padding:52px 0 72px;display:flex}.ll-land-final-title{font-family:var(--font-serif);letter-spacing:-.02em;color:var(--ink);margin:0;font-size:30px;font-weight:600;line-height:1.15}.ll-land-final-link{font-family:var(--font-sans);color:var(--text-2);font-size:13.5px;text-decoration:none}.ll-land-final-link:hover{color:var(--accent)}@media (max-width:900px){.ll-land-formats,.ll-land-options{grid-template-columns:1fr}}.ll-reader-back{font-family:var(--font-sans);color:var(--text-2);margin-bottom:22px;font-size:13px;font-weight:500;text-decoration:none;transition:color .16s;display:inline-block}.ll-reader-back:hover{color:var(--accent)}.ll-reader-back:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-reader-toc-box>summary{cursor:pointer;list-style:none}.ll-reader-toc-box>summary::-webkit-details-marker{display:none}.ll-reader-toc-summary{border:1px solid var(--border);border-radius:var(--r-btn);background:var(--surface);font-family:var(--font-sans);color:var(--ink);justify-content:space-between;align-items:center;gap:10px;padding:11px 14px;font-size:13px;font-weight:600;display:none}.ll-reader-toc-summary svg{width:15px;height:15px;color:var(--text-3);transition:transform .2s}.ll-reader-toc-box[open] .ll-reader-toc-summary svg{transform:rotate(180deg)}.ll-reader-toc-label-desktop{color:var(--text-3);font-family:var(--font-sans);letter-spacing:.14em;text-transform:uppercase;margin:0 0 12px;font-size:10px;font-weight:700}@media (max-width:880px){.ll-reader-toc-summary{display:flex}.ll-reader-toc-label-desktop{display:none}.ll-reader-toc-box .ll-reader-toc{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);margin-top:12px;padding:14px 14px 10px}}.ll-reader-slides{gap:12px;margin:22px 0;display:grid}.ll-reader-slides--multi{grid-template-columns:repeat(2,1fr)}.ll-reader-slides .ll-reader-slide{margin:0}.ll-reader-slide{transition:border-color .16s}.ll-reader-slide:hover{border-color:var(--accent)}@media (max-width:620px){.ll-reader-slides--multi{grid-template-columns:1fr}}.ll-reader-prose .ll-callout{border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:0 var(--r-card)var(--r-card)0;background:var(--surface);margin:18px 0;padding:0}.ll-reader-prose .ll-callout>summary{cursor:pointer;font-family:var(--font-sans);letter-spacing:.14em;text-transform:uppercase;color:var(--accent);justify-content:space-between;align-items:center;gap:10px;padding:11px 15px;font-size:11.5px;font-weight:700;list-style:none;display:flex}.ll-reader-prose .ll-callout>summary::-webkit-details-marker{display:none}.ll-reader-prose .ll-callout>summary svg{width:15px;height:15px;color:var(--text-3);flex:none;transition:transform .22s}.ll-reader-prose .ll-callout[open]>summary{border-bottom:1px solid var(--border)}.ll-reader-prose .ll-callout[open]>summary svg{transform:rotate(180deg)}.ll-callout-body{padding:4px 17px 8px;font-size:17px;font-style:italic;line-height:1.66}.ll-share .ll-share-icon,.ll-share .ll-share-done{display:inline-flex}.ll-share .ll-share-done,.ll-share--done .ll-share-icon{display:none}.ll-share--done .ll-share-done{color:var(--accent);display:inline-flex}.ll-share--done{background:var(--accent-soft)}}@layer utilities{.visible{visibility:visible}.sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.static{position:static}.hidden{display:none}.resize{resize:both}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}}:root{--bg:#f4f2eb;--bg-2:#efece3;--surface:#fbf9f3;--surface-2:#ece9df;--ink:#26241e;--text-2:#6b665a;--text-3:#9c968a;--border:#e3dfd2;--border-2:#d3cdbc;--accent:#2f5a4c;--accent-2:#3c7060;--accent-soft:#e5ece7;--rail:#d8d3c5;--mark:#f0d896;--mark-cur:#e6bd55;--shadow:0 1px 2px #2822140a,0 10px 30px #2822140d;--font-serif:"Source Serif 4",Georgia,serif;--font-sans:"Onest",system-ui,sans-serif;--r-card:13px;--r-slide:11px;--r-btn:10px;--r-pill:7px;--r-track:5px}[data-theme=dark]{--bg:#16151a;--bg-2:#1c1b20;--surface:#222127;--surface-2:#2a2931;--ink:#ece8e0;--text-2:#a6a39d;--text-3:#726f6a;--border:#2f2e36;--border-2:#3f3e48;--accent:#7fcab0;--accent-2:#97d8c1;--accent-soft:#1d2a2a;--rail:#2f2e36;--mark:#574d2c;--mark-cur:#9a8338;--shadow:0 1px 2px #00000057,0 14px 38px #0000006b}@media print{.ll-topbar,.ll-footer,.ll-reader-progress,.ll-reader-search,.ll-reader-sidebar,.ll-reader-player,.ll-reader-lightbox,.ll-reader-export,.ll-reader-text-button{display:none!important}body{background:#fff;display:block}.ll-main{max-width:none;padding:0}.ll-reader-layout{display:block}.ll-reader-article{width:100%}.ll-reader-timeline{border-left:none;padding-left:0}.ll-reader-sub:before{display:none}.ll-reader-section-head{margin-left:0}.ll-reader-prose{color:#000}}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false} \ No newline at end of file +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial}}}@layer theme{:root,:host{--font-sans:var(--font-sans);--font-serif:var(--font-serif);--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}:root{color-scheme:light}[data-theme=dark]{color-scheme:dark}body{background:var(--bg);color:var(--ink);font-family:var(--font-sans);-webkit-font-smoothing:antialiased;flex-direction:column;min-height:100vh;display:flex}::selection{background:var(--mark);color:var(--ink)}*{scrollbar-width:thin;scrollbar-color:var(--border-2)transparent}::-webkit-scrollbar{width:10px;height:10px}::-webkit-scrollbar-thumb{background:var(--border-2);background-clip:content-box;border:2px solid #0000;border-radius:5px}::-webkit-scrollbar-track{background:0 0}html{scroll-behavior:smooth}@media (prefers-reduced-motion:reduce){*,:before,:after{scroll-behavior:auto!important;transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}}@layer components{.ll-reader{font-family:var(--font-sans);color:var(--ink)}.ll-reader-progress{z-index:55;background:var(--rail);width:100%;height:3px;position:fixed;top:58px;left:0}.ll-reader-progress>div{background:var(--accent);width:0;height:100%;transition:width .12s linear}.ll-reader-export,.ll-reader-text-button{border:1px solid var(--border);border-radius:var(--r-btn);background:var(--surface);color:var(--text-2);font:600 13px var(--font-sans);cursor:pointer;padding:8px 12px;text-decoration:none}.ll-reader-export:hover,.ll-reader-text-button:hover{color:var(--ink);border-color:var(--border-2)}.ll-reader-search{z-index:70;border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);width:min(480px,100vw - 26px);box-shadow:var(--shadow);align-items:center;gap:8px;padding:9px 10px;display:flex;position:fixed;top:66px;right:22px}.ll-reader-search-field{flex:1}.ll-reader-search input{border:1px solid var(--border-2);border-radius:var(--r-btn);background:var(--surface);width:100%;color:var(--ink);font:14px var(--font-sans);outline:none;padding:10px 13px}.ll-reader-search input:focus{border-color:var(--accent)}.ll-reader-search-count{min-width:58px;color:var(--text-3);text-align:right;font-variant-numeric:tabular-nums;font-size:12px}.ll-reader-layout{align-items:flex-start;gap:54px;display:flex}.ll-reader-sidebar{flex:0 0 280px;max-height:calc(100vh - 100px);padding:4px 12px 24px 0;position:sticky;top:82px;overflow:auto}.ll-reader-source-card{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);color:var(--text-2);flex-direction:column;gap:8px;padding:16px;font-size:13px;display:flex}.ll-reader-source-card strong{color:var(--ink);font-size:14px}.ll-reader-owner{color:var(--accent);font-weight:600}.ll-reader-visibility{border:1px solid var(--border);border-radius:var(--r-pill);background:var(--surface-2);color:var(--text-2);align-items:center;padding:1px 8px;font-size:11px;font-weight:500;display:inline-flex}.ll-reader-visibility--unlisted{border-color:var(--border-2)}.ll-reader-visibility--public{background:var(--accent-soft);border-color:var(--accent-soft);color:var(--accent)}.ll-reader-reading{color:var(--text-3);margin:20px 0 25px;font-size:12px}.ll-reader-reading strong{float:right;color:var(--text-2);font-variant-numeric:tabular-nums}.ll-reader-reading div{clear:both;border-radius:var(--r-track);background:var(--rail);height:4px;margin-top:9px;overflow:hidden}.ll-reader-reading i{background:var(--accent);width:0;height:100%;display:block}.ll-reader-toc>p{color:var(--text-3);letter-spacing:.14em;text-transform:uppercase;margin:0 0 12px;font-size:10px;font-weight:700}.ll-reader-toc-section+.ll-reader-toc-section{margin-top:10px}.ll-reader-toc-section>div{color:var(--text-2);gap:9px;font-size:13px;display:flex}.ll-reader-toc-section>div span,.ll-reader-toc-link span{color:var(--text-3);font-variant-numeric:tabular-nums;flex:none}.ll-reader-toc-section ul{border-left:1px solid var(--border);margin:6px 0 0 9px;padding:0 0 0 12px;list-style:none}.ll-reader-toc-link{color:var(--text-2);border-left:2px solid #0000;gap:8px;padding:6px 0 6px 10px;font-size:13px;line-height:1.4;text-decoration:none;display:flex}.ll-reader-toc-link:hover,.ll-reader-toc-link.active{border-left-color:var(--accent);color:var(--accent)}.ll-reader-article{width:min(100%,720px);padding-bottom:60px}.ll-reader-doc-head{border-bottom:1px solid var(--border);padding:12px 0 46px}.ll-reader-doc-head p{color:var(--accent);letter-spacing:.14em;text-transform:uppercase;margin:0 0 10px;font-size:11px;font-weight:700}.ll-reader-doc-head h1{color:var(--ink);font:600 clamp(34px,5vw,52px)/1.08 var(--font-serif);letter-spacing:-.025em;margin:0}.ll-reader-doc-head div{color:var(--text-3);margin-top:17px;font-size:14px}.ll-reader-timeline{border-left:1px solid var(--rail);margin-top:45px;padding-left:32px;position:relative}.ll-reader-section+.ll-reader-section{margin-top:58px}.ll-reader-section-head{align-items:baseline;gap:15px;margin-left:-33px;display:flex}.ll-reader-section-head span{color:var(--accent);font-variant-numeric:tabular-nums;font-size:13px;font-weight:700}.ll-reader-section-head h2{font:600 27px/1.22 var(--font-serif);letter-spacing:-.015em;margin:0}.ll-reader-sub{margin-top:35px;scroll-margin-top:82px;position:relative}.ll-reader-sub:before{border:2px solid var(--bg);background:var(--accent);content:"";border-radius:50%;width:9px;height:9px;position:absolute;top:9px;left:-37px}.ll-reader-sub>header{align-items:baseline;gap:12px;display:flex}.ll-reader-sub>header span{color:var(--text-3);font-variant-numeric:tabular-nums;font-size:13px}.ll-reader-sub h3{color:var(--ink);font:600 22px/1.3 var(--font-serif);margin:0}.ll-reader-prose{color:var(--ink);font:18px/1.72 var(--font-serif)}.ll-reader-prose>:first-child{margin-top:15px}.ll-reader-prose a{color:var(--accent)}.ll-reader-prose blockquote,.ll-reader-prose details{border-left:3px solid var(--accent);border-radius:0 var(--r-card)var(--r-card)0;background:var(--accent-soft);margin:18px 0;padding:14px 17px}.ll-reader-player{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);margin-top:18px;padding:13px}.ll-reader-player>div{color:var(--text-3);font-variant-numeric:tabular-nums;justify-content:space-between;margin-bottom:9px;font-size:12px;display:flex}.ll-reader-media-kind{color:var(--accent);font-weight:700}.ll-reader-player audio,.ll-reader-player video{width:100%;max-height:330px;display:block}.ll-reader-slide{border:1px solid var(--border);border-radius:var(--r-slide);background:var(--surface);margin:22px 0;overflow:hidden}.ll-reader-slide img{cursor:zoom-in;width:100%;display:block}.ll-reader-slide figcaption{color:var(--text-3);padding:9px 13px;font-size:12px}.ll-reader-foot{border-top:1px solid var(--border);color:var(--text-3);margin-top:58px;padding-top:18px;font-size:12px}.ll-reader-lightbox[hidden]{display:none}.ll-reader-lightbox{z-index:90;background:var(--ink);place-items:center;padding:4vw;display:grid;position:fixed;inset:0}@supports (color:color-mix(in lab, red, red)){.ll-reader-lightbox{background:color-mix(in srgb,var(--ink)76%,transparent)}}.ll-reader-lightbox{cursor:zoom-out}.ll-reader-lightbox img{border-radius:var(--r-slide);max-width:100%;max-height:90vh;box-shadow:var(--shadow)}.ll-reader-lightbox-close{border:1px solid var(--bg);border-radius:var(--r-btn);min-width:40px;min-height:40px;color:var(--bg);cursor:pointer;font-size:28px;line-height:1;position:absolute;top:22px;right:22px}.ll-reader-lightbox-close:focus-visible{outline:2px solid var(--bg);outline-offset:3px}.ll-reader-prose mark{background:var(--mark);color:var(--ink);-webkit-box-decoration-break:clone;box-decoration-break:clone;border-radius:3px;margin:-.05em;padding:.05em .15em}.ll-reader-prose mark.ll-reader-mark-current{background:var(--mark-cur);box-shadow:0 0 0 2px var(--mark-cur)}@media (max-width:880px){.ll-reader-layout{display:block}.ll-reader-sidebar{width:100%;max-height:none;margin-bottom:34px;padding:0;position:static}.ll-reader-article{width:100%}}@media (max-width:620px){.ll-reader-search{right:13px}.ll-reader-search-count{display:none}.ll-reader-layout{gap:0}.ll-reader-timeline{padding-left:26px}.ll-reader-sub:before{left:-31px}.ll-reader-doc-head h1{font-size:35px}}.ll-topbar{z-index:50;background:var(--bg-2);height:58px;position:sticky;top:0}@supports (color:color-mix(in lab, red, red)){.ll-topbar{background:color-mix(in srgb,var(--bg-2)86%,transparent)}}.ll-topbar{-webkit-backdrop-filter:saturate(1.05)blur(12px);backdrop-filter:saturate(1.05)blur(12px);border-bottom:1px solid var(--border)}.ll-topbar-inner{max-width:1240px;height:58px;font-family:var(--font-sans);align-items:center;gap:14px;margin:0 auto;padding:0 22px;display:flex}.ll-brand{flex:1;align-items:center;gap:11px;min-width:0;display:flex}.ll-brand-mark{background:var(--accent);width:24px;height:24px;color:var(--bg);border-radius:6px;flex:none;justify-content:center;align-items:center;display:flex}.ll-brand-mark svg{width:15px;height:15px}.ll-brand-t{color:var(--ink);white-space:nowrap;letter-spacing:-.02em;font-size:15px;font-weight:600}.ll-top-actions{flex:none;align-items:center;gap:8px;display:flex}.ll-icon-btn{width:37px;height:37px;color:var(--text-2);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:10px;justify-content:center;align-items:center;transition:all .16s;display:inline-flex}.ll-icon-btn:hover{background:var(--surface-2);color:var(--ink)}.ll-icon-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-icon-btn svg{width:18px;height:18px;display:block}.ll-icon-moon,.ll-icon-sun{display:block}[data-theme=light] .ll-icon-sun,:root:not([data-theme=dark]) .ll-icon-sun,[data-theme=dark] .ll-icon-moon{display:none}[data-theme=dark] .ll-icon-sun{display:block}.ll-main{max-width:1240px;margin:0 auto;padding:34px 22px 120px}.ll-demo-content{max-width:768px;font-family:var(--font-serif);color:var(--ink);margin:0 auto}.ll-demo-content h1{letter-spacing:-.02em;margin-bottom:16px;font-size:43px;font-weight:600;line-height:1.12}.ll-demo-content p{color:var(--text-2);font-size:19px;line-height:1.78}.ll-lectures-section{width:100%}.ll-lec-grid{grid-template-columns:repeat(auto-fill,minmax(252px,1fr));gap:16px;display:grid}.ll-lec-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);flex-direction:column;gap:10px;padding:16px;transition:border-color .16s,box-shadow .16s,transform .16s;display:flex}.ll-lec-card:hover{border-color:var(--accent);box-shadow:var(--shadow);transform:translateY(-1px)}.ll-hub-card{color:inherit;text-decoration:none}.ll-hub-card:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-lec-card-top{justify-content:space-between;align-items:center;gap:8px;display:flex}.ll-lec-card-actions{align-items:center;gap:4px;display:flex}.ll-lec-card-body{flex-direction:column;flex:1;gap:6px;display:flex}.ll-lec-card-footer{justify-content:space-between;align-items:center;gap:8px;margin-top:auto;display:flex}.ll-badge{border-radius:var(--r-pill);font-family:var(--font-sans);background:var(--accent-soft);color:var(--accent);align-items:center;padding:2px 8px;font-size:12px;font-weight:500;display:inline-flex}.ll-badge--muted{background:var(--surface-2);color:var(--text-2)}.ll-status{font-family:var(--font-sans);font-size:12.5px;font-weight:500}.ll-status--processing{color:var(--text-2);animation:1.8s ease-in-out infinite ll-pulse}@keyframes ll-pulse{0%,to{opacity:1}50%{opacity:.5}}.ll-status--ready{color:var(--accent);background:var(--accent-soft);border-radius:var(--r-pill);padding:2px 6px;display:inline-block}.ll-status--failed{color:var(--text-3)}.ll-lec-bar{border-radius:var(--r-track);background:var(--surface-2);border:1px solid var(--border);height:4px;margin-top:6px;overflow:hidden}.ll-lec-bar>i{background:var(--accent);height:100%;transition:width .3s;display:block}.ll-lec-error{font-family:var(--font-sans);color:var(--text-3);font-size:12px;line-height:1.4}.ll-lec-title{font-family:var(--font-serif);color:var(--ink);-webkit-line-clamp:2;resize:none;background:0 0;border:none;outline:none;-webkit-box-orient:vertical;width:100%;padding:0;font-size:16.5px;font-weight:600;line-height:1.35;display:-webkit-box;overflow:hidden}.ll-lec-title:focus{outline:1px solid var(--border-2);-webkit-line-clamp:unset;border-radius:3px}.ll-lec-title-form{align-items:flex-start;gap:4px;display:flex}.ll-lec-rename-btn{border:1px solid var(--border);background:var(--surface-2);width:28px;height:28px;color:var(--text-2);cursor:pointer;opacity:0;border-radius:6px;flex:none;justify-content:center;align-items:center;transition:opacity .12s;display:inline-flex}.ll-lec-title-form:focus-within .ll-lec-rename-btn{opacity:1}.ll-lec-rename-btn svg{width:14px;height:14px}.ll-lec-meta{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;font-size:12.5px}.ll-hub-author{min-width:0;font-family:var(--font-sans);color:var(--text-2);align-items:center;gap:7px;font-size:12.5px;display:inline-flex}.ll-hub-avatar{border:1px solid var(--border);object-fit:cover;border-radius:50%;flex:none;width:22px;height:22px}.ll-toggle{border-radius:var(--r-pill);border:1px solid var(--border);background:var(--surface-2);color:var(--text-2);font-family:var(--font-sans);cursor:pointer;align-items:center;min-height:26px;padding:3px 10px;font-size:12px;font-weight:500;transition:all .16s;display:inline-flex}.ll-toggle:hover:not(:disabled){background:var(--surface);border-color:var(--accent);color:var(--accent)}.ll-toggle:disabled:not(.ll-toggle--active){opacity:.5;cursor:not-allowed}.ll-toggle--active:disabled{cursor:default}.ll-toggle-group{border:1px solid var(--border);border-radius:var(--r-pill);background:var(--surface-2);align-items:center;gap:2px;padding:2px;display:inline-flex}.ll-toggle-group .ll-toggle{white-space:nowrap;background:0 0;border-color:#0000;min-height:22px;padding:2px 9px;font-size:11.5px;line-height:1.2}.ll-toggle--active[aria-pressed=true]{background:var(--surface);border-color:var(--border);color:var(--text-2)}.ll-toggle--unlisted[aria-pressed=true]{border-color:var(--border-2)}.ll-toggle--public[aria-pressed=true]{background:var(--accent-soft);border-color:var(--accent-soft);color:var(--accent)}.ll-empty{text-align:center;flex-direction:column;justify-content:center;align-items:center;gap:16px;padding:80px 24px;display:flex}.ll-empty-icon{width:48px;height:48px;color:var(--text-3)}.ll-empty-title{font-family:var(--font-serif);color:var(--ink);margin:0;font-size:22px;font-weight:600}.ll-empty-text{font-family:var(--font-sans);color:var(--text-2);max-width:360px;margin:0;font-size:15px;line-height:1.6}.ll-btn{border-radius:var(--r-btn);font-family:var(--font-sans);cursor:pointer;border:1px solid #0000;justify-content:center;align-items:center;min-height:40px;padding:9px 20px;font-size:14px;font-weight:500;text-decoration:none;transition:all .16s;display:inline-flex}.ll-btn--accent{background:var(--accent);color:var(--bg)}.ll-btn--accent:hover{background:var(--accent-2)}.ll-upload{width:100%;max-width:660px;font-family:var(--font-sans);color:var(--ink);margin:0 auto}.ll-upload-hidden{display:none!important}.ll-upload-head{margin-bottom:22px}.ll-upload-kicker{letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin-bottom:16px;font-size:11.5px;font-weight:600}.ll-upload-title{font-family:var(--font-serif);letter-spacing:0;color:var(--ink);margin:0 0 16px;font-size:43px;font-weight:600;line-height:1.12}.ll-upload-dek{font-family:var(--font-serif);color:var(--text-2);max-width:54ch;margin:0;font-size:20px;font-style:italic;line-height:1.55}.ll-upload-seg{background:var(--surface-2);border:1px solid var(--border);border-radius:var(--r-card);gap:3px;margin-bottom:22px;padding:3px;display:inline-flex}.ll-upload-seg-btn{font-family:var(--font-sans);color:var(--text-2);border-radius:var(--r-pill);cursor:pointer;background:0 0;border:none;align-items:center;gap:7px;padding:8px 18px;font-size:13px;font-weight:500;transition:all .14s;display:inline-flex}.ll-upload-seg-btn:hover,.ll-upload-seg-btn:focus-visible{color:var(--ink)}.ll-upload-seg-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-seg-btn svg{width:15px;height:15px}.ll-upload-seg-btn--active{background:var(--surface);color:var(--ink);box-shadow:var(--shadow)}.ll-upload-drop{border:1.5px dashed var(--border-2);border-radius:var(--r-card);background:var(--surface);text-align:center;padding:52px 40px;transition:border-color .18s,background .18s}.ll-upload-drop--over{border-color:var(--accent);background:var(--accent-soft)}.ll-upload-drop--error{border-color:var(--border-2)}.ll-upload-drop-icon{background:var(--accent-soft);width:58px;height:58px;color:var(--accent);border-radius:50%;justify-content:center;align-items:center;margin-bottom:18px;transition:transform .18s;display:inline-flex}.ll-upload-drop--over .ll-upload-drop-icon{transform:translateY(-3px)}.ll-upload-drop-icon svg{width:26px;height:26px}.ll-upload-drop-title{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;margin:0 0 4px;font-size:21px;font-weight:600}.ll-upload-drop-sub{color:var(--text-2);margin:0 0 18px;font-size:13.5px}.ll-upload-pick{border:1px solid var(--border-2);background:var(--bg);border-radius:var(--r-btn);min-height:38px;color:var(--ink);cursor:pointer;font-family:var(--font-sans);align-items:center;gap:8px;padding:0 18px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex}.ll-upload-pick:hover,.ll-upload-pick:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-upload-pick:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-pick svg{width:15px;height:15px}.ll-upload-formats{color:var(--text-3);font-variant-numeric:tabular-nums;margin:18px 0 0;font-size:12px}.ll-upload-file{text-align:left;align-items:center;gap:14px;display:flex}.ll-upload-file-icon{border-radius:var(--r-btn);background:var(--accent-soft);width:46px;height:46px;color:var(--accent);flex:none;justify-content:center;align-items:center;display:inline-flex}.ll-upload-file-icon svg{width:22px;height:22px}.ll-upload-file-meta{flex:1;min-width:0}.ll-upload-file-name{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;white-space:nowrap;text-overflow:ellipsis;font-size:18px;font-weight:600;overflow:hidden}.ll-upload-file-sub{color:var(--text-3);font-variant-numeric:tabular-nums;margin-top:3px;font-size:12.5px}.ll-upload-file-bar{border-radius:var(--r-track);background:var(--surface-2);border:1px solid var(--border);height:4px;margin-top:13px;overflow:hidden}.ll-upload-file-bar>i{background:var(--accent);width:100%;height:100%;display:block}.ll-upload-file-remove{border-radius:var(--r-btn);border:1px solid var(--border-2);width:40px;height:40px;color:var(--text-2);cursor:pointer;background:0 0;flex:none;justify-content:center;align-items:center;transition:all .14s;display:inline-flex}.ll-upload-file-remove:hover,.ll-upload-file-remove:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-upload-file-remove:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-file-remove svg{width:15px;height:15px}.ll-upload-errnote{color:var(--text-2);background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-btn);text-align:left;margin-top:16px;padding:10px 13px;font-size:13px;line-height:1.45;display:none}.ll-upload-errnote--show{display:block}.ll-upload-url-field{background:var(--surface);border:1px solid var(--border-2);border-radius:var(--r-card);align-items:center;gap:11px;min-height:54px;padding:0 15px;display:flex}.ll-upload-url-field svg{width:18px;height:18px;color:var(--text-3);flex:none}.ll-upload-url-field input{min-width:0;color:var(--ink);font-family:var(--font-sans);background:0 0;border:none;outline:none;flex:1;font-size:15px}.ll-upload-url-field input::placeholder{color:var(--text-3)}.ll-upload-url-hint{color:var(--text-3);margin:12px 2px 0;font-size:12.5px}.ll-upload-options{border-top:1px solid var(--border);gap:18px;margin-top:26px;padding-top:22px;display:grid}.ll-upload-check,.ll-upload-switch-row{cursor:pointer;align-items:flex-start;gap:14px;display:flex}.ll-upload-check input{opacity:0;pointer-events:none;position:absolute}.ll-upload-check-box{border:1px solid var(--border-2);border-radius:var(--r-pill);background:var(--surface-2);flex:none;width:23px;height:23px;margin-top:2px}.ll-upload-check input:checked+.ll-upload-check-box{background:var(--accent);border-color:var(--accent);box-shadow:inset 0 0 0 5px var(--surface)}.ll-upload-check input:focus-visible+.ll-upload-check-box{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-slides-option{gap:12px;display:grid}.ll-upload-slides{border:1px dashed var(--border-2);border-radius:var(--r-card);background:var(--surface-2);margin-left:37px;padding:14px 16px}.ll-upload-slides-pick,.ll-upload-slides-file button{border:1px solid var(--border-2);border-radius:var(--r-btn);background:var(--surface);color:var(--ink);font:600 13px var(--font-sans);cursor:pointer}.ll-upload-slides-pick{min-height:38px;padding:0 16px}.ll-upload-slides-file{color:var(--ink);justify-content:space-between;align-items:center;gap:12px;font-size:13px}.ll-upload-slides-file:not(.ll-upload-hidden){display:flex}.ll-upload-slides-file span{overflow-wrap:anywhere;min-width:0}.ll-upload-slides-file button{color:var(--text-2);flex:none;padding:7px 11px}.ll-upload-slides>p{color:var(--text-3);margin:8px 0 0;font-size:12px}.ll-upload-opt-title,.ll-upload-opt-text{display:block}.ll-upload-opt-title{font-family:var(--font-serif);color:var(--ink);letter-spacing:0;font-size:17px;font-weight:600}.ll-upload-opt-text{color:var(--text-2);max-width:46ch;margin-top:3px;font-size:13px;line-height:1.5}.ll-upload-switch-row{justify-content:space-between}.ll-upload-switch-input{opacity:0;pointer-events:none;position:absolute}.ll-upload-switch{border-radius:var(--r-pill);background:var(--surface-2);border:1px solid var(--border-2);flex:none;width:44px;height:25px;margin-top:2px;transition:all .18s;position:relative}.ll-upload-switch:after{content:"";background:var(--bg);width:19px;height:19px;box-shadow:var(--shadow);border-radius:50%;transition:all .18s;position:absolute;top:2px;left:2px}.ll-upload-switch-input:checked+.ll-upload-switch{background:var(--accent);border-color:var(--accent)}.ll-upload-switch-input:checked+.ll-upload-switch:after{background:var(--surface);left:21px}.ll-upload-switch-input:disabled+.ll-upload-switch{opacity:.5;cursor:not-allowed}.ll-upload-switch-input:focus-visible+.ll-upload-switch{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-cta-row{align-items:center;gap:18px;margin-top:34px;display:flex}.ll-upload-cta{border-radius:var(--r-btn);background:var(--accent);min-height:50px;color:var(--bg);cursor:pointer;font-family:var(--font-sans);border:none;justify-content:center;align-items:center;gap:10px;padding:0 30px;font-size:14.5px;font-weight:600;transition:all .16s;display:inline-flex}.ll-upload-cta:hover:not(:disabled),.ll-upload-cta:focus-visible:not(:disabled){background:var(--accent-2)}.ll-upload-cta:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-upload-cta:disabled{opacity:.42;cursor:not-allowed;background:var(--accent)}.ll-upload-cta svg{width:17px;height:17px}.ll-upload-cta-note{color:var(--text-3);font-size:12.5px;line-height:1.45}@media (max-width:620px){.ll-upload-title{font-size:30px}.ll-upload-dek{font-size:18px}.ll-upload-drop{padding:40px 22px}.ll-upload-cta-row{flex-direction:column;align-items:stretch}.ll-upload-cta{width:100%}}.ll-settings{width:100%;max-width:660px;font-family:var(--font-sans);color:var(--ink);margin:0 auto}.ll-settings-head{margin-bottom:22px}.ll-settings-kicker{letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin-bottom:16px;font-size:11.5px;font-weight:600}.ll-settings-title{font-family:var(--font-serif);letter-spacing:0;color:var(--ink);margin:0;font-size:43px;font-weight:600;line-height:1.12}.ll-settings-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);padding:24px 26px}.ll-settings-card-title{font-family:var(--font-serif);letter-spacing:-.015em;color:var(--ink);margin:0 0 6px;font-size:28px;font-weight:600;line-height:1.18}.ll-settings-card-sub{color:var(--text-2);margin:0 0 20px;font-size:14px;line-height:1.5}.ll-settings-warning{background:var(--surface-2);border-left:3px solid var(--border-2);border-radius:0 var(--r-btn)var(--r-btn)0;align-items:flex-start;gap:12px;margin-bottom:18px;padding:14px 16px;display:flex}.ll-settings-warning-icon{width:18px;height:18px;color:var(--text-2);flex:none;margin-top:1px}.ll-settings-warning-icon svg{width:18px;height:18px;display:block}.ll-settings-warning-kicker{letter-spacing:.14em;text-transform:uppercase;color:var(--text-2);margin-bottom:4px;font-size:11px;font-weight:700}.ll-settings-warning-text{color:var(--text-2);margin:0;font-size:13.5px;line-height:1.55}.ll-settings-status{border-bottom:1px solid var(--border);align-items:flex-start;gap:12px;margin-bottom:20px;padding:14px 0;display:flex}.ll-settings-status-dot{border:1.5px solid var(--border-2);background:0 0;border-radius:50%;flex:none;width:12px;height:12px;margin-top:4px}.ll-settings-status-dot--filled{border-color:var(--accent);background:var(--accent)}.ll-settings-status-body{flex:1;min-width:0}.ll-settings-status-title{font-family:var(--font-serif);color:var(--ink);font-size:17px;font-weight:600}.ll-settings-status-meta{color:var(--text-3);font-variant-numeric:tabular-nums;margin-top:3px;font-size:12.5px}.ll-settings-delete{border:1px solid var(--border-2);border-radius:var(--r-btn);min-height:37px;color:var(--text-2);font-family:var(--font-sans);cursor:pointer;background:0 0;flex:none;align-items:center;gap:7px;padding:0 14px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex}.ll-settings-delete:hover,.ll-settings-delete:focus-visible{border-color:var(--accent);color:var(--accent)}.ll-settings-delete:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-delete svg{width:15px;height:15px}.ll-settings-status--error{border-bottom-color:var(--border)}.ll-settings-status-icon{width:18px;height:18px;color:var(--text-2);flex:none;margin-top:2px}.ll-settings-status-icon svg{width:18px;height:18px;display:block}.ll-settings-status--error .ll-settings-status-title{font-family:var(--font-sans);color:var(--ink);font-size:14px;font-weight:500}.ll-settings-form{padding-top:4px}.ll-settings-file-label{color:var(--ink);margin-bottom:10px;font-size:13px;font-weight:600;display:block}.ll-settings-file-row{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.ll-settings-file-pick{border:1px solid var(--border-2);background:var(--bg);border-radius:var(--r-btn);min-height:38px;color:var(--ink);cursor:pointer;font-family:var(--font-sans);align-items:center;gap:8px;padding:0 18px;font-size:13px;font-weight:500;transition:all .16s;display:inline-flex;position:relative}.ll-settings-file-pick:hover{border-color:var(--accent);color:var(--accent)}.ll-settings-file-pick svg{width:15px;height:15px}.ll-settings-file-input{opacity:0;cursor:pointer;width:100%;height:100%;position:absolute;inset:0}.ll-settings-file-input:focus-visible+span{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-file-name{color:var(--text-3);text-overflow:ellipsis;white-space:nowrap;min-width:0;font-size:13px;overflow:hidden}.ll-settings-file-hint{color:var(--text-2);max-width:58ch;margin:14px 0 0;font-size:12.5px;line-height:1.55}.ll-settings-file-formats{color:var(--text-3);font-variant-numeric:tabular-nums;margin:8px 0 0;font-size:12px}.ll-settings-cta-row{align-items:center;gap:14px;margin-top:20px;display:flex}.ll-settings-cta{border-radius:var(--r-btn);background:var(--accent);min-height:44px;color:var(--bg);cursor:pointer;font-family:var(--font-sans);border:none;padding:0 24px;font-size:13.5px;font-weight:600;transition:all .16s}.ll-settings-cta:hover:not(:disabled),.ll-settings-cta:focus-visible:not(:disabled){background:var(--accent-2)}.ll-settings-cta:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-settings-cta:disabled{opacity:.55;cursor:not-allowed}.ll-settings-indicator{color:var(--text-2);opacity:0;align-items:center;gap:7px;font-size:12.5px;display:inline-flex}.ll-settings-indicator.htmx-request{opacity:1}.ll-settings-spinner{width:14px;height:14px;animation:.8s linear infinite ll-spin}@keyframes ll-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (max-width:620px){.ll-settings-title{font-size:30px}.ll-settings-card{padding:20px}.ll-settings-status{flex-wrap:wrap}.ll-settings-delete{justify-content:center;width:100%}}.ll-main{flex:1 0 auto;width:100%}.ll-brand{color:inherit;border-radius:var(--r-btn);flex:none;margin-left:-2px;padding:5px 8px 5px 2px;text-decoration:none}.ll-brand:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-brand:hover .ll-brand-t{color:var(--accent)}.ll-brand-t{transition:color .16s}.ll-nav{min-width:0;font-family:var(--font-sans);scrollbar-width:none;flex:1;align-items:center;gap:2px;margin-left:8px;display:flex;overflow-x:auto}.ll-nav::-webkit-scrollbar{display:none}.ll-nav-link{border-radius:var(--r-btn);color:var(--text-2);white-space:nowrap;padding:8px 11px;font-size:13.5px;font-weight:500;text-decoration:none;transition:color .16s,background .16s;position:relative}.ll-nav-link:hover{color:var(--ink);background:var(--surface-2)}.ll-nav-link:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-nav-link--active{color:var(--ink)}.ll-nav-link--active:after{content:"";background:var(--accent);border-radius:1px;height:2px;position:absolute;bottom:3px;left:11px;right:11px}.ll-btn--login{border:1px solid var(--border-2);background:var(--surface);min-height:34px;color:var(--ink);padding:5px 15px;font-size:13.5px}.ll-btn--login:hover{border-color:var(--accent);color:var(--accent)}.ll-logout-form{display:contents}.ll-btn{gap:8px}.ll-btn svg{width:16px;height:16px}.ll-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-btn--lg{min-height:50px;padding:0 28px;font-size:14.5px;font-weight:600}.ll-footer{border-top:1px solid var(--border);font-family:var(--font-sans)}.ll-footer-inner{flex-wrap:wrap;align-items:center;gap:18px;max-width:1240px;margin:0 auto;padding:24px 22px 32px;display:flex}.ll-footer-brand{color:var(--ink);align-items:center;gap:9px;font-size:13.5px;font-weight:600;display:inline-flex}.ll-footer-brand .ll-brand-mark{border-radius:5px;width:20px;height:20px}.ll-footer-brand .ll-brand-mark svg{width:12px;height:12px}.ll-footer-tag{min-width:240px;color:var(--text-3);flex:1;margin:0;font-size:12.5px}.ll-footer-link{color:var(--text-2);border-bottom:1px solid #0000;font-size:12.5px;text-decoration:none;transition:all .16s}.ll-footer-link:hover{color:var(--accent);border-bottom-color:var(--accent)}.ll-footer-links{flex-wrap:wrap;align-items:center;gap:16px;display:flex}.ll-footer-link--ext{align-items:center;gap:6px;display:inline-flex}.ll-footer-link--ext svg{flex-shrink:0;width:14px;height:14px}.ll-footer-link--icon{border-bottom:none;padding:3px}.ll-footer-link--icon:hover{border-bottom-color:#0000}.ll-footer-link--icon svg{width:18px;height:18px}.ll-hero{text-align:center;margin-bottom:84px;padding-top:44px}.ll-hero-kicker{font-family:var(--font-sans);letter-spacing:.18em;text-transform:uppercase;color:var(--accent);margin:0 0 18px;font-size:11.5px;font-weight:600}.ll-hero-title{font-family:var(--font-serif);letter-spacing:-.025em;color:var(--ink);max-width:21ch;margin:0 auto 20px;font-size:clamp(36px,5.2vw,56px);font-weight:600;line-height:1.08}.ll-hero-dek{font-family:var(--font-serif);color:var(--text-2);max-width:52ch;margin:0 auto 30px;font-size:20px;font-style:italic;line-height:1.6}.ll-hero-cta{flex-wrap:wrap;justify-content:center;align-items:center;gap:16px;margin-bottom:64px;display:flex}.ll-hero-note{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;font-size:12.5px}.ll-hero-steps{border-top:1px solid var(--border);text-align:left;grid-template-columns:repeat(3,1fr);gap:28px;margin:0;padding:30px 0 0;list-style:none;display:grid}.ll-hero-step-num{font-family:var(--font-sans);color:var(--accent);font-variant-numeric:tabular-nums;margin-bottom:8px;font-size:13px;font-weight:700;display:block}.ll-hero-step-title{font-family:var(--font-serif);color:var(--ink);margin-bottom:6px;font-size:18px;font-weight:600;display:block}.ll-hero-step-text{font-family:var(--font-sans);color:var(--text-2);margin:0;font-size:13.5px;line-height:1.55}.ll-section-head{align-items:baseline;gap:12px;margin-bottom:18px;display:flex}.ll-section-title{font-family:var(--font-serif);letter-spacing:-.01em;color:var(--ink);margin:0;font-size:22px;font-weight:600;line-height:1.2}.ll-section-count{font-family:var(--font-sans);color:var(--accent);background:var(--accent-soft);border-radius:var(--r-pill);font-variant-numeric:tabular-nums;padding:2px 9px;font-size:12.5px;font-weight:600}.ll-page-head{flex-wrap:wrap;justify-content:space-between;align-items:flex-end;gap:18px;margin-bottom:26px;display:flex}.ll-page-kicker{font-family:var(--font-sans);letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin:0 0 10px;font-size:11.5px;font-weight:600}.ll-page-title{font-family:var(--font-serif);letter-spacing:-.02em;color:var(--ink);margin:0;font-size:36px;font-weight:600;line-height:1.1}.ll-page-sub{font-family:var(--font-sans);color:var(--text-3);font-variant-numeric:tabular-nums;margin:8px 0 0;font-size:13px}.ll-page-head-cta{flex:none}.ll-hub-card-arrow{width:26px;height:26px;color:var(--accent);opacity:0;border-radius:50%;justify-content:center;align-items:center;transition:opacity .18s,transform .18s;display:inline-flex;transform:translate(-4px)}.ll-hub-card-arrow svg{width:16px;height:16px}.ll-hub-card:hover .ll-hub-card-arrow,.ll-hub-card:focus-visible .ll-hub-card-arrow{opacity:1;transform:none}.ll-hub-avatar--ph{background:var(--accent-soft);color:var(--accent);justify-content:center;align-items:center;font-size:11px;font-weight:600;line-height:1;display:inline-flex}.ll-hub-author-name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.ll-empty-icon{background:var(--surface);border:1px solid var(--border);width:74px;height:74px;color:var(--text-3);border-radius:50%;justify-content:center;align-items:center;display:flex}.ll-empty-icon svg{width:30px;height:30px}.ll-empty--404{padding-top:70px}.ll-404-code{font-family:var(--font-serif);letter-spacing:-.04em;color:var(--border-2);font-variant-numeric:tabular-nums;font-size:96px;font-weight:600;line-height:1}@media (max-width:640px){.ll-topbar-inner{gap:8px;padding:0 13px}.ll-brand-t{display:none}.ll-nav{margin-left:0}.ll-nav-link{padding:8px 9px;font-size:13px}.ll-main,.ll-footer-inner{padding-left:13px;padding-right:13px}.ll-hero{text-align:left;margin-bottom:60px;padding-top:26px}.ll-hero-title,.ll-hero-dek{margin-left:0;margin-right:0}.ll-hero-cta{justify-content:flex-start;margin-bottom:44px}.ll-hero-steps{grid-template-columns:1fr;gap:22px}.ll-page-title{font-size:30px}.ll-page-head-cta{justify-content:center;width:100%}}.ll-lec-title{text-overflow:ellipsis}.ll-status-row{justify-content:space-between;align-items:center;gap:10px;display:flex}.ll-lec-read{font-family:var(--font-sans);color:var(--accent);border-radius:var(--r-pill);align-items:center;gap:5px;font-size:13px;font-weight:600;text-decoration:none;transition:gap .16s,color .16s;display:inline-flex}.ll-lec-read svg{width:14px;height:14px;transition:transform .16s}.ll-lec-read:hover{color:var(--accent-2)}.ll-lec-read:hover svg{transform:translate(2px)}.ll-lec-read:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-landing{max-width:980px;margin:0 auto}.ll-btn--ghost{border:1px solid var(--border-2);background:var(--surface);color:var(--ink)}.ll-btn--ghost:hover{border-color:var(--accent);color:var(--accent)}.ll-land-section{border-top:1px solid var(--border);padding:46px 0 54px}.ll-landing .ll-hero{margin-bottom:0;padding-bottom:64px}.ll-landing .ll-hero-cta{margin-bottom:0}.ll-land-title{font-family:var(--font-serif);letter-spacing:-.015em;color:var(--ink);margin:0 0 26px;font-size:26px;font-weight:600;line-height:1.2}.ll-land-formats{grid-template-columns:repeat(3,1fr);gap:16px;display:grid}.ll-land-format{background:var(--surface);border:1px solid var(--border);border-radius:var(--r-card);font-family:var(--font-sans);flex-direction:column;gap:7px;padding:20px;display:flex}.ll-land-format-icon{border-radius:var(--r-btn);background:var(--accent-soft);width:40px;height:40px;color:var(--accent);justify-content:center;align-items:center;margin-bottom:6px;display:inline-flex}.ll-land-format-icon svg{width:20px;height:20px}.ll-land-format strong{font-family:var(--font-serif);color:var(--ink);font-size:18px;font-weight:600}.ll-land-format p{color:var(--text-2);flex:1;margin:0;font-size:13.5px;line-height:1.5}.ll-land-format-meta{color:var(--text-3);font-variant-numeric:tabular-nums;letter-spacing:.02em;font-size:12px}.ll-land-options{grid-template-columns:repeat(2,1fr);gap:16px;margin-top:16px;display:grid}.ll-land-option{border:1px dashed var(--border-2);border-radius:var(--r-card);font-family:var(--font-sans);align-items:flex-start;gap:12px;padding:16px 18px;display:flex}.ll-land-option .ll-badge{flex:none;margin-top:2px}.ll-land-option strong{font-family:var(--font-serif);color:var(--ink);margin-bottom:3px;font-size:16px;font-weight:600;display:block}.ll-land-option p{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.ll-hero-steps--landing{border-top:none;padding-top:0}.ll-land-final{border-top:1px solid var(--border);text-align:center;flex-direction:column;align-items:center;gap:20px;padding:52px 0 72px;display:flex}.ll-land-final-title{font-family:var(--font-serif);letter-spacing:-.02em;color:var(--ink);margin:0;font-size:30px;font-weight:600;line-height:1.15}.ll-land-final-link{font-family:var(--font-sans);color:var(--text-2);font-size:13.5px;text-decoration:none}.ll-land-final-link:hover{color:var(--accent)}@media (max-width:900px){.ll-land-formats,.ll-land-options{grid-template-columns:1fr}}.ll-reader-back{font-family:var(--font-sans);color:var(--text-2);margin-bottom:22px;font-size:13px;font-weight:500;text-decoration:none;transition:color .16s;display:inline-block}.ll-reader-back:hover{color:var(--accent)}.ll-reader-back:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.ll-reader-toc-box>summary{cursor:pointer;list-style:none}.ll-reader-toc-box>summary::-webkit-details-marker{display:none}.ll-reader-toc-summary{border:1px solid var(--border);border-radius:var(--r-btn);background:var(--surface);font-family:var(--font-sans);color:var(--ink);justify-content:space-between;align-items:center;gap:10px;padding:11px 14px;font-size:13px;font-weight:600;display:none}.ll-reader-toc-summary svg{width:15px;height:15px;color:var(--text-3);transition:transform .2s}.ll-reader-toc-box[open] .ll-reader-toc-summary svg{transform:rotate(180deg)}.ll-reader-toc-label-desktop{color:var(--text-3);font-family:var(--font-sans);letter-spacing:.14em;text-transform:uppercase;margin:0 0 12px;font-size:10px;font-weight:700}@media (max-width:880px){.ll-reader-toc-summary{display:flex}.ll-reader-toc-label-desktop{display:none}.ll-reader-toc-box .ll-reader-toc{border:1px solid var(--border);border-radius:var(--r-card);background:var(--surface);margin-top:12px;padding:14px 14px 10px}}.ll-reader-slides{gap:12px;margin:22px 0;display:grid}.ll-reader-slides--multi{grid-template-columns:repeat(2,1fr)}.ll-reader-slides .ll-reader-slide{margin:0}.ll-reader-slide{transition:border-color .16s}.ll-reader-slide:hover{border-color:var(--accent)}@media (max-width:620px){.ll-reader-slides--multi{grid-template-columns:1fr}}.ll-reader-prose .ll-callout{border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:0 var(--r-card)var(--r-card)0;background:var(--surface);margin:18px 0;padding:0}.ll-reader-prose .ll-callout>summary{cursor:pointer;font-family:var(--font-sans);letter-spacing:.14em;text-transform:uppercase;color:var(--accent);justify-content:space-between;align-items:center;gap:10px;padding:11px 15px;font-size:11.5px;font-weight:700;list-style:none;display:flex}.ll-reader-prose .ll-callout>summary::-webkit-details-marker{display:none}.ll-reader-prose .ll-callout>summary svg{width:15px;height:15px;color:var(--text-3);flex:none;transition:transform .22s}.ll-reader-prose .ll-callout[open]>summary{border-bottom:1px solid var(--border)}.ll-reader-prose .ll-callout[open]>summary svg{transform:rotate(180deg)}.ll-callout-body{padding:4px 17px 8px;font-size:17px;font-style:italic;line-height:1.66}.ll-share .ll-share-icon,.ll-share .ll-share-done{display:inline-flex}.ll-share .ll-share-done,.ll-share--done .ll-share-icon{display:none}.ll-share--done .ll-share-done{color:var(--accent);display:inline-flex}.ll-share--done{background:var(--accent-soft)}}@layer utilities{.visible{visibility:visible}.sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.static{position:static}.hidden{display:none}.resize{resize:both}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}}:root{--bg:#f4f2eb;--bg-2:#efece3;--surface:#fbf9f3;--surface-2:#ece9df;--ink:#26241e;--text-2:#6b665a;--text-3:#9c968a;--border:#e3dfd2;--border-2:#d3cdbc;--accent:#2f5a4c;--accent-2:#3c7060;--accent-soft:#e5ece7;--rail:#d8d3c5;--mark:#f0d896;--mark-cur:#e6bd55;--shadow:0 1px 2px #2822140a,0 10px 30px #2822140d;--font-serif:"Source Serif 4",Georgia,serif;--font-sans:"Onest",system-ui,sans-serif;--r-card:13px;--r-slide:11px;--r-btn:10px;--r-pill:7px;--r-track:5px}[data-theme=dark]{--bg:#16151a;--bg-2:#1c1b20;--surface:#222127;--surface-2:#2a2931;--ink:#ece8e0;--text-2:#a6a39d;--text-3:#726f6a;--border:#2f2e36;--border-2:#3f3e48;--accent:#7fcab0;--accent-2:#97d8c1;--accent-soft:#1d2a2a;--rail:#2f2e36;--mark:#574d2c;--mark-cur:#9a8338;--shadow:0 1px 2px #00000057,0 14px 38px #0000006b}@media print{.ll-topbar,.ll-footer,.ll-reader-progress,.ll-reader-search,.ll-reader-sidebar,.ll-reader-player,.ll-reader-lightbox,.ll-reader-export,.ll-reader-text-button{display:none!important}body{background:#fff;display:block}.ll-main{max-width:none;padding:0}.ll-reader-layout{display:block}.ll-reader-article{width:100%}.ll-reader-timeline{border-left:none;padding-left:0}.ll-reader-sub:before{display:none}.ll-reader-section-head{margin-left:0}.ll-reader-prose{color:#000}}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false} \ No newline at end of file diff --git a/internal/web/web.go b/internal/web/web.go index 1f55c5f..763e0b9 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -87,6 +87,14 @@ func NewRouter(opts ...Option) http.Handler { } r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(sfs))) + // Правила обхода для ИИ-краулеров и поисковых роботов: публичные и + // ссылочные разделы открыты, служебные — закрыты. + r.Get("/robots.txt", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(robotsTxt)) + }) + // Главная — лендинг сервиса: hero, свежие публичные конспекты, форматы. r.Get("/", func(w http.ResponseWriter, req *http.Request) { var examples []HubCardVM diff --git a/internal/web/web_test.go b/internal/web/web_test.go index 54ce16f..75cf4bb 100644 --- a/internal/web/web_test.go +++ b/internal/web/web_test.go @@ -214,29 +214,177 @@ func TestLayout_HtmxHeaders(t *testing.T) { } // TestVisibilityToggle_SendsTargetValue фиксирует контракт с handleSetVisibility: -// тумблер обязан слать form-поле visibility с целевым (противоположным) значением — -// без hx-vals публикация из UI молча не работает. +// каждая кнопка трёхпозиционного переключателя обязана слать form-поле visibility +// со своим значением — без hx-vals переключение из UI молча не работает. func TestVisibilityToggle_SendsTargetValue(t *testing.T) { - render := func(vm web.LectureCardVM) string { - var b bytes.Buffer - if err := web.LectureCard(vm).Render(context.Background(), &b); err != nil { - t.Fatalf("LectureCard.Render: %v", err) + privateHTML, privateButtons := parseCardVisibility(t, web.LectureCardVM{ID: "x", Status: "ready", Visibility: "private", CanPublish: true}) + if len(privateButtons) != 3 { + t.Fatalf("кнопок переключателя = %d, ожидается 3", len(privateButtons)) + } + for _, visibility := range []string{"private", "unlisted", "public"} { + want := `{"visibility":"` + visibility + `"}` + if got := attrVal(privateButtons[visibility], "hx-vals"); got != want { + t.Errorf("кнопка %s: hx-vals = %q, ожидается %q", visibility, got, want) } - return b.String() } - - private := render(web.LectureCardVM{ID: "x", Status: "ready", Visibility: "private", CanPublish: true}) - if !strings.Contains(private, `{"visibility":"public"}`) && !strings.Contains(private, `{"visibility":"public"}`) { - t.Errorf("личная лекция: hx-vals должен слать visibility=public, получено:\n%s", private) + for _, want := range []string{"Личная", "По ссылке", "Витрина"} { + if !strings.Contains(privateHTML, want) { + t.Errorf("личная лекция: в карточке нет метки %q", want) + } + } + if strings.Contains(privateHTML, "ll-share") { + t.Error("личная карточка не должна содержать кнопку «Скопировать ссылку»") + } + if !strings.Contains(privateHTML, "Опубликовать лекцию на Витрине?") { + t.Error("переход в «Витрина» должен требовать подтверждения") } - public := render(web.LectureCardVM{ID: "x", Status: "ready", Visibility: "public", CanPublish: true}) - if !strings.Contains(public, `{"visibility":"private"}`) && !strings.Contains(public, `{"visibility":"private"}`) { - t.Errorf("публичная лекция: hx-vals должен слать visibility=private, получено:\n%s", public) + unlistedHTML, _ := parseCardVisibility(t, web.LectureCardVM{ID: "x", Status: "ready", Visibility: "unlisted", CanPublish: true}) + if !strings.Contains(unlistedHTML, "ll-share") { + t.Error("unlisted-карточка должна содержать кнопку «Скопировать ссылку»") } - if !strings.Contains(public, "ll-share") { + + publicHTML, publicButtons := parseCardVisibility(t, web.LectureCardVM{ID: "x", Status: "ready", Visibility: "public", CanPublish: true}) + if !strings.Contains(publicHTML, "ll-share") { t.Error("публичная карточка должна содержать кнопку «Скопировать ссылку»") } + if strings.Contains(publicHTML, "Опубликовать лекцию на Витрине?") { + t.Error("уже публичная лекция не должна запрашивать подтверждение публикации") + } + if got := attrVal(publicButtons["public"], "aria-pressed"); got != "true" { + t.Errorf("публичная карточка: aria-pressed = %q, ожидается true", got) + } +} + +// TestVisibilityToggle_ThreeState проверяет семантику 3-позиционного переключателя: +// активная кнопка помечена aria-pressed="true" и классом состояния, а для неготовой +// лекции открытие по ссылке и публикация заблокированы. +func TestVisibilityToggle_ThreeState(t *testing.T) { + tests := []struct { + name string + vm web.LectureCardVM + active string + disabledOn []string + }{ + { + name: "личная", + vm: web.LectureCardVM{ID: "x", Status: "ready", Visibility: "private", CanPublish: true}, + active: "private", + disabledOn: []string{"private"}, + }, + { + name: "по ссылке", + vm: web.LectureCardVM{ID: "x", Status: "ready", Visibility: "unlisted", CanPublish: true}, + active: "unlisted", + disabledOn: []string{"unlisted"}, + }, + { + name: "витрина", + vm: web.LectureCardVM{ID: "x", Status: "ready", Visibility: "public", CanPublish: true}, + active: "public", + disabledOn: []string{"public"}, + }, + { + name: "неготовая лекция", + vm: web.LectureCardVM{ID: "x", Status: "processing", Visibility: "public", CanPublish: false}, + active: "public", + disabledOn: []string{"unlisted", "public"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, buttons := parseCardVisibility(t, tt.vm) + if len(buttons) != 3 { + t.Fatalf("кнопок переключателя = %d, ожидается 3", len(buttons)) + } + disabledSet := make(map[string]bool, len(tt.disabledOn)) + for _, v := range tt.disabledOn { + disabledSet[v] = true + } + for visibility, button := range buttons { + wantPressed := "false" + if visibility == tt.active { + wantPressed = "true" + } + if got := attrVal(button, "aria-pressed"); got != wantPressed { + t.Errorf("%s: aria-pressed = %q, ожидается %q", visibility, got, wantPressed) + } + if visibility == tt.active && !strings.Contains(attrVal(button, "class"), "ll-toggle--"+visibility) { + t.Errorf("активная кнопка %s без класса ll-toggle--%s: %q", visibility, visibility, attrVal(button, "class")) + } + if hasAttr(button, "disabled") != disabledSet[visibility] { + t.Errorf("%s: disabled = %v, ожидается %v", visibility, hasAttr(button, "disabled"), disabledSet[visibility]) + } + } + }) + } +} + +// parseCardVisibility рендерит карточку и возвращает её HTML и кнопки переключателя. +func parseCardVisibility(t *testing.T, vm web.LectureCardVM) (string, map[string]*html.Node) { + t.Helper() + var b bytes.Buffer + if err := web.LectureCard(vm).Render(context.Background(), &b); err != nil { + t.Fatalf("LectureCard.Render: %v", err) + } + doc, err := html.Parse(strings.NewReader(b.String())) + if err != nil { + t.Fatalf("html.Parse: %v", err) + } + return b.String(), visibilityButtons(doc) +} + +// visibilityButtons собирает кнопки переключателя видимости по значению hx-vals. +func visibilityButtons(doc *html.Node) map[string]*html.Node { + result := make(map[string]*html.Node, 3) + var walk func(*html.Node) + walk = func(n *html.Node) { + if n.Type == html.ElementNode && n.DataAtom == atom.Button { + vals := attrVal(n, "hx-vals") + for _, visibility := range []string{"private", "unlisted", "public"} { + if strings.Contains(vals, `"`+visibility+`"`) { + result[visibility] = n + } + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + walk(c) + } + } + walk(doc) + return result +} + +// TestLectureCard_NonReadyPrivateHidesToggle проверяет, что у неготовой личной +// лекции переключателя видимости нет (как и раньше): открывать нечего. +func TestLectureCard_NonReadyPrivateHidesToggle(t *testing.T) { + html := renderLectureCard(t, web.LectureCardVM{ + ID: "lec-1", + Title: "Лекция", + Status: "processing", + StatusLabel: "Обработка", + Visibility: "private", + SourceKind: "audio", + UpdatedAt: "24 июн. 2026", + }) + if strings.Contains(html, "ll-toggle") { + t.Errorf("неготовая приватная карточка не должна показывать переключатель: %s", html) + } +} + +// TestLayout_NoIndex проверяет, что флаг NoIndex добавляет meta robots в , +// а без флага метатег не появляется. +func TestLayout_NoIndex(t *testing.T) { + indexable := renderLayoutWithData(t, web.LayoutData{Title: "Витрина"}) + if strings.Contains(indexable, `name="robots"`) { + t.Error("индексируемая страница не должна содержать meta robots") + } + + noIndex := renderLayoutWithData(t, web.LayoutData{Title: "Лекция по ссылке", NoIndex: true}) + if !strings.Contains(noIndex, ``) { + t.Error("NoIndex должен добавлять meta robots noindex, nofollow в ") + } } // TestRouter_Landing проверяет лендинг на корневом маршруте.